Z
Z
zigen2015-07-28 15:33:22
Django
zigen, 2015-07-28 15:33:22

How to set initial parameter for ModelForm?

Good afternoon.
Tell me how to get the initial values ​​​​of the form from the model?

class VendorEditForm(forms.ModelForm):
    class Meta:
        model = Vendor
        fields = ('avatar','description',)

I understand what needs to be done when I instantiate the form, but I don’t get it right
context['form'] = self.form_class(self.request.GET, initial=??? )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2015-07-28
@zigen

www.stackoverflow.com/a/4674127

# forms.py
# ...
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

# views.py
# ...    
def my_view(request, id): 
    instance = get_object_or_404(MyModel, id=id)
    form = MyForm(request.POST or None, instance=instance)
    if form.is_valid():
        form.save()
        return redirect('next_view')
    return direct_to_template(request, 'my_template.html', {'form': form}

Z
zigen, 2015-07-28
@zigen

sim3x , thank you!
It worked for me for CBV like this:
self.object = self.get_object()
context['form'] = self.form_class(self.request.GET or self.request.POST or None, instance=self.object)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question