django 查看会话 ID - 未登录的用户缺少

django view Session ID -missing for user not logged in

在我当前的项目中,我希望用户无需先注册即可填写表格(让他们更有可能使用该服务)。

在下面的视图中,我尝试使用表单数据保存注册用户,或者如果用户未注册,则将会话 ID 保存为临时用户 ID。

然而,当我尝试使用会话 ID 时,它 returns none。我不确定为什么数据丢失了? (根据文档,会话在应用程序和中间件中具有默认的 django 设置)。请注意,当用户登录时,它似乎有一个用户 ID,但当没有用户登录时则没有。

查看:

class ServiceTypeView(CreateView):
    form_class = ServiceTypeForm
    template_name = "standard_form.html"
    success_url = '/'

    def form_valid(self, form):
        if self.request.user.is_authenticated():
            form.instance.user = self.request.user
        else:
            form.instance.temp_user = self.request.session.session_key
        super().form_valid(form)
        online_account = form.cleaned_data['online_account']
        if online_account:
            return redirect('../online')
        else:
            return redirect('../address')

型号:

class EUser(models.Model):

    supplier1 = models.OneToOneField(SupplierAccount)
    supplier2 = models.OneToOneField(SupplierAccount)
    supplier3 = models.OneToOneField(SupplierAccount)
    online_account = models.BooleanField()
    address = models.OneToOneField(Address, null=True)
    temp_user = models.CharField(max_length=255, null=True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, default=None)


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')

如果会话字典中已经有数据集,会话密钥就会存在。登录用户有一个会话密钥,因为 Django 默认在会话中存储与身份验证相关的数据,因此总是会分配一个密钥。

您可以通过在尝试获取密钥之前将一些数据扔到会话存储中来确保密钥始终存在。