How do I initiate values for fields in a form for editing in a template

泪湿孤枕 提交于 2019-12-08 07:50:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10642625/how-do-i-initiate-values-for-fields-in-a-form-for-editing-in-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!