Display a form field i.e., a choice field of form in the template django

巧了我就是萌 提交于 2021-02-11 13:14:27

问题


I've have forms.py file in that i have a choice field which i've to display it in the template.html

forms.py

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

template.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 %}

i'm getting Value error can you guys help me how to write the choice field in template.html


回答1:


You need not to do anything with choice field in forms.py you can directly use it in your template. template

<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:


The choices [Django-doc] should be:

Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized. Defaults to an empty list.

Here you provide it an iterable of 1-tuples. The tuple specify the value, and the textual representation, for example:

API_SELECT_CHOICES = [('yelp', 'Yelp')]

class UtilitiesForm(forms.Form):
    api_select = forms.ChoiceField(
        widget=forms.Select,
        choices=API_SELECT_CHOICES
    )
    text_url = forms.CharField()

It is also strange that you used a MultipleChoiceField with a Select widget. Normally a Select widget is used to select exactly one element, whereas a SelectMultiple widget is used to select zero, one, or more elements. So I here changed the field to ChoiceField. A ChoiceField with a Select widget makes sense, and a MultipleChoiceField with a SelectMultiple makes sense, but the other combinations do not make much sense.




回答3:


Add the choice in form

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']

in 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 you will get choice in html

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

for more details please refer this link



来源:https://stackoverflow.com/questions/53099670/display-a-form-field-i-e-a-choice-field-of-form-in-the-template-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!