繁体   English   中英

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

[英]django login decorator and user redirect issues

这是我需要做的。 我有一个名为“卖出”的按钮。 如果用户已登录,则它会执行其正常步骤并允许用户进行销售。 如果用户未登录,则需要重定向至登录页面,并在用户登录后,将登录用户执行的正常步骤重定向至带有用户名和用户名的url,然后以这种“用户名/销售方式”进行销售。

该视图作为经过身份验证的用户运行良好

@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>

现在这很有效,因为我是登录用户,然后以匿名用户的身份在另一个浏览器上尝试使用时,我很快看到匿名用户没有用户名,因此我更改了视图,URL和模板以仅使用用户。 然后工作正常,直到装饰器重定向到登录页面后尝试登录。 登录后的{{next}}网址是绝对路径,即“用户/出售”。 这样做的问题是,使用使用用户而不是用户名的更新视图将其重定向到“ AnonymousUser / sell”。 我认为这与我的观点有关,但有人可以提供帮助。 我需要登录后的重定向为“用户/销售”,就像最近登录的用户一样。

我认为您不必输入用户名,因为当用户登录时,系统现在可以访问其用户名。

@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”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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