You should always populate your form in forms.py. This is done using the
'initial' kwarg and is thoroughly explained in the docs! [1]

Borrowing from the tutorial's Poll model [2]:

Class PollsForm(forms.Form):
    def __init__ (self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)

        if self.instance.pk is not None:
            kwargs['initial'] = kwargs.get('initial', {})
            kwargs['initial'] = {'question': self.instance.question}

        super(PollsForm, self).__init__(*args, **kwargs)

This way, you can edit a Poll object by calling
PollsForm(instance=some_poll_object),
and it will automatically populate 'question' with the instance's
question attribute.


Cheers,
AT

[1]
https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values
[2] https://docs.djangoproject.com/en/dev/intro/tutorial01/#creating-models




On Sun, Oct 23, 2011 at 4:08 PM, Swaroop Shankar V <swaroo...@gmail.com>wrote:

> Hello All,
>
> I am trying to create a Edit form to edit user information. I would like to
> display the default values in the form fields rendered and am getting the
> values from the db table. I can take an approach by creating a dictionary
> with the values that needs to be populated in the form fields in my view
> file and then pass it to the html. Then in the html, i can manually set the
> values using the django-widget_tweaks. But the problem here is that there
> are few select box for which this approach wont work. So the next option is
> to do it from the forms.py but there i need to get the currently logged in
> user and since request object is not available i created an __init__
> function with the following statements
>
> def __init__(self, *args, **kwargs):
>         self.request = kwargs.pop('request', None)
>         super(UserEditForm, self).__init__(*args, **kwargs)
>
> but now i am not sure on how to set up the form values. My form's class
> code can be accessed via the url http://pastebin.com/1TuRmNhH . Please
> help.
>
> Thanks and Regards,
> Swaroop Shankar V
>
>  --
> 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.
>

-- 
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