如何在Django中创建一个传递参数的URL?

时间:2014-12-02 19:46:43

标签: python django

我正在处理注册逻辑,而我似乎无法使参数传入正常工作。我得到的错误是找不到404页面。以前,我还有一个“视图没有返回HttpResponse对象"错误。任何帮助表示赞赏。

这是来自urls.py的我的网址:

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

这是我的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')

我发送的网址字符串如下:

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

所以链接看起来像这样: http://www.example.com/accounts/confirm/4beo8d98fef1cd336a0f239jf4dc7fbe7bad8849a127d847f

2 个答案:

答案 0 :(得分:2)

这里有两个问题:

  1. 从您的模式中移除尾随的/,或将其设为/?,这样它就是可选的。
  2. /d+仅匹配数字,您的链接还包含其他字符。请改为[a-z0-9]+
  3. 完整模式:

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

答案 1 :(得分:0)

从网址末尾删除/

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

或将/添加到您的链接末尾:

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