nasufuu
nasufuu

Reputation: 29

Django Override the Default success_url in contrib.auth.views

I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function.

Now I need to change all the class details of the success_url, for instance from:

reverse_lazy('login') 

to:

reverse_lazy('accounts:login') 

but overwriting the original urls.py is not a good practice. I'm a python beginner and struggling with this problem already for a month..

how can I achieve this?

What I attemptd was making subclasses in my views inherent from each of the class in django.contrib.auth.views.

I even tried putting try/except method with except 'NoReverseMatch:' but the function itself did not exist.

Upvotes: 2

Views: 268

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477641

Typically the login url is specified in the LOGIN_URL setting [Django-doc]:

# settings.py

# …

LOGIN_URL = reverse_lazy('accounts:login')

In your views where you need the LOGIN_URL, you then import this from the settings, so:

from django.conf import settings


class PasswordChangeView(PasswordContextMixin, FormView):
    form_class = PasswordChangeForm
    success_url = settings.LOGIN_URL
    template_name = 'registration/password_change_form.html'
    title = _('Password change')

This thus makes it convenient to plug in a different view name.

Upvotes: 1

Lucas Grugru
Lucas Grugru

Reputation: 1869

I think there is no other solution that override django.contrib.auth classes for make your custom urls if you are using the default.

Overriding the default urls.py does not work because auth code use the original urls.

With package like django-allauth, you can make custom urls, but with Django-auth, it is not possible. then I think it goes rather quickly to copy paste the classes of auth.views.py and to overload the different urls

I am interesting if someone else has a better and elegant solution of this problem too

Upvotes: 1

Related Questions