django登录装饰器和用户重定向问题

时间:2013-02-05 04:46:21

标签: python django

这就是我需要做的。我有一个名为sell的按钮。如果用户已登录,则它将执行其正常步骤并允许用户进行销售。如果用户未登录,我需要重定向到登录页面,并在用户登录后,重定向正常步骤,登录用户将使用用户用户名的ia url并按照“username / sell”销售。< / p>

这是一个可以作为经过身份验证的用户正常使用的视图

@login_required()
def UserSell(request,username):

    thegigform=GigForm()
    theuser=User.objects.get(username=username)
    if request.method=='POST':
         gigform=GigForm(request.POST,request.FILES)
          if gigform.is_valid():
        gigform.title=gigform.cleaned_data['title']
        gigform.description=gigform.cleaned_data['description']
        gigform.more_info=gigform.cleaned_data['more_info']
        gigform.time_for_completion=gigform.cleaned_data['time_for_completion']
        #need to change this, shouldnt allow any size image to be uploaded
        gigform.gig_image=gigform.cleaned_data['gig_image']
        #commit=False doesnt save to database so that I can add the current user to the gig
        finalgigform=gigform.save(commit=False)
        finalgigform.from_user=theuser
        finalgigform.save()
        return HttpResponseRedirect('done')

else:
    gigform=GigForm()
context=RequestContext(request)
return render_to_response('sell.html',{'theuser':theuser,'thegigform':gigform},context_instance=context)

这是网址

url(r'^(?P<username>\w+)/sell$','gigs.views.UserSell', name='sell'),

然后是模板

<a href="{% url sell user.username %}"><button type="button">Start Selling!</button></a>

现在这很好用,因为我是一个登录用户,然后当我在另一个浏览器上作为匿名用户尝试它时,我很快就看到一个匿名用户没有用户名所以我更改了视图,网址和模板仅使用用户。然后,只有在装饰器重定向到登录页面后尝试登录时才能正常工作。登录后的{{next}}网址是'user / sell'的绝对路径。问题在于使用使用用户而不是用户名的更新视图会重定向到“AnonymousUser / sell”。我认为这是我的观点的问题,但有人可以帮忙。登录后我需要重定向为“用户/销售”,如最近登录的用户。

1 个答案:

答案 0 :(得分:0)

我认为您不需要用户名,因为当用户登录时,系统现在可以访问他们的用户名。

@login_required()
def UserSell(request):
    ..........

    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('app_name:login'))
    else:
        context=RequestContext(request)
        return render_to_response('sell.html',{'theuser':request.user,'thegigform':gigform},context_instance=context)

如果要显示用户只需输入“request.user”或“request.user.username”