1

I understand that you can use the initiate parameter for a Form class from this question.

I am creating an edit form and I'm trying to figure out how to initiate values from a pre-existing object.

Do I do it in the template level or in the view level (I don't even know how to do it in the template level)? Or maybe I need to pass the actual object to the form and initiate in the form level?

What is the best practice?


EDIT:

For @Bento: In my original Form, I'm doing something like this

class OrderDetailForm(forms.Form):
    work_type = forms.ChoiceField(choices=Order.WORK_TYPE_CHOICES)
    note = forms.CharField(widget=forms.Textarea)

    def __init__(self, creator_list=None, place_list=None, *args, **kwargs):
        super(OrderCreateForm, self).__init__(*args, **kwargs)

        if creator_list:
            self.fields['creator'] = UserModelChoiceField(
                queryset=creator_list,
                empty_label="Select a user",
            )

    def clean(self):
        super(OrderCreateForm, self).clean()

        if 'note' in self.cleaned_data:
            if len(self.cleaned_data['note']) < 50:
                self._errors['note'] = self.error_class([u"Please enter a longer note."])

                del self.cleaned_data['note']

        return self.cleaned_data

How would I do that with ModelForm?

Community
  • 1
  • 1
hobbes3
  • 28,078
  • 24
  • 87
  • 116

1 Answers1

2

Assuming you are using a ModelForm, it's actually fairly simple. The task is something like this: retrieve the object of the model that you want to populate your 'edit' for with, create a new form based on your ModelForm, and populate it with the object using 'instance'.

Here's the skeleton of your view:

def view(request): 
  obj = Model.objects.get(pk = objectpk)
  form = MyModelForm(instance = obj)

  return render (request, "template", {'form' = form})

You can access the 'initial' values by using something like:

form.fields['fieldname'].initial = somevalue

And then you'd return the form like above.

bento
  • 4,846
  • 8
  • 41
  • 59
  • I'm using `forms.Form`, not `forms.ModelForm`, but I can convert my form model to `ModelForm`. The reason I didn't use `ModelForm` was because my form has a permission-based system where it dynamically creates the fields for certain users. – hobbes3 May 17 '12 at 20:26
  • 1
    You can probably achieve the same thing with a regular form, but you might need to populate the data manually -- i.e., retrieving a queryset, and parsing that data into individual fields using the .initial method above. If you figure it out, post your solution. – bento May 17 '12 at 20:58
  • Okay, ya so I'll convert my form to `ModelForm`. I'll need to figure out how to programmatically add fields in a `ModelForm`. Please see my updated question. – hobbes3 May 17 '12 at 21:20