简体   繁体   English

为隐藏的 ModelForm 字段 Django 设置默认值

[英]Set default value for hidden ModelForm field Django

I want to pass an initial value for HiddenInput form field in Meta class of ModelForm object.我想在ModelForm对象的Meta类中为HiddenInput表单字段传递一个初始值。 If the field is not hidden, eg as:如果该字段未隐藏,例如:

class Meta:
    model = SomeModel
    fields = ['some_id', 'some_amount',]

and I pass initial values via kwargs to this form constructor, then initial values are set to these fields correctly.我通过kwargs将初始值传递给这个表单构造函数,然后将初始值正确设置到这些字段。

But when I try to hide one field (but I still need it to be set up to initial value from kwargs ), as eg:但是当我尝试隐藏一个字段时(但我仍然需要将其设置为kwargs初始值),例如:

class Meta:
    model = SomeModel
    widgets = {'ord_id': forms.HiddenInput(),}
    fields = ['some_id', 'some_amount',]

Then 'ord_id' is not set up to initial value from kwargs and I get the following error when trying to submit such form:然后'ord_id'未设置为kwargs初始值,并且在尝试提交此类表单时出现以下错误:

(Hidden field ord_id) Select a valid choice. (隐藏字段 ord_id)选择一个有效的选项。 That choice is not one of the available choices该选择不是可用的选择之一

So is there any way to pass an initial value to the Hidden form field correctly?那么有没有办法正确地将初始值传递给隐藏表单字段?

You can set defaults value to form fields in two ways.您可以通过两种方式为form字段设置默认值。

first method is by passing default values while on initializing the form in your view.py ie第一种方法是在初始化view.py的表单时传递默认值,即

from forms import ExampleForm

INITIAL_DATA = {'ord_id': 'some_id'}

def my_view(request):
    ...

    if request.method == 'GET':
        form = ExampleForm(initial=INITIAL_DATA)
    if request.method == 'POST':
        form = ExampleForm(request.POST)
    ...

Second is by overriding the form __init__ method ie其次是通过覆盖形式__init__方法即

class ExampleForm(forms.ModelForm):类 ExampleForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    """If no initial data, provide some defaults."""
    initial = kwargs.get('initial', {})
    initial['ord_id'] = 'ord_id'
    kwargs['initial'] = initial
    super(ExampleForm, self).__init__(*args, **kwargs)

If you've verified with the inspection tool that your select element really does have the correct option selected, the problem may be that your field is disabled somehow instead of just hidden.如果您已使用检查工具验证您的 select 元素确实选择了正确的选项,则问题可能是您的字段以某种方式被禁用,而不仅仅是隐藏。 I've seen similar error messages from attempting to submit disabled fields.我在尝试提交禁用字段时看到过类似的错误消息。 If that's not the case, I may have an alternative solution for designating your fields as hidden.如果不是这种情况,我可能有一个替代解决方案来将您的字段指定为隐藏。

If you are using django templates you can use widget tweaks to modify form fields in the template, which allows you to do things like add classes and styles or change values.如果您使用 django 模板,您可以使用小部件调整来修改模板中的表单字段,这允许您执行添加类和样式或更改值等操作。 So you can pass the initial arguments to your form as you have already and hide them using template tags.因此,您可以将初始参数传递给您的表单,并使用模板标签隐藏它们。 Hope this works for you!希望这对你有用!

{% for field in form %}
    {% if field == form.hidden_field_name %}
        {% render_field field hidden='True' id='hidden-field' class='hidden-field-class' %}
    {% endif %}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM