匿名用户错误

Anonymous user error

我正在尝试将表单数据保存到匿名用户,但是当我尝试在 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')

如果用户未登录,则request.user为匿名用户。将匿名用户分配给 form.instance.user 没有意义,因为数据库中不存在匿名用户或没有主键。

如何更改代码取决于您希望应用程序如何工作。

如果要允许匿名用户创建服务类型,那么

# if self.request.user.is_authenticated(): # Django < 1.10 
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):
    ...

我认为您不能将 AnonymousUser 用作用户外键的值。

在这种情况下,您应该将 is 保留为 Null。

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
        ...