我在Django中进行表单验证时遇到问题,我真的不知道问题是什么。它是一个消息传递应用程序,我试图让用户发送消息自动填充登录的用户。我已经尝试了很多东西,但没有一个工作。任何帮助,将不胜感激。这是我的models.py :(任何评论的内容都是之前尝试的解决方案)
class Message(models.Model):
#readonly_fields = 'sender'
sender = models.ForeignKey(User, related_name="send", default=User)
recipient = models.ForeignKey(User, related_name="receive", default=None)
message_subject = models.CharField("Subject", max_length=25)
message_text = models.TextField("Message")
message_time_created = models.DateTimeField(auto_now_add=True)
urgent = models.CharField(max_length=3, choices=URGENCY)
#field to make message urgent or not
def __str__(self):
return self.message_subject
这是用于创建新消息的views.py :(任何已注释掉的内容都是之前尝试的解决方案)(还包括粘贴时不会显示的@ login_required标记)
def newMessage(request, user):
user = get_object_or_404(User, pk=user)
#form = MessageForm(request.POST or None, initial={'sender':request.POST.get('username')})
if request.method == 'POST':
#instance = Message(sender=request.user)
#form = MessageForm(instance=instance)
#form = MessageForm(initial={'sender':request.user})
form = MessageForm(request.POST)
if form.is_valid():
new_instance = form.save()
temp = Event(activity='\n' + new_instance.sender.get_full_name() + " sent a message to " + new_instance.recipient.get_full_name())
temp.save()
try:
target = Patient.objects.get(user=user)
return HttpResponseRedirect('/patients/%s/' % target.id)
except Exception as e:
try:
target = Nurse.objects.get(user=user)
return HttpResponseRedirect('/nurses/%s/' % target.id)
except Exception as e:
try:
target = Doctor.objects.get(user=user)
return HttpResponseRedirect('/doctors/%s/' % target.id)
except Exception as e:
try:
target = HospitalAdmin.objects.get(user=user)
return HttpResponseRedirect('/hospitalAdmins/%s/' % target.id)
except Exception as e:
return render(request, "main_site/newMessagePrompt.html",
{ "form" : form, })
elif request.method == 'GET':
form = MessageForm()
return render(request, "main_site/newMessagePrompt.html",
{ "form" : form, })
以下是表格:(任何评论的内容都是之前尝试的解决方案)
class MessageForm(ModelForm):
#readonly_fields = 'sender'
urgent = forms.ChoiceField(choices=URGENCY, required=True)
class Meta:
model = Message
#widgets = {'sender': forms.HiddenInput()}
exclude =['message_time_created']
目前,在模型中为发件人提供default = User,它会自动填充登录的用户,如果您尝试发送邮件,它将起作用。但是,仍然可以编辑该字段,这不是故意的。如果我尝试在model.py中使字段editable = False,然后尝试发送消息,则会出错。如果我尝试其他方法来隐藏它,例如表单中的HiddenInput,表单将无法验证。尝试使用实例变量时发生了类似的结果。我还尝试将sender字段设置为只读字段,但还没有成功实现它以查看它是否可行。我真的无法弄清楚如何解决这个问题。任何人都可以帮我解决这个问题吗?