I need to make a very simple modification -- require that certain views only show up when a user is not authenticated -- to django-registration default views. For example, if I am logged in, I don't want users to be able to visit the /register page again.
So, I think the idea here is that I want to subclass the register
view from django-registration. This is just where I'm not sure how to proceed. Is this the right direction? Should I test the user's authentication status here? Tips and advice welcomed!
Edit
I think this is the right track here: Django: Redirect logged in users from login page
Edit 2
Solution:
Create another app, for example, custom_registration
, and write a view like this (mine uses a custom form as well):
f开发者_如何学编程rom registration.views import register
from custom_registration.forms import EduRegistrationForm
def register_test(request, success_url=None,
form_class=EduRegistrationForm, profile_callback=None,
template_name='registration/registration_form.html',
extra_context=None):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
else:
return register(request, success_url, form_class, profile_callback, template_name, extra_context)
I had to use the same function parameters, but otherwise just include the test, and if we pass it, continue to the main function.
Don't forget to put this in your URLConf either (again, this includes some stuff about my custom form as well):
top-level URLConf
(r'^accounts/', include('custom_registration.urls')),
(r'^accounts/', include('registration.urls')),
custom_registration.views
from django.conf.urls.defaults import *
from custom_registration.views import register_test
from custom_registration.forms import EduRegistrationForm
urlpatterns = patterns('',
url(r'^register/$', register_test, {'form_class': EduRegistrationForm}, name='registration.views.register'),
)
As far as I remember django-registration is using function-based views, so you can not really subclass them. The approach I usually follow is "overwriting" the original views (without modifying the django-registration app of course). This works like this:
- Create another app (you could call it custom_registration or whatever you want)
- This app need to contain another
urls.py
and in your case anotherviews.py
- Copy the original
register
view code to your newviews.py
and modify it, add a pattern to yoururls.py
to point to this view (use the same url pattern as in django-registration for this view) - Put an
include
to your projectsurls.py
of your new appurls.py
before your are including the original django-registration app. This could look like this for example:
urlpatterns = patterns('', ... url(r'^accounts/', include('custom_registration.urls')), url(r'^accounts/', include('registration.backends.default.urls')), ... )
This simply works since the first matching url pattern for /accounts/register
will point to your new app, so it will never try to call the one from the original app.
精彩评论