'AnonymousUser'对象没有属性'company'



问候,我正试图将一家名为CharField的新公司添加到用户表单中,但即使填写了字段,数据也不会保存。。。我尝试了以下内容,但没有成功,因为我在标题中出现了错误。

views.py

def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user_frm = form.save(commit = False)
user_frm.company = request.user.company
user_frm.save()
username = form.cleaned_data.get('username')
messages.success(request, f"Registration Complete! User: {username}")
username = form.cleaned_data.get('username')
login(request, user_frm)

return redirect("main:homepage")

else:
for msg in form.error_messages:
messages.error(request, f"{msg}:{form.error_messages[msg]}")
return render(request = request,
template_name = "main/register.html",
context={"form":form})    

form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})

forms.py

class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
company = forms.CharField( max_length= 500)

class Meta:
model = User
fields = ("username", "email", "company", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.company = self.cleaned_data["company"]
if commit:
user.save()
return user

试试这个:型号.py

from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
nickname = models.CharField("昵称", max_length=20, null=True, blank=True)
company = models.CharField(max_length=200, null=True, blank=True)
class Meta:
verbose_name = verbose_name_plural = "个人信息"
def __str__(self):
return self.nickname or self.user.username

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance, created, **kwargs):
"""创建user的同时自动创建profile并与之关联"""
if created:
Profile.objects.create(user=instance)

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_user_profile(sender, instance, **kwargs):
"""保存user的同时也保存对应的profile"""
instance.profile.save()

views.py

def register(request):
form_class = NewUserForm
if request.method == "POST":
form = form_class(request.POST)
if form.is_valid():
user = form.save()
messages.success(request, f"Registration Complete! User: {user.username}")
login(request, user)
return redirect("main:homepage")
else:
form = form_class()
return render(request, "main/register.html", {"form":form})

forms.py

class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
company = forms.CharField(max_length= 500)
def save(self, commit=True):               
if not commit:
return super().save(commit=commit)
company = self.cleaned_data.pop("company", None)
user = super().save()
user.profile.company = company
user.profile.save()
return user

class Meta:
model = User
fields = ("username", "email", "company", "password1", "password2")

使用以下方法解决:

def update_user_data(user):
Profile_Reg.objects.update_or_create(user=user, defaults={'company': user.company,})

def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.company = form.cleaned_data.get('company')
update_user_data(user)
user.save()
raw_password = form.cleaned_data.get('password1')
username = form.cleaned_data.get('username')
messages.success(request, f"Registration Complete! User: {username}")
#breakpoint()
#user = authenticate(username=user.username, password=raw_password)
#breakpoint()
login(request, user)

return redirect("main:homepage")

else:
for msg in form.error_messages:
messages.error(request, f"{msg}:{form.error_messages[msg]}")
return render(request = request,
template_name = "main/register.html",
context={"form":form})    
form = NewUserForm
return render(request,
"main/register.html",
context={"form":form})

其中Profile_Reg是一个模型:

class Profile_Reg(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
company = models.CharField(max_length=5000)
def __str__(self):
return str(self.user)

相关内容

  • 没有找到相关文章

最新更新