sarchi-xo
sarchi-xo

Reputation: 246

Using the user_username instead of user_id to access a user profile

How can I access a model object by their username instead of their id or how can I convert the username into an id that can then be used to access a model object?

I have a view like below where the argument that is being passed in is the user_username:

views.py

def profile_page(request, user_username):
    form = FollowUserForm(request)
    profile = Profile.objects.get(user=user_username)
    return render(request, "network/profilePage.html", {
        "form": form,
        "profile": profile
    })

I know that we can't put the user equal to user_username so is there a way of converting the username somehow into an id which I can then use to access the relevant Profile object? I'm doing it like this because in my urls.py I want the url to show the user's username rather than just a number id.

urls.py

path("profile/<str:user_username>", views.profile_page, name="profile"),

Edited to add:

models.py

class User(AbstractUser):
    pass


class Profile(models.Model):
    user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True)
    friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False)

Upvotes: 1

Views: 617

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can filter on the username of the user with:

from django.shortcuts import get_object_or_404

def profile_page(request, user_username):
    profile = get_object_or_404(Profile, user__username=user_username)
    form = FollowUserForm(request)
    return render(request, 'network/profilePage.html', {
        'form': form,
        'profile': profile
    })

Note: It is often better to use get_object_or_404(…) [Django-doc], then to use .get(…) [Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using .get(…) will result in a HTTP 500 Server Error.

Upvotes: 1

Related Questions