Django 存储匿名用户数据 [英] Django storing anonymous user data

查看:35
本文介绍了Django 存储匿名用户数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 django 模型,它存储来自表单输入的用户和产品数据:

I have a django model which stores user and product data from a form input:

def ProductSelection(request, template_name='product_selection.html'):
    ...
    if user.is_authenticated():
        user = request.user
    else:
        # deal with anonymous user info
    project = Project.objects.create(
        user=user,
        product=form.cleaned_data["product"],
        quantity=form.cleaned_data["product_quantity"],
    )

当然这对于经过身份验证的用户来说很好,但我也希望能够存储匿名用户项目,如果可能的话,在他们最终注册和身份验证时将它们与用户关联起来.

Of course this is fine for authenticated users, but I also want to be able to store anonymous user projects, and if possible, associate them with the user when they eventually register and authenticate.

我的想法是创建具有 name = some_variable 的匿名用户(时间戳与随机散列连接?),然后将该用户名保存在会话数据中.如果我确保该会话变量(如果存在)用于记录该用户的所有项目活动,那么我应该能够在用户注册时使用其真实凭据更新项目.

My idea is to create anonymous user with name = some_variable (timestamp concatenated with a random hash?), then save that username in session data. If I ensure that that session variable, if exists, is used to record all projects activity of that user, I should be able to update the projects with the user's real credentials when they register.

这是否过于复杂和脆弱?我是否冒着不必要地保存数千行数据的风险?这个常见问题的最佳方法是什么?

Is this overly complicated and brittle? Do I risk saving thousands of rows of data unnecessarily? What would be the optimal approach for this common issue?

对此的任何指导将不胜感激.

Any guidance on this would be much appreciated.

推荐答案

您可以使用 Django 的会话框架 用于存储匿名用户数据.

You can use Django's session framework to store anonymous user data.

然后,您可以向 Project 模型添加一个字段,以保存匿名用户的 session_key 值,

You can then either add a field to your Project model to hold the session_key value for anonymous users,

project = Project.objects.create(
    user=request.user,  # can be anonymous user
    session=request.session.session_key,
    product=form.cleaned_data["product"],
    quantity=form.cleaned_data["product_quantity"])

或者简单地存储一个 Project 实例在会话中将拥有的所有数据

or simply store all the data a Project instance would have in the session

if user.is_authenticated():
    project = Project.objects.create(
        user=request.user,
        product=form.cleaned_data["product"],
        quantity=form.cleaned_data["product_quantity"])
else:
    # deal with anonymous user info
    request.session['project'] = {
        "product": form.cleaned_data["product"],
        "quantity": form.cleaned_Data["product_quantity"]}

您可以稍后在创建适当的用户时从会话中检索数据.

You can retrieve the data from the session later, when creating a proper user.

这篇关于Django 存储匿名用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆