gpt4 book ai didi

Django 在带有隐藏字段的表单中引发错误仍然存​​在问题

转载 作者:行者123 更新时间:2023-12-02 02:24:40 25 4
gpt4 key购买 nike

我正在尝试创建一个应用程序,用户可以在其中互相发送消息。

我正在开发的函数称为read,允许用户阅读他收到的消息。

我的模型按以下方式工作:每条消息都与一个线程相关,这将用于跟踪彼此相关的回复消息。

我的函数通过捕获消息 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}}

最佳答案

首先,我建议您仅使用 form.cleaned_data 来获取提交的数据。

id = form.cleaned_data['hidden_field']

此外,当您的函数参数中已经定义了 id 时,为什么还要从 request.POST 数据中重新分配 id 呢?也许它应该看起来像:

msg_response_id = form.cleaned_data['hidden_field']

然后,您始终需要检查 hidden_​​field 值,并且可以使用自定义的 clean 方法来完成此操作。将 clean_hidden_​​field 方法添加到您的表单中,并且您还应该重写 init 表单方法并传递 idmsg_response_id

您认为:

form = ReplyForm(initial=initial, id=id, msg_response_id=msg_response_id)

和表格:

class ReplyForm(forms.Form):

def __init__(self, *args, **kwargs):
self.id = kwargs.pop('id', None)
self.msg_response_id = kwargs.pop('msg_response_id', None)
super(ReplyForm, self).__init__(*args, **kwargs)

hidden_field = forms.CharField(widget=forms.HiddenInput())

def clean_hidden_field(self):
if self.id and self.msg_response_id and self.id == self.msg_response_id:
# Raise form error, which will appear in your template.
raise forms.ValidationError(_('You can't reply to your own message.'))

关于Django 在带有隐藏字段的表单中引发错误仍然存​​在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com