Hi Tom,
==================================================================================
-- As per your first suggestion I tried a ModelChoiceField in place of ChoiceField.
It also results in a validation error.
I am putting my new code here.
=================================================================================
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=choices_des_fn())
desig_group = forms.ModelChoiceField(queryset=Group.objects.all())
def initialize_designation(self):
print("Initializing designation")
self.desig_group = forms.ChoiceField(choices=choice_des())
return
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"]
print("New_user_form save : Designation :", designation)
if commit:
user.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)
valid = form.is_valid()
print("validation complete. result = ", valid)
if valid:
print("Form Validated")
new_user = form.save()
context = {}
return HttpResponseRedirect("/hr_base/index")
else:
print("Forms non field error", form.non_field_errors())
print("Form invalid")
print("choice_desig = ",choice_desig())
print("validation error. retrying")
else:
print("Non post method")
form = New_user_form()
g = Group.objects.all()
desig = []
for k in g:
desig.append(k.name)
args = {}
args.update(csrf(request))
args.update({'user':request.user.username,
'form':form,
'STATIC_URL':settings.STATIC_URL,
'is_hr_group':hr_group(request.user),
'is_user_authenticated': request.user.is_authenticated(),
'is_user_superuser':request.user.is_superuser,
'desig': desig,
'k': zip(desig, range(len(desig))),
})
res= render_to_response('emp_users/register.html', args)
return res
===========================================================================================
Given below is my 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,j in k %}
<option value='{{ j }}'>{{ i }}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
<input type="submit" value="Register"/>
</form>
Whats going wrong here?
Am I missing something here?
I am not getting much info anywhere on ChoiceFields or ModelChoiceFields with dynamic data.
Regards,
Preetam
On Friday, 21 March 2014 00:20:51 UTC+5:30, sashank reddy wrote:
On Friday, 21 March 2014 00:20:51 UTC+5:30, sashank reddy wrote:
Tom,In addition it still doesn't explain why I am unable to traceback the point of exception.How can there be an exception when the only thing there are are few perfect printsI am always invariably getting the"Validation completed print"for desig_name field.Then I get"BaseForm: _clean_fields: ValidationError for desig_group"It should actually be:"Field executing validators :Running validatorsCompleted executing field validator"It should atleast give the first 2 printsThe following are the prints in my core files Field class in django.forms.fields:======================================================== def validate(self, value):if value in validators.EMPTY_VALUES and self.required:raise ValidationError(self.error_messages['required']) print("Validation complete")def run_validators(self, value):print("Running validators")if value in validators.EMPTY_VALUES:returnerrors = []for v in self.validators:try:v(value)except ValidationError as e:if hasattr(e, 'code') and e.code in self.error_messages:message = self.error_messages[e.code]if e.params:message = message % e.paramserrors.append(message)else:errors.extend(e.messages)if errors:raise ValidationError(errors)def clean(self, value):"""Validates the given value and returns its "cleaned" value as anappropriate Python object.Raises ValidationError for any errors."""value = self.to_python(value)self.validate(value)print("Field executing validators : ")self.run_validators(value)print("Completed executing field validator")return value
On Thursday, 20 March 2014 23:11:24 UTC+5:30, sashank reddy wrote:Hi Tom,I did try an override meanwhile.I added,def initialize_designation(self):print("Initializing designation")self.desig_group = forms.ChoiceField(choices=choice_des()) returnto my form class.This will override the desig_group that is previously declared.I call this in the view after the form instance is created and assigned to formform.initialize_designation()I am getting the prints from the function meaning that the function is executed.Still there is Validation error.This should have worked right? Why dint this work?Regards,PreetamOn Thursday, 20 March 2014 17:12:07 UTC+5:30, Tom Evans wrote:On Thu, Mar 20, 2014 at 10:12 AM, sashank reddy
<preetamsa...@gmail.com> wrote:
> Hi Tom,
>
> I have not understood what you have said. Shouldn't choice_desig be called
> every time I instantiate it in the view with the form = New_user_form(). I
> thought I was creating an object of New_user_form every time I do that.
This is pretty basic python, the function is run when python
interprets the class.
Eg,
class Foo(object):
some_var = 'this is a string'.split()
The string is split only once, when the class Foo is parsed by python,
not whenever an instance of Foo is instantiated. Things that happen
when an instance is instantiated are contained in the __init__ method.
Although the some_var looks like it is just declaring a class
attribute, it is actually just running code in the scope of the class,
and as such you can write almost any code there (contrast with
definition of class variables in java). Eg this is perfectly valid:
class Foo(object):
some_var = 'this is a string'.split()
some_var = some_var[1:]
some_var.sort()
Cheers
Tom
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2cbd3207-baaa-4b18-9a08-dca0b7e1c510%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment