Django username in url instead of id

in the mini-virtual community, I have a profile_view function, so I can view the profile of any registered user. The profile view function has as a parameter the identifier of the user to which the profile belongs, so when I want to access the profile of user 2, for example, I call it like this: http://127.0.0.1:8000/accounts/profile_view/2/

My problem is that I would like to have a username in the url and NOT an id. I am trying to change my code as follows, but it does not work. Here is my code:

View:

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,
        'u':u,  
        'up':up, 
        'cv': cv, 
        'ing': following.order_by('-date_initiated'),  
        'er': follower.order_by('-date_follow'),
        'list':blog.order_by('-date'),
        'replies':replies
        }, 
        context_instance=RequestContext(request)) 

and my url:

urlpatterns = patterns('',
                        url(r'^profile_view/(?P<user>\d+)/$', 
                           profile_view,
                           name='profile_view'),

early!

+3
source share
3

, , . , - .

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

url, , :

url(r'^profile_view/(?P<username>\w+)/$', 
                       profile_view,
                       name='profile_view'),
+20

, . .

# accounts/views.py
from django.contrib.auth.models import User
from django.views.generic.detail import DetailView

class UserProfileView(DetailView):
    model = User
    slug_field = "username"
    template_name = "userprofile.html"

# accounts/urls.py
from views import UserProfileView
urlpatterns = patterns('',
    # By user ID
    url(r'^profile/id/(?P<pk>\d+)/$', UserProfileView.as_view()),
    # By username
    url(r'^profile/username/(?P<slug>[\w.@+-]+)/$', UserProfileView.as_view()),
)

, accounts/profile/id/123/, accounts/profile/username/gertvdijk/.

?

  • URL pk slug URL. , ...
  • slug DetailView ( SingleObjectMixin), User.username model = User slug_field = "username". (docs)
  • slug , pk.
+9

Add to the beginning of the file:

from django.shortcuts import get_object_or_404

and replace

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

with

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

where login is the username in the user model.

+2
source

Source: https://habr.com/ru/post/1749365/


All Articles