本文介绍了如何启动表单中字段的值,以便在模板中进行编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以使用启动参数,从。

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?

最佳做法是什么?

编辑:

对于@Bento:在我原来的表单中,我正在做这样的事情

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

如何使用 ModelForm

推荐答案

假设您正在使用ModelForm,它实际上相当简单。任务是这样的:检索要填充您的编辑的模型对象,根据您的ModelForm创建一个新表单,并使用实例将该对象填充到对象中。

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

这是您的视图的骨架:

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.

这篇关于如何启动表单中字段的值,以便在模板中进行编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 20:38