Reputation: 2722
I am trying to force users to enter their email when they sign up. I understand how to use form fields in general with ModelForms. I am unable to figure out how to force an existing field to be required, however.
I have the following ModelForm:
class RegistrationForm(UserCreationForm):
"""Provide a view for creating users with only the requisite fields."""
class Meta:
model = User
# Note that password is taken care of for us by auth's UserCreationForm.
fields = ('username', 'email')
I am using the following View to process my data. I am not sure how relevant it is, but it is worth saying that other fields (username, password) are properly loading with errors. The User model already has those fields set as required, however.
def register(request):
"""Use a RegistrationForm to render a form that can be used to register a
new user. If there is POST data, the user has tried to submit data.
Therefore, validate and either redirect (success) or reload with errors
(failure). Otherwise, load a blank creation form.
"""
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
# @NOTE This can go in once I'm using the messages framework.
# messages.info(request, "Thank you for registering! You are now logged in.")
new_user = authenticate(username=request.POST['username'],
password=request.POST['password1'])
login(request, new_user)
return HttpResponseRedirect(reverse('home'))
else:
form = RegistrationForm()
# By now, the form is either invalid, or a blank for is rendered. If
# invalid, the form will sent errors to render and the old POST data.
return render_to_response('registration/join.html', { 'form':form },
context_instance=RequestContext(request))
I have tried creating an email field in the RegistrationForm, but this seems to have no effect. Do I need to extend the User model and there override the email field? Are there any other options?
Thanks,
ParagonRG
Upvotes: 0
Views: 541
Reputation: 34553
Just override the __init__
to make the email field required:
class RegistrationForm(UserCreationForm):
"""Provide a view for creating users with only the requisite fields."""
class Meta:
model = User
# Note that password is taken care of for us by auth's UserCreationForm.
fields = ('username', 'email')
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
This way, you don't have to completely re-define the field, but simply change the property. Hope that helps you out.
Upvotes: 2