jph
jph

Reputation: 367

Display username in URL - Django

When I try to display the username in the URL, I get this error:

Reverse for 'account_home' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['/(?P\w+)/$'].

Here is my views.py

@login_required
def account_home(request, username):
    u = MyUser.objects.get(username=username)
    return render(request, "accounts/account_home.html", {})

Here is my urls.py

urlpatterns += patterns('accounts.views',
    # url(r'^account/$', 'account_home', name='account_home'),
    url(r'^/(?P<username>\w+)/$', 'account_home', name='account_home'),
    url(r'^logout/$', 'auth_logout', name='logout'),
    url(r'^login/$', 'auth_login', name='login'),
    url(r'^register/$', 'auth_register', name='register'),
)

This is the code it is trying to render, but can't.enter image description here

Thank you in advance for your help!

Upvotes: 2

Views: 2502

Answers (1)

Selcuk
Selcuk

Reputation: 59164

Short answer: The problem is with your template code. You are not passing the username parameter to your view. Instead of

<a href="{% url 'account_home' %}">Account<a>

try

<a href="{% url 'account_home' user.username %}">Account<a>

Long answer: That being said, you could probably get rid of the username parameter by modifying your view instead. You already have the current user in the request object in your view:

@login_required
def account_home(request):
    u = MyUser.objects.get(username=request.user.username)
    return render(request, "accounts/account_home.html", {})

and remove it from the url definition:

url(r'^$', 'account_home', name='account_home'),

Upvotes: 9

Related Questions