On Thu, 2009-01-08 at 17:09 -0800, DragonSlayre wrote:
> I'm trying to generate a form with a user's details, so that they can
> change the details they've submitted.
> 
> One of my forms is a ModelForm, which is the profile of the User
> object.  I also want to show the first name, last name and email from
> the User object, so I've created a form for that which validates the
> email (to make sure no-one else has the same email).
> 
> Here's my view code so far:
> 
> @login_required
> def change_my_account(request):
>     fireman = Fireman.objects.get(pk=request.user.get_profile().id)
> 
>     if request.method == 'POST':
>         #also need to check my RegistrationFormSimple
>         form = FiremanForm(request.POST, instance=fireman)
>         if form.is_valid():
>             form.save()
>     else:
>         form =FiremanForm(instance=fireman)
>         data = {'first_name' : request.user.first_name,
>                 'last_name'  : request.user.last_name,
>                 'email'      : request.user.email}
>         userForm = RegistrationFormSimple(data)
>     return render_to_response('Change_account.html', {'form' : form,
>                                                       'user_form' :
> userForm})
> 
> This works well, except that I have a validator in my
> RegistrationFormSimple, which needs to know who the user is, to check
> the emails.
> 
> I'm stumped about how I give this information to my
> RegistrationFormSimple.

The validation method needs to be able to look up the user or have it
passed in. I would pass it in. You can write an __init__ method for your
RegistrationFormSimple class that accepts an extra parameter (preferably
a keyword argument) that it uses in the validator. For example

        class RegistrationFormSimple(forms.Form):
           def __init__(self, *args, **kwargs):
              self.user = kwargs.pop("user")
              super(RegistrationFormSimple, self).__init__(*args,
        **kwargs)
        
           def clean_email(self):
              # Can refer to self.user in here
        
Then you can create this form in your view like this:

        userForm = RegistrationFormSimple(data, user=request.user)
        
Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to