python - django 查看 session ID - 未登录的用户缺少

标签 python django django-sessions

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

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

但是,当我尝试使用 session ID 时,它没有返回任何结果。我不确定为什么数据丢失了? (根据文档, session 在应用程序和中间件中具有默认的 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')

最佳答案

如果 session 字典中已经有数据集,则 session key 将存在。登录用户有一个 session key ,因为 Django 默认在 session 中存储与身份验证相关的数据,因此始终会分配一个 key 。

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

关于python - django 查看 session ID - 未登录的用户缺少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280214/

相关文章:

python - 模型编译部分的 RMSprop 优化器,在 keras 中不起作用

python - Django - 获取存储在外键中的对象

session - 用于 Django 中缓存 session 的 Redis 复制

Django/Auth : logout clears the session data?

django - 为什么 django 在数据库中创建许多 session 对象?

python - 在Python中,有什么理由比字符串切片更喜欢startswith吗?

python - 辅助轴和日期 x 轴错误

python - 具有 Python Cmd 类的面向行命令解释器的多种模式

python - Django 创建新用户失败

python - 自定义 user_logged_in 信号在 django 更新 last_login 之前