我正在尝试创建一个用户可以相互发送消息的应用程序。
我正在处理的功能称为读取,允许用户阅读他收到的消息。
我的模型的工作方式如下:每条消息都与一个线程相关,这将用于跟踪彼此相关的回复消息。
我的函数通过捕获消息 ID 并过滤与消息线程相关的所有消息来工作。然后我将使用当前消息 id 填充一个表单并允许用户回复该表单。
当用户通过 POST 提交时,我将检索隐藏的消息 id 并使用检索到的消息 id 线程创建一条新消息。
问题:当超出字符限制并使用引发的错误填充当前消息 ID 时,我无法弄清楚如何在这种情况下引发错误。有人可以帮助我吗?
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30, blank=True)
def __unicode__(self):
return self.user.username
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)
def __unicode__(self):
return self.body
意见:
@login_required
def read(request,id):
try:
messages = Message.objects.get(pk=id,recipient=request.user)
except Message.DoesNotExist:
return HttpResponseRedirect(reverse('world:Display'))
messages.read = True
messages.save()
if request.method =='POST':
form = ReplyForm(request.POST)
if form.is_valid():
id = request.POST.get('hidden_field', False)
try:
messages = Message.objects.get(pk=id ,recipient=request.user,sentmessage=True,draft=False)
except Message.DoesNotExist or Thread.DOesNotExist:
return HttpResponseRedirect(reverse('world:LoginRequest'))
person = Person.objects.get(user=messages.user)
if person.inbox == "D":
return HttpResponseRedirect(reverse('world:message'))
body = form.cleaned_data['body']
Message.objects.create(user=request.user,recipient=messages.user,body=body,thread=messages.thread,sentmessage=True,read=False)
return HttpResponseRedirect(reverse('world:message'))
message = Message.objects.filter(thread=messages.thread ).filter(created__lte=messages.created)
person = Person.objects.get(user=request.user)
initial = {}
initial.update({'hidden_field': messages.id})
form = ReplyForm(initial=initial)
return render(request,'read.html',{'messages':messages,'form':form,'message':message,'person':person})
形式
class ReplyForm(forms.Form):
body = forms.CharField(widget=forms.Textarea,required=False,max_length=555)
hidden_field = forms.CharField(widget=forms.HiddenInput())
模板:
<div class="box22">
{% for m in message %}
<div class="wrapper">
<div class="user">{{m.user.username}} </div>
<div class="message">{{m.body}}</div>
</div>
{% endfor %}
<form method="POST" >{% csrf_token %}
{{form.body}}{{form.hidden_field}}
<input type = "submit" value= "send" class="sen"/>
</form>
{{form.body.errors}}