【问题标题】:Why is blank=True in my model not propagating to my model form?为什么我的模型中的 blank=True 没有传播到我的模型表单?
【发布时间】:2021-04-16 06:03:36
【问题描述】:

我有一个模型如下:

from cities.models import City
    
class Post(models.Model):
    location = models.ForeignKey(City, default='', blank=True, null=True, on_delete=models.CASCADE)

在模板中:

<form id="dropdownForm" action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ wizard.form.media }}
    {{ wizard.management_form }}
    {% if wizard.form.forms %}
        {{ wizard.form.management_form }}
        {% for form in wizard.form.forms %}
            {{ form }}
        {% endfor %}
    {% else %}
        <div class="content-section-idea-detail-1stpage mt-4 text-center">
        <label for="selectorlocation" class=""><h4><b>Select your location:</b></h4></label><br>
        {{ wizard.form.location }}
        </div>
    {% endif %}
    <input id="id_sub_post_details" class="btn btn-sm btn-primary ml-2"  type="submit" value="{% trans 'submit' %}"/>
</form>

但问题是,我无法将位置字段留空,因为它会在提交之前验证该字段。但是,我希望 blank=True 禁用验证。你知道问题出在哪里吗?

附: django版本是最新版本,>3

在forms.py中:

class post_form(forms.ModelForm):
    location = forms.ModelChoiceField(
        queryset=City.objects.none(),
        widget=autocomplete.ModelSelect2(
            url='location-autocomplete',
            attrs={
                'data-placeholder': '<span class="fe fe-map-pin"></span> City',
                'data-html': True,
                'style': 'height:55px;width:450px;min-width: 27em !important ;',
            }
        )
    )

    class Meta:
        model = Post
        fields = [ 'location']
        search_fields = ['location']

    def __init__(self, *args, **kwargs):
        super(post_form, self).__init__(*args, **kwargs)
        self.fields['location'].queryset = City.objects.all().select_related('region', 'country')

【问题讨论】:

  • 你能告诉我们你的模型形式和你的看法吗?
  • 我刚刚添加了表单,够吗?因为它是一个向导表单,所以发布一个汇总视图和它的 url 有点复杂
  • 你可以尝试在forms.ModelChoiceField 中添加required=False,,在queryset=City.objects.none(), 的下方吗?
  • @NgocPham 是的,谢谢

标签: django forms django-models django-forms


【解决方案1】:

由于您已在表单中以声明方式定义了 location 字段,因此它不再使用您在模型中设置的任何与表单相关的属性。

要么在模型表单的字段中添加required=False,要么您可以只使用模型中的默认表单字段实现而不在表单级别定义字段。

【讨论】:

    猜你喜欢
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多