Reputation: 10132
I am defining a custom registration form that includes email Field in it. Here is the code:
forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
#define fields
email=forms.EmailField(required=True)
class Meta:
model=User
fields=('username','email','password','password2')
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email=self.cleaned_data["email"]
if commit:
user.save()
return user
views.py:
def register_user(request):
if request.method=='POST':
#form=UserCreationForm(request.POST)
form=MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect("/accounts/register_success")
args={}
args.update(csrf(request))
#args['form']=UserCreationForm()
args['form']=MyRegistrationForm()
return render(request,"register.html",args)
templates/register.html:
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="register"/>
</form>
{% endblock %}
As you can see from the attached screenshot, I get three password Fields
. why is that?
A similar question is asked here, but no solution is provided.
Upvotes: 1
Views: 311
Reputation: 31242
I guess it is because you are defining a new password field
. your fields
in class Meta
should be as follows:
class Meta:
model=User
fields=('username','email','password1','password2')
In this case, you are inheriting the fields from UserCreationForm
.
Upvotes: 2