首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django 2.0.1:循环以创建单选按钮中断“必需”设置

Django 2.0.1:循环以创建单选按钮中断“必需”设置
EN

Stack Overflow用户
提问于 2018-03-19 11:03:37
回答 1查看 1.3K关注 0票数 1

我已经为这个问题挣扎了一段时间,所以我很感激任何帮助,不管多么模糊。

Django 2.0.1: Django使用"required“设置来验证字段是否有效,如果我将:{{ client_primary_sector }}输入到适用的html文件中,并通过数据模型(blank=False)或通过forms.py (attrs={"required": "required"})选择”必需“设置,效果会很好。但是,当我使用for循环来生成单选按钮时,“必需”设置将失败。

下面是一个有用的和坏掉的例子.

models.py:.

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
  <!-- 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循环逻辑,因此需要一个解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-19 14:40:55

回答了我自己的问题。来自文档for 2.0:https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#radioselect

正确的语法是:

代码语言:javascript
复制
{% for radio in form.client_profile %}
    <label for="{{ radio.id_for_label }}">
        {{ radio.choice_label }}
        <span class="radio">{{ radio.tag }}</span>
    </label>
{% endfor %}

不是我以前发现的那样。确认是有效的。好啊!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49361430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档