django中的自定义注册重定向

时间:2016-04-18 15:48:28

标签: python django django-registration django-users

我已经制作了一份登记表。当用户注册时,他们应该被重定向到不同的URL,以便使用不同的视图。

我的view.py

def register(request):
    if request.method=='POST':
        user_form=UserRegistrationForm(request.POST)
        if user_form.is_valid():
            new_user=user_form.save(commit=False)
            new_user.set_password(
                                  user_form.cleaned_data['password'])
            new_user.save()
            company=Company.objects.create(user=new_user)
            new_user = authenticate(username=user_form.cleaned_data['username'],
                                    password=user_form.cleaned_data['password2'],
                                    )
            login(request, new_user)
            return render(request,'account/register_done.html',{'new_user':new_user})
    else:
        user_form=UserRegistrationForm()
    return render(request,'account/register.html',{'user_form':user_form})

urls.py

urlpatterns = [
               #url(r'^login/$',views.user_login,name='login'),
               url(r'^login/$','django.contrib.auth.views.login',name='login'),
               url(r'^logout/$','django.contrib.auth.views.logout',name='logout'),
               url(r'^logout_then_login/$','django.contrib.auth.views.logout_then_login',name='logout_then_login'),
               url(r'^$',views.dashboard,name='dashboard'),
               url(r'^register/$',views.register,name='register'),
               url(r'^addcompany/$',views.companyadd,name='companyadd'),
               url(r'^addcompanyreg/$',views.companyaddreg,name='companyaddreg'),
               #url(r'^createinvoice/$',views.createinvoice,name='createinvoice'),
               url(r'^createreceivable/$',views.createreceivables,name='createreceivable'),
               ]

当用户注册时,应将其重定向到

url(r'^addcompanyreg/$',views.companyaddreg,name='companyaddreg'),

请指导。

1 个答案:

答案 0 :(得分:2)

在处理POST请求后,只需执行重定向,而不是重新呈现表单:

from django.core.urlresolvers import reverse
....

if user_form.is_valid():
    ....
    return HttpResponseRedirect(reverse('companyaddreg'))
    #return render(request,'account/register_done.html',{'new_user':new_user})