如果用户已通过身份验证并预加载数据库中的所有信息,则尝试加载某些表单,但我收到此错误,很可能是 forms.py 中出现了问题,但想法是,如果用户已通过身份验证,则他们不应完成该过程输入他们的姓名和电子邮件,他们只需要发送消息。它目前对非注册用户来说就像一个魅力,但我以前从未为注册用户做过这样的事情,所以我被困住了。forms.pyfrom django import formsfrom django.forms import ModelFormfrom .models import Messageclass NonAuthMessage(forms.ModelForm): class Meta: model = Message fields = "__all__"class AuthMessage(forms.ModelForm): def __init__(self): self.name = user.request.username self.email = user.request.email class Meta: model = Message fields = ["message"]models.pyfrom django.db import modelsfrom django.utils import timezoneclass Message(models.Model): name = models.CharField(max_length=50) email = models.EmailField() message = models.TextField(max_length=3000) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ['-date_posted',]views.pyfrom django.shortcuts import render, redirectfrom .models import Messagefrom .forms import NonAuthMessage, AuthMessagedef contact(request): formAuth = AuthMessage() formNonAuth = NonAuthMessage() mess = Message.objects.all() if request.user.is_authenticated: if request.method == "POST": form = AuthMessage(request.POST) if form.is_valid(): form.save() return redirect('contact') messages.success(request, 'Message sent to Alex!') else: if request.method =="POST": form = NonAuthMessage(request.POST) if form.is_valid(): form.save() return redirect('contact') messages.success(request, 'Message sent to Alex!') context = {'formAuth': formAuth, 'formNonAuth': formNonAuth, 'mess': mess} return render(request, 'contact/contact.html', context)
1 回答
青春有我
TA贡献1784条经验 获得超8个赞
尝试将所需的用户信息直接放在视图中而不是表单中:
if request.user.is_authenticated:
if request.method == "POST":
form = AuthMessage(request.POST)
if form.is_valid():
authmess = form.save(commit=False)
authmess.name = request.user.first_name
authmess.email = request.user.email
authmess.save()
messages.success(request, 'Message sent to Alex!')
return redirect('contact')
添加回答
举报
0/150
提交
取消