Django storing anonymous user data

前端 未结 2 2033
广开言路
广开言路 2020-12-23 16:59

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

def ProductSelection(request, template_name=\'product_selection.html\'):
    ...
         


        
2条回答
  •  臣服心动
    2020-12-23 17:27

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

    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"])
    

    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.

提交回复
热议问题