如果用户已通过身份验证并预加载数据库中的所有信息,则尝试加载某些表单,但我收到此错误,很可能是 forms.py 中出现了问题,但想法是,如果用户已通过身份验证,则他们不应完成该过程输入他们的姓名和电子邮件,他们只需要发送消息。它目前对非注册用户来说就像一个魅力,但我以前从未为注册用户做过这样的事情,所以我被困住了。
forms.py
from django import forms
from django.forms import ModelForm
from .models import Message
class 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.py
from django.db import models
from django.utils import timezone
class 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.py
from django.shortcuts import render, redirect
from .models import Message
from .forms import NonAuthMessage, AuthMessage
def 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)
青春有我
相关分类