Jaime38130
Jaime38130

Reputation: 165

django-registration class overriding

Because I need to add a captcha(django-recaptcha) to the registration form I want to override the RegistrationForm class from the django-registration module.

I am using:

I've tried some options has shown below.

forms.py

from django_registration.forms import RegistrationForm

class MyRegistrationForm(RegistrationForm):
    age = forms.IntegerField()

    class Meta(RegistrationForm.Meta):
        fields = RegistrationForm.Meta.fields + ['age']

urls.py

from .forms import MyRegistrationForm
from django_registration.backends.activation.views import RegistrationView

path('accounts/register/', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register')

registration_form.html

<form method="post" action=".">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="{% trans 'Submit' %}" />
</form> 

Nothing overrides the form. I don't understand why. Same thing for the RegistrationView. I can't override it for some reason. I've been arround these for a while now. Probably am missing something obvious by now. Help is appreciated. Thank you.

Upvotes: 0

Views: 49

Answers (1)

Jaime38130
Jaime38130

Reputation: 165

Solution:

Because in django-registration there are multiple RegistrationView:

  • backends\activation\views.py
  • backends\one_step\views.py
  • views.py

Being that that the RegistrationView in \backends inherit from the views.py in the root. The form_class attribute is defined in the root view. So the solution I found was the one below:

#views.py

from .forms import *
from django_registration.views import RegistrationView

RegistrationView.form_class = MyRegistrationForm

#forms.py

from django_registration.forms import RegistrationForm
from captcha.fields import ReCaptchaField

class MyRegistrationForm(RegistrationForm):
    captcha = ReCaptchaField()

captcha is then accessible in registration_form.html through {{form}}.

Overriding the RegistrationView

Yet about having trouble overriding the view, the problem I was having seems to be in what order my urls were defined.

path('accounts/register/', MyRegistrationView.as_view(), name='registration_register'),
path('accounts/', include('django_registration.backends.activation.urls')),

I had to place /accounts/register before /accounts. I initially expected that by placing /accounts/register after the native urls inclusion would overwrite any others urls.

Upvotes: 0

Related Questions