简体   繁体   中英

How do you make a url that passes a parameter work in Django?

I'm working on registration logic and I can't seem to make the parameter pass in to work properly. The error I get is a 404 page not found. Previously, I also got a “The view didn't return an HttpResponse object" error. Any help is appreciated.

Here is my url from urls.py:

url(r'^accounts/confirm/(?P<activation_key>\d+)/$', 'mysite.views.confirm', name='confirm'),

This is my views.py:

def confirm(request, activation_key):
    if request.user.is_authenticated():
        HttpResponseRedirect('/home')

    user = Hash.objects.filter(hash_key = activation_key)
    if user:
        user = Hash.objects.get(hash_key = activation_key) 
        user_obj = User.objects.get(username= user.username)
        user_obj.is_active = True
        user_obj.save()

    HttpResponseRedirect('/home')

I send the url with a string that looks like:

"Click the link to activate your account http://www.example.com/accounts/confirm/%s" % (obj.username, activation_key)"

So the link looks like this: http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f

You have two issues here:

  1. Remove the trailing / from your pattern, or make it /? so it will be optional.
  2. /d+ will only match digits, and your link also contains other characters. Try [a-z0-9]+ instead.

Complete pattern:

^accounts/confirm/(?P<activation_key>[a-z0-9]+)$

Remove / from end of your url:

url(r'^accounts/confirm/(?P<activation_key>\d+)$', 'mysite.views.confirm', name='confirm'),

or add / to end of your link:

http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM