我正在尝试将表单数据保存到匿名用户,但是当我尝试在CreateView中保存一些表单数据时出现以下错误“。我不清楚问题是什么?
ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x11126bc18>>": "EUser.user" must be a "User" instance.
型号:
class EUser(models.Model):
online_account = models.BooleanField()
supplier1 = models.OneToOneField(SupplierAccount)
supplier2 = models.OneToOneField(SupplierAccount)
supplier3 = models.OneToOneField(SupplierAccount)
address = models.OneToOneField(Address)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
class SupplierAccount(models.Model):
supplier = models.ForeignKey(Supplier)
username = models.CharField(max_length=255)
password = models.CharField(max_length=255)
形式:
class ServiceTypeForm(forms.ModelForm):
# BOOL_CHOICES = ((False, 'No'), (True, 'Yes'))
# online_account = forms.BooleanField(widget=forms.RadioSelect(choices=BOOL_CHOICES))
def __init__(self, *args, **kwargs):
super(ServiceTypeForm, self).__init__(*args, **kwargs)
self.fields['service_type'].initial = 'D'
class Meta:
model = EUser
fields = ('service_type', 'online_account')
查看:
class ServiceTypeView(CreateView):
form_class = ServiceTypeForm
template_name = "standard_form.html"
success_url = '/'
def form_valid(self, form):
form.instance.user = self.request.user
super().form_valid(form)
online_account = form.cleaned_data['online_account']
if online_account:
return redirect('../online')
else:
return redirect('../address')
答案 0 :(得分:3)
如果用户未登录,则request.user
是匿名用户。将匿名用户分配给form.instance.user
是没有意义的,因为匿名用户不存在于数据库中或具有主键。
如何更改代码取决于您希望应用程序如何工作。
如果您想允许匿名用户创建服务类型,那么
if self.request.user.is_authenticated():
form.instance.user = self.request.user
为此,您需要更改用户字段以使其可选。
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
进行此更改后,您需要运行makemigrations
然后migrate
来更新数据库。
另一种选择是将视图限制为登录用户。在Django 1.9+中,您可以使用LoginRequiredMixin
。
from django.contrib.auth.mixins import LoginRequiredMixin
class ServiceTypeView(LoginRequiredMixin, CreateView):
...
答案 1 :(得分:0)
我认为你不能将AnonymousUser用作对象的ForeignKey的值。
在这种情况下你应该保持为空。
class EUser(models.Model):
...
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, default=None)
class ServiceTypeView(CreateView):
...
def form_valid(self, form):
if self.request.user.is_authenticated():
form.instance.user = self.request.user
...