我已经为这个问题挣扎了一段时间,所以我很感激任何帮助,不管多么模糊。
Django 2.0.1: Django使用"required“设置来验证字段是否有效,如果我将:{{ client_primary_sector }}输入到适用的html文件中,并通过数据模型(blank=False)或通过forms.py (attrs={"required": "required"})选择”必需“设置,效果会很好。但是,当我使用for循环来生成单选按钮时,“必需”设置将失败。
下面是一个有用的和坏掉的例子.
models.py:.
class SurveyInstance(models.Model):
client_primary_sector = models.CharField(choices=PRIMARY_SECTOR, null=True, default='no_selection', blank=False, max_length=100)请注意,在“`default=‘no_selection”的上方,它不在PRIMARY_SECTOR选项中,也不作为选项呈现给用户。这迫使用户在保存数据之前进行选择(我已经确认它有效)。
forms.py
class ClientProfileForm(ModelForm):
class Meta:
model = SurveyInstance
fields = ('client_primary_sector',)
widgets = {'client_primary_sector': forms.RadioSelect(choices=PRIMARY_SECTOR, attrs={"required": "required"}),
}views.py
def client_profile_edit(request, pk):
# get the record details from the database using the primary key
survey_inst = get_object_or_404(SurveyInstance, pk=pk)
# if details submitted by user
if request.method == "POST":
# get information from the posted form
form = ClientProfileForm(request.POST, instance=survey_inst)
if form.is_valid():
survey_inst = form.save()
# redirect to Next view:
return redirect('questionnaire:business-process-management', pk=survey_inst.pk)
else:
# Retrieve existing data
form = ClientProfileForm(instance=survey_inst)
return render(request, 'questionnaire/client_profile.html', {'form': form})client_profile.html
<!-- this works: -->
<!-- <div class="radio_3_cols">
{{ form.client_primary_sector }}
</div> -->
<!-- this doesn't: -->
{% for choice in form.client_primary_sector %}
<div class="radio radio-primary radio-inline">
{{ choice.tag }}
<label for='{{ form.client_primary_sector .auto_id }}_{{ forloop.counter0 }}'>{{ choice.choice_label }}</label>
</div>
{% endfor %}你可能想知道我为什么不直接用工作解决方案..。我希望能够在其他情况下使用for循环逻辑,因此需要一个解决方案。
发布于 2018-03-19 14:40:55
回答了我自己的问题。来自文档for 2.0:https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#radioselect
正确的语法是:
{% for radio in form.client_profile %}
<label for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
<span class="radio">{{ radio.tag }}</span>
</label>
{% endfor %}不是我以前发现的那样。确认是有效的。好啊!
https://stackoverflow.com/questions/49361430
复制相似问题