为什么在我的模型中blank=True没有传播到我的模型窗体



我有一个如下的模型:

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将禁用验证。你知道问题发生在哪里吗?

p.S.django版本是最新版本,>3

和形式.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')

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

向模型表单中的字段添加required=False,或者只使用模型中的默认表单字段实现,而不在表单级别定义字段。

最新更新