django username in url, instead of id

django urls path
django url parameters in template
django url pass parameter to view
django get url parameters
django optional url parameter
django url multiple parameters
django url tag
django wildcard url

in a mini virtual community, i have a profile_view function, so that i can view the profile of any registered user. The profile view function has as a parameter the id of the user wich the profile belongs to, so that when i want to access the profile of user 2 for example, i call it like that:

My problem is that i would like to have the username in the url, and NOT the id. I try to modify my code as follows, but it doesn't work still. Here is my code:


def profile_view(request, user):
        u = User.objects.get(pk=user)
        up = UserProfile.objects.get(created_by = u)
        cv = UserProfile.objects.filter(created_by = User.objects.get(pk=user))
        blog = New.objects.filter(created_by = u) 
        replies = Reply.objects.filter(reply_to = blog)
        vote = Vote.objects.filter(voted=blog)
        following = Relations.objects.filter(initiated_by = u)
        follower = Relations.objects.filter(follow = u)
    return render_to_response('profile/publicProfile.html', {
        'vote': vote,
        'cv': cv, 
        'ing': following.order_by('-date_initiated'),  
        'er': follower.order_by('-date_follow'),

and my url:

urlpatterns = patterns('',

thanks in advance!

You don't show what you have tried, or where you are having trouble. This is fairly simple, after all - just pass a username string to the function instead of an integer, and look up based on that.

def profile_view(request, username):
    u = User.objects.get(username=username)

and modify your url to allow strings rather than integers:


Django Class Based Views: How to use username instead of ID to , from django.conf.urls import patterns, include, url from userprofiles.views import UserDetailView Only the User object is present in the context. Use the reverse relationship to access the profile from the User model: I am trying to access detail view. Previous i used id in url and it was working correctly. Now my condition has changed and instead of id, I want to add place_id in url. For that i used &lt;str:pla

URL dispatcher | Django documentation, You can use Django's URL routing to create easy to read URLs that can keep up with content changes. blog.asp?post=12 (if you were running ASP… ahem) and the script you're running there will pull up the blog post with row ID 12. It works, but it's ugly and not terribly user friendly. Instead of the usual slug, like this:. Removing the username field. Making the email field required and unique. Telling Django that you are going to use the email field as the USERNAME_FIELD. Removing the email field from the REQUIRED_FIELDS settings (it is automatically included as USERNAME_FIELD). Substitute the default Django User model with yours¶

Add in the top of the file:

from django.shortcuts import get_object_or_404

and replace

u = User.objects.get(pk=user)


u = get_object_or_404(User, <login>=user)

where login is the username field in User model.

Create Human Readable URLs in Django That Don't Break, So I added the "url" to tell Django how to create the URL for a User response (​calling it user-detail and using the username as lookup field). I could also remove the  django-allauth. Django does not come with built-in views, urls, and templates for a sign up page. So while we can roll our own a better approach–and the current default for many professionals–is to use the django-allauth package instead. Install it with Pipenv making sure you’ve used Control+c to stop the local server.


urlpatterns = [
    path('<str:username>/', UserDetailView.as_view(), name='user_detail'),

With class based view.

class UserDetailView(LoginRequiredMixin, DetailView):

    model = User
    slug_field = "username"
    slug_url_kwarg = "username"
    template_name = "account/user_detail.html"

    def get_object(self):

        object = get_object_or_404(User, username=self.kwargs.get("username"))

        # only owner can view his page
        if self.request.user.username == object.username:
            return object
            # redirect to 404 page
            print("you are not the owner!!")

I have tested in Django 2.1.

Username instead of ID for urls in Django Rest Framework, One of the features that I wanted so bad is how Instagram manages URLs the username property from the User model in Django instead of using the id or the  Adding lookup_field in the serializer's Meta class did nothing to change the automatically generated URL nor did it allow me to access the item by manually writing the slug instead of the ID in the URL.

For Django 2.0 and above:

path(‘profile/<username>/, views.profile, name=‘profile’),

How to get users based on usernames in django, to humans (when possible, readable words rather than long ID numbers) from django.urls import path from blog.views import ArticleDetailView when an application provides direct access to objects based on user-supplied input. 'pk':, 'slug': self.slug } return reverse('article-pk-slug-detail',  If there is a current application defined, Django finds and returns the URL resolver for that instance. The current application can be specified with the current_app argument to the reverse() function. The url template tag uses the namespace of the currently resolved view as the current application in a RequestContext.

Generating slugs automatically in Django without packages, For example, PHP allows session identifiers to be passed in the URL (e.g., An attacker who tricks a user into clicking a link with a hard-coded session ID will Instead, store a session ID that maps to session data stored on the back-end. Now let's create a user: Navigate back to the home page of the admin site. Click the Add button next to Users to open the Add user dialogue. Enter an appropriate Username and Password/Password confirmation for your test user. Press SAVE to create the user.

The Definitive Guide to Django: Web Development Done Right, #Add Django site authentication urls (for login, logout, password and a URL parameter name instead of " next " to insert the current absolute  11. How to use a UUID instead of ID as primary key?¶ Whenever we create any new model, there is an ID field attached to it. The ID field’s data type will be Integer by default. To make id field as UUID, there is a new field type UUIDField which was added in django version 1.8+. Example

Django Tutorial Part 8: User authentication and permissions, def viewname(request, user_id): user = User.objects.get(id=user_id) #do something with this user. In class based view, we can get url parameter in kwargs​. from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.shortcuts import get_object_or_404 from myapp.models import BlogPost def user_gains_perms (request, user_id): user = get_object_or_404 (User, pk = user_id) # any permission check will cache the current set of permissions user. has_perm ('myapp.change_blogpost') content_type = ContentType. objects. get_for_model (BlogPost) permission = Permission. objects. get

  • based on what I see in django/contrib/auth/ I think a better regex to use to grab the username is (?P<username>[\w.@+-]+)
  • What if username is an email and you don't want this info to be public? You could use user first and last name, but this could be duplicated, so I think we should add an ID or a hash on the ID.
  • What would happen if the username had any of .@+ as these are not valid characters in a slug?
  • How do you do this in the case of extends User to UserProfile (you know to get more fields for a user). The User model has the 'username' field but the UserProfile model has the customize fields that I wan to show too.
  • @RicardoGonzales That's pretty straightforward... change the model and the slug_field. Works with every Django model, this recipe, not just with Users.
  • i've replaced just as you said, and it says i have a Syntax error at the line "u = User.objects.get(<login>=user) "
  • Replace login with the name of the field that's user name. I don't know how it's called there. Also look at the other answer and fix the url.