简体   繁体   中英

Django-registration custom urls

I've used django-registration ( the app , HMAC) for user registration and login. Everything works fine, but I would like to have the login form at http://localhost:8000/ , instead of /accounts/login/. What would be the cleanest way to accomplish this?

When just copying the form from login.html to my index.html file, which provides the view of the main page, it (obviously (?)) doesn't work. I'm using django 1.9.6 and django-registration 2.1. Please note that I haven't got 'registration' in INSTALLED_APPS in the setting.py file, since that wasn't needed according to the docs.

This is my login.html file:

{% extends "mysite/base.html" %}
{% load i18n %}

{% block content %}
<form method="post" action=".">
  {% csrf_token %} 
  {{ form.as_p }}

  <input type="submit" value="{% trans 'Log in' %}" />
  <input type="hidden" name="next" value="{{next}}" />
</form>

<p>{% trans "Forgot password" %}? <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>!</p>
<p>{% trans "Not member" %}? <a href="{% url 'registration_register' %}">{% trans "Register" %}</a>!</p>
{% endblock %}

And my urls.py file:

from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name='index'),
    url(r'^accounts/', include('registration.backends.hmac.urls')),
    url(r'^groups/', include('groups.urls')), #my own app
]

Theres a few ways to do it, and it really depends on whether you care about redirects and how you like to organize your URL structure.

I would do something like this:

from django.conf.urls import include, url from django.contrib import admin from . import views form registration.backends.hmac.views import login

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name='index'),
    url(r'^accounts/login$', RedirectView.as_view(url='/login'), name='got-to-lgoin') # You have several options for this, see below
    url(r'^accounts/', include('registration.backends.hmac.urls')),  
    url(r'^login/$, login, name='login'),
    url(r'^groups/', include('groups.urls')), #my own app
]

Now as per the second login url, you could remove it from the hmac.urls, change it to redirect to /login, make a new custom urls file and include that, or do what I did and just add a redirect view.

Like I said its personal preference. If youre going to do it for more urls other than just /login and /logout, I would just make a separate urls.py file and include that. It's cleaner.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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