【问题标题】:Display a form field i.e., a choice field of form in the template django在模板 django 中显示一个表单域,即表单的选择域
【发布时间】:2019-04-05 13:58:45
【问题描述】:

我有 forms.py 文件,我有一个选择字段,我必须在 template.html 中显示它

forms.py

 Choices = [('Yelp',)]
 class UtilitiesForm(forms.Form):
     api_select = forms.MultipleChoiceField(widget=forms.Select(), 
                  choices=Choices)
     text_url = forms.CharField()

模板.html

{% block body_content %}

  <form action="/utilities/fetch-data/" method="post" id="utitliy__form">
     <div class="form-row">
         <label>Select an API</label>
           {{ form.api_select }}
     </div>
  </form>
 {% endblock body_content %}

我收到值错误,你们能帮我如何在 template.html 中编写选择字段

【问题讨论】:

  • 能否请您发布完整的回溯?
  • 此外,我不完全理解您为什么将 MultipleChoiceFieldSelect 小部件一起使用:Select 小部件仅允许选择 one 选项,而 @987654326 @s 旨在选择多个选项(零个、一个或多个)。

标签: django forms templates


【解决方案1】:

您不需要对 forms.py 中的选择字段做任何事情,您可以直接在模板中使用它。 模板

<form action="" method="post">
        {% csrf_token %}
        <label for="order_no">Order No.:</label>
        <input type="text" class='form-control' value="{{Order}}" name="order_no" readonly><br>
        <label for="isbn">ISBN No.:</label>
        <input type="text" class='form-control' value="{{ISBN}}" name="isbn" readonly><br>
        <label for="rate">Rate:</label>{{forms.rate}}(Rate us 10 is the Highest and 1 is the lowest)<br><br>
        <label for="comment">Comments</label>{{forms.comment}}<br><br>
        <input type="submit" class="btn btn-success">
</form>

Models.py

RATING=( (1,1), (2,2), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (10,10) )
class returnbook(models.Model):
    order_no=models.IntegerField(blank=True,null=True)
    isbn=models.CharField(max_length=15)
    rate=models.IntegerField(choices=RATING,default='1')
    comment=models.TextField(max_length=20000,blank=True)
    user=models.CharField(max_length=50) 

class Meta:
    unique_together = ('order_no', 'isbn')
    def __unicode__(self):
        return unicode(self.rate)

【讨论】:

    【解决方案2】:

    choices [Django-doc] 应该是:

    2-tuples 的可迭代(例如,列表或元组)用作 此字段的选择,或返回此类迭代的可调用对象。 此参数接受与选择参数相同的格式 模型字段。请参阅有关选择的模型字段参考文档 更多细节。如果参数是可调用的,则对每个参数进行评估 初始化字段表单的时间。默认为空列表。

    在这里,您为它提供了一个可迭代的 1 元组。元组指定值和文本表示,例如:

    API_SELECT_CHOICES = [('yelp', 'Yelp')]
    
    class UtilitiesForm(forms.Form):
        api_select = forms.ChoiceField(
            widget=forms.Select,
            choices=API_SELECT_CHOICES
        )
        text_url = forms.CharField()

    您使用MultipleChoiceFieldSelect 小部件也很奇怪。通常Select 小部件用于选择恰好一个元素,而SelectMultiple 小部件用于选择一个更多个元素。所以我这里把字段改成ChoiceField。带有Select 小部件的ChoiceField 有意义,带有SelectMultipleMultipleChoiceField 有意义,但其他组合没有多大意义。

    【讨论】:

    • 我也使用过ChoiceField,但我遇到了错误,需要超过 1 个值才能解压请求方法:POST 请求 URL:localhost:8000/utilities/fetch-data Django 版本:1.10.5 异常类型:ValueError异常值:需要超过 1 个值才能解压异常位置:render_options 中的 /Users/apple/move-easy/move-easy/lib/python2.7/site-packages/django/forms/widgets.py,第 567 行 Python 可执行文件:/Users/apple/move-easy/move-easy/bin/python Python版本:2.7.13
    • @krishnakrish:你取消choices了吗?请发布 full 错误。
    • @krishnakrish:我觉得你确实没有choices更改为[('yelp', 'Yelp')]
    【解决方案3】:

    在表单中添加选项

    forms.py

    from django.contrib.auth.models import User
    from django import forms
    
    class UserForm(forms.ModelForm):
        status = models.IntegerField(choices=((1, _("Unread")),(2, _("Read"))),default=1)
        class Meta:
            model = User
            fields = ['first_name', 'last_name', 'status']
    

    在views.py中

    from django.contrib.auth.models import User
    from .forms import UserForm # Add form which is written in your forms.py
    def index(request):
        context = {}
        form = UserForm() #Initiate 
        return render(request, 'index.html', {'form': form})
    

    index.html您将在 html 中获得选择

    <form action="{% url 'about' %}" method="POST" role="form">
            {% csrf_token %}
            {{ form }}
    </form>
    

    更多详情请参考link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-14
      • 2011-07-23
      • 2011-10-11
      • 2021-06-28
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多