Hi,
I have been trying to extend the UserCreationForm and have a form which performs user registration and adds email and the names.
In addition I am using a choice field that allows a list down of existing groups so that you can assign the user to an group immediately upon creation.
The problem is that, if I create a new group, and try to add users to it, then the form validation fails.
I have restart the django server or wait for it to reset internally and show "Validating models ..". Then it starts to work.
The following is the code snippet:
=============================================================================
def choice_desig():
choice_desig = []
g = Group.objects.all()
for k in g:
return choice_desig
class New_user_form(UserCreationForm):
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
desig_group = forms.ChoiceField(choices=choice_desig())
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
designation = self.cleaned_data["desig_group"]
if commit:
user.save()
p = person.objects.get(pk=employee_id)
u = user_maps(user_name=user.username, emp_id=p)
u.save()
g = Group.objects.filter(name=designation)
print("acquired group", g[0].name)
#user.groups.add(g)
g[0].user_set.add(user)
g[0].save()
return user
def register_user(request):
if request.method == 'POST':
print("Register user : POST")
print("request.POST = ", request.POST)
form = New_user_form(request.POST)
if form.is_valid():
print("Form Validated")
new_user = form.save()
context = {}
print_user(new_user)
host = request.get_host()
link = "http://"+host +"/hr_base/index"
#return HttpResponseRedirect("http://"+host +"/hr_base/index")
return HttpResponseRedirect("/hr_base/index")
else:
print("Forms non field error", form.non_field_errors())
print("Form invalid")
print("choice_desig = ",choice_desig())
emp_id = request.POST.get('emp_id')
#host = request.get_host()
#link = "http://"+host +"/hr_base/index"
#return HttpResponseRedirect("http://"+host +"/hr_base/index")
return HttpResponseRedirect("/emp_users/new_user")
else:
print("Non post method")
print("Acquired emp_id: ", request.session['emp_id'])
form = New_user_form()
#form.acquire_groups()
#print("Form desig choice : ", form.choice_desig)
g = Group.objects.all()
desig = []
for k in g:
args = {}
args.update(csrf(request))
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'is_user_authenticated': request.user.is_authenticated(),
'is_user_superuser':request.user.is_superuser,
'desig': desig,})
res= render_to_response('emp_users/register.html', args)
return res
print("general area")
return HttpResponse("Doesn't Make sense")
===========================================================================================
Below is the template:
==========================================================================================
<h2>Register</h2>
<hr />
<form action='/emp_users/new_user' method='post'>{% csrf_token %}
<table>
<tr>
<th><label for="id_username">Username:</label></th>
<td>
<input id="id_username" maxlength="30" name="username" type="text" />
<br /><span class="helptext">Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.</span>
</td>
</tr>
<tr>
<th><label for="id_password1">Password:</label></th>
<td>
<input id="id_password1" maxlength="4096" name="password1" type="password" />
</td>
</tr>
<tr>
<th><label for="id_password2">Password confirmation:</label></th>
<td>
<input id="id_password2" maxlength="4096" name="password2" type="password" />
<br /><span class="helptext">Enter the same password as above, for verification.</span>
</td>
</tr>
<tr>
<th><label for="id_email">email</label></th>
<td>
<input id="id_email" maxlength="4096" name="email" type="email" />
<br /><span class="helptext">Enter your email id, for verification.</span>
</td>
</tr>
<tr>
<th><label for="id_first_name">First name:</label></th>
<td>
<input id="id_first_name" maxlength="4096" name="first_name" type="text" />
</td>
</tr>
<tr>
<th><label for="id_last_name">Last name:</label></th>
<td>
<input id="id_last_name" maxlength="4096" name="last_name" type="text" />
</td>
</tr>
<tr>
<th><label for="id_desig_group">Group/Designation:</label></th>
<td>
<select id="id_desig_group" name="desig_group">
{% for i in desig %}
<option value='{{ i }}'>{{ i }}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
<input type="submit" value="Register"/>
</form>
========================================================================================
I did some debugging on my own and I was surprised.
The validation error is for the select field desig_group and it fails somewhere just after self.validate(value) in the field.clean method.
The prints clearly indicate that the method passed and completed.
def validate(self, value):
print("Validating. value = ", value, "Empty validator result = ", value in validators.EMPTY_VALUES, "self.required = ", self.required)
if value in validators.EMPTY_VALUES and self.required:
print("validating: empty values =", validators.EMPTY_VALUES)
print("validating: self.required =", self.required)
raise ValidationError(self.error_messages['required'])
print("Validation complete")
def clean(self, value):
"""
Validates the given value and returns its "cleaned" value as an
appropriate Python object.
Raises ValidationError for any errors.
"""
print("Field cleaning")
value = self.to_python(value)
print("Field got value by to_python :", value)
self.validate(value)
print("Field executing validators : ")
self.run_validators(value)
print("Completed executing field validator")
return value
For these prints, I got this in my console:
=============================================
BaseForm: _clean_fields: cleaning
BaseForm: _clean_fields: Got widget value : tester90
BaseForm: _clean_fields: isinstance else
Field cleaning
Field got value by to_python : tester90
Validating. value = tester90 Empty validator result = False self.required = True
Validation complete
BaseForm: _clean_fields: ValidationError for desig_group
==================================================
That is ridiculous as the next statement after Validation complete is print("Field executing validators : ") which should have been printed.
I need to solve this to be able to bring stability to my application. Please help.
Regards,
Preetam