【发布时间】: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