request.session.get('user') returning AnonymousUser when there is a user logged in

Question:

I am somewhat new at this so apologies in advance.

  1. I have run into a problem where I am using Auth0 with a custom db.
  2. I have created a user Profile model with a one-to-one relationship with User
  3. I am trying to allow the user to update their profile using a modelform

Where I am getting stuck is that I am trying to save() the form to a profile instance which is related to the user_id. However, I can’t seem to find a way to get the user_id and when I use

request.user.id

I keep getting back AnonymousUser. – I assume this is because it’s looking at the admin backend to find the user but there is none, the user is only in the session.

I have tried using

request.session.get('user')

and when I do I get back the auth0 user(which include all the userinfo), but there is no user_id which is associated with the user in the db.

So my issue is: How do I get a user_id which relates to the user that is logged in on the session but is in the db so I can store the data against it?

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        null=True,
        on_delete=models.CASCADE,
    )
    name = models.CharField(max_length=255, blank=True)
    bio = models.TextField(max_length=255, blank=True)
    platforms = models.CharField(max_length=255, blank=True)
    profile_url = models.URLField(max_length=255, blank=True)

    def __str__(self):
        return self.name

forms.py

from django import forms
from django.forms import ModelForm
from requests import request
from .models import Profile
from django.contrib.auth.models import User

class ProfileForm(ModelForm):
    user = forms.CharField()
    name = forms.CharField()
    bio = forms.CharField(widget=forms.TextInput)
    choices = [('1', 'Option1'), ('2', 'Option2'), ('3', 'Option3'), ('4', 'Option4'), ('5', 'Option5')]
    platforms = forms.ChoiceField(widget=forms.Select, choices=choices)
    profile_url = forms.URLField()
    class Meta:
        model = Profile
        fields = ['user','name','bio','platforms','profile_url']

views.py


def updateProfile(request):
    form = forms.ProfileForm()
    profile = request.session.get('user')
    if request.method == 'POST':
        try:
            form = forms.ProfileForm(request.POST, instance=profile)
        except:
            form = forms.ProfileForm(request.POST)
        if form.is_valid():
            form.save()
            return render(
                request,
                "update_profile.html",
                context={
                    "form":form,
                    "session": request.session.get("user"),
                    "pretty": json.dumps(request.session.get("user"), indent=4),
                },
            )
        else:
            print(form.errors.as_data())
    return render(
    request,
    "update_profile.html",
    context={
        "form":form,
        "session": request.session.get("user"),
        "pretty": json.dumps(request.session.get("user"), indent=4),
    },
)
update_profile.html

...form...
                <label for="brand" class="">Input your profile URL</label>
                **{% render_field form.user type="number" name="user" id="user" value=request.user.id %} ** 
            </div>

        </div>
        <div class="">
            <button type="submit" class="">
                Update Profile
            </button>

urls.py


urlpatterns = [
    path("update-profile", views.updateProfile, name="update-profile")
]

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
    
Asked By: Rno

||

Answers:

There is a django.contrib.auth.models.User object attached to the request. You can access it in a view via request.user. You must have the auth middleware installed, though.

def view(request):
    if request.user.is_authenticated:
        user = request.user
        print(user)
        # do something with user
Answered By: Awon Ali

So finally what worked for me in this instance was to use the following:

Because a user has a Profile associated, I needed to first get the user from the User object using their email and then use that user to access the instance of the Profile object.

user = User.objects.get(email=email)
user_profile = Profile.objects.get(user=user)
Answered By: Rno