0

I am trying to include the username in the url, but I can no longer logout without getting this error:

enter image description here

It traces back to this line in views.py:

u = MyUser.objects.get(username=username)

Any idea what I'm doing wrong?

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", {})

def auth_logout(request):
logout(request)
return HttpResponseRedirect('/')

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'),
)

Thanks guys!

jph
  • 347
  • 2
  • 7
  • 18
  • Have you tried changing the username parameter to something like "user" so that it doesn't clash when you define u? – deweyredman Feb 18 '15 at 23:22
  • 1
    What does your `urls.py` look like? It looks like you're trying to use the `account_home` view in a context in which the username is missing or incorrect, probably as a result of redirecting to `/` after logging out. – Peter DeGlopper Feb 18 '15 at 23:30
  • I am redirecting to "/" after logging out. Where should I have it redirected to? @PeterDeGlopper I added my urls.py as well – jph Feb 18 '15 at 23:33

2 Answers2

2

Django uses the first view that matches your query. As your account_home view is the first view in the list, and it matches /logout/, /login/ and /register/, all these url's are directed at the account_home view. As you don't have a user with those names, you get that error.

To fix it, the very least you need to do is move the account_home view to the end of the list. You probably also want to add some code that properly handles non-existent users, e.g. get_object_or_404

knbk
  • 52,111
  • 9
  • 124
  • 122
  • Obviously we agree on the cause, and `get_object_or_404` is a good practice - although in this case it would have left the user with a different problem. – Peter DeGlopper Feb 18 '15 at 23:46
0

The problem is with your url matching regular expressions. Django uses the first matching pattern, and /logout/ matches r'^(?P<username>[\w.@+-]+)/$' - it's looking for a user named logout.

You can either reorder your url patterns to put the username pattern at the end, or (a better solution) put something unambiguous in your pattern like r'^/account/(?P<username>[\w.@+-]+)/$'.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83