我是Django的新手并编写了登录/注册程序。
目前,点击提交按钮登录后,我将导航到页面www.example.com/login
。同样,当我尝试注销时,注销成功,URL为www.example.com/logout
。注册成功后,虽然www.example.com/register
和register
函数使用相同的模板,但网址为login
。我知道这是因为我以这种方式修改了urls.py
中的网址。
无论用户是否登录,注册或注销,我都希望保持网址相同(www.example.com
)。我怎么能这样做?
这是我的urls.py
文件:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'website.views.home', name='home' ),
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', 'website.views.user_login'),
url(r'^register/$', 'website.views.user_register'),
url(r'^logout/$', 'website.views.user_logout'),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
我的views.py
档案:http://dpaste.com/1196312/
答案 0 :(得分:1)
看看django-multiurl。此程序包允许对不同的视图使用相同的URL。
我认为,在您的情况下,您可能需要创建一个额外的视图,用于在GET请求上呈现登录和注册表单。
以下是如何入门:
urls.py:
from multiurl import multiurl
urlpatterns = patterns('',
url(r'^$', 'website.views.home', name='home' ),
url(r'^admin/', include(admin.site.urls)),
multiurl(
url('/your_single_auth_url/$', 'website.views.user_logout'),
url('/your_single_auth_url/$', ''website.views.show_register_or_login_forms'),
url('/your_single_auth_url/$', ''website.views.user_login'),
url('/your_single_auth_url/$', ''website.views.user_register'),
)
)
views.py:
from multiurl import ContinueResolving
from django.http import Http404
def user_logout(request):
if request.user.is_authenticated():
logout(request)
return render_to_response('index.html', RequestContext(request))
else:
# continue to search needed view
raise ContinueResolving
def show_register_or_login_forms(request):
if request.method == 'GET':
# on GET request show two forms, one for register and one for login
else:
raise ContinueResolving
def user_login(request):
if request.method == 'POST':
# check, if login form was submitted here
if is_login_form:
# login user here
else:
raise ContinueResolving
else:
raise Http404
def user_register(request):
if request.method == 'POST':
# check, if register form was submitted here
if is_register_form:
# register user here
else:
raise Http404
else:
raise Http404
答案 1 :(得分:0)
也许你应该尝试ClassBasesViews并做这样的事情:
class Website(View):
def get(self, request, *args, **kwargs):
# Your Website Code
pass
def post(self, request, *args, **kwargs):
# Register Code
def delete(self, request, *args, **kwargs):
# Logout Code
def put(self, request, *args, **kwargs):
# Login Code
比你有4个动作网址(其余)现在你只需要将正确的方法传递给你的表单,它会正确地执行,你的网址也需要一些升级:
url(r'^$', 'Website.as_view()', name='home' ),
其余的没有必要