我有一个允许用户互相发送消息的应用程序。
我正在处理的当前函数获取消息 id 并在表单中填充消息对象。它就像一个草稿消息,然后它将允许用户编辑消息表单并发送它。
我有一个名为 person 的 User 模型,它有一个名为 inbox 的属性。此属性确定用户是否希望激活或停用他的收件箱
我遇到的问题是。如果用户停用他的收件箱,我的名为 draftform 的表单不会引发错误。但如果该字段丢失或用户不存在,它确实会引发错误
我假设他们是我如何在表单和 views.py 中传递 request.user 的问题。有人可以帮助我吗
视图.py
class Person(models.Model):
inbox = (
('A', 'Activate'),
('D', 'Deactivate'),
('F', 'Permit To Friends Only'),
)
user = models.ForeignKey(User)
inbox = models.CharField(max_length=1, choices=inbox ,default='A')
class Thread(models.Model):
subject = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(User)
class Message(models.Model):
user = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
created = models.DateTimeField(auto_now_add=True)
body = models.CharField(max_length=1000)
read = models.BooleanField(default=False)
sentmessage = models.BooleanField(default=False)
thread = models.ForeignKey(Thread)
draft = models.BooleanField(default=False)
意见
@login_required
def ReadDraft(request,id):
try:
messages = Message.objects.get(pk=id,recipient=request.user)
except Message.DoesNotExist:
return HttpResponseRedirect(reverse('world:Display'))
thread = Thread.objects.get(message=messages)
initial = {}
initial.update({'hidden_field': messages.id})
draft = DraftForm(request,instance=messages,initial=initial)
thread = ThreadForm(instance=thread)
person = Person.objects.get(user=request.user)
if request.method =='POST':
id = request.POST.get('hidden_field', False)
form = ThreadForm(request.POST)
forms = DraftForm(request,request.POST)
if form.is_valid() and forms.is_valid():
m = Message.objects.get(pk=id,)
recipient = forms.cleaned_data['recipient']
subject = form.cleaned_data['subject']
body = forms.cleaned_data['body']
person = Person.objects.get(user=request.user)
m.user =request.user
m.recipient = recipient
m.body = body
m.draft = False
m.sentmessage = True
m.save()
return HttpResponseRedirect(reverse('world:message'))
else:
ctx = {'DraftForm': forms, 'ThreadForm': form,'person':person}
return render(request, 'create.html', ctx)
return render(request,'create.html',{'DraftForm':draft,'ThreadForm':thread,'person':person})
表格.py
class DraftForm(forms.ModelForm):
recipient = forms.CharField(required=True,max_length=51)
body = forms.CharField(widget=forms.Textarea,required=True,max_length=51)
hidden_field = forms.CharField(widget=forms.HiddenInput())
def __init__(self, request, *args, **kwargs):
self.request = request
super(DraftForm, self).__init__(*args, **kwargs)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
person = Person.objects.get(user=self.request.user)
if person.inbox == "D":
raise forms.ValidationError("You have deactivated your inbox , Please enable it at profile settings")
if recipient:
try:
recipient = User.objects.get(username=recipient)
except User.DoesNotExist:
raise forms.ValidationError("This username does not exist")
return recipient
class Meta:
model = Message
fields = ('body',)
def clean_recipient(self):
recipient = self.cleaned_data['recipient']
try:
recipient = User.objects.get(username=recipient)
except User.DoesNotExist:
raise forms.ValidationError("This username does not exist")
return recipient
class ThreadForm(forms.ModelForm):
class Meta:
model = Thread
fields = ('subject',)
创建.html
{% if DraftForm and ThreadForm %}
<form method="POST" >{% csrf_token %}
{{DraftForm.recipient}}
{{ThreadForm.subject}}
{{DraftForm.body}}
{{DraftForm.hidden_field}}
<input type = "submit" value= "send" class="save" id="send" />
</form>
{% endif %}
{{ThreadForm.subject.errors}}
{{DraftForm.recipient.errors}}
{{DraftForm.body.errors}}