Django - 为什么我的单选按钮不呈现?

时间:2014-07-03 02:54:13

标签: django django-forms

models.py

class Trip(models.Model):
    location_name = models.CharField(max_length=60)
    trip_date = models.DateField()
    trip_rating = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
    fishing_vehicle = models.ForeignKey(FishingVehicle)
    water_body = models.ForeignKey(WaterBody)
    user = models.ForeignKey(User)
    def __unicode__(self):
        return self.location_name

forms.py

class TripForm(ModelForm):
    class Meta:
        model = Trip
        exclude = ['user']
        CHOICES = (('1', 'First',), ('2', 'Second',))
        trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)

logtrip.html

{% extends "base.html" %}

{% block content %}

<div class="container">
  <!-- Example row of columns -->
  <div class="row">
    <div class="col-md-4">
      <form action="/logtrip/" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
      </form>
    </div>
  </div>
</div>

{% endblock %}

我的表单呈现没有错误,但不是为trip_rating字段获取一对单选按钮,而是呈现数字字段,

<input id="id_trip_rating" name="trip_rating" type="number">

如何获得这些单选按钮?

1 个答案:

答案 0 :(得分:2)

modelform中的表单字段是类级属性,而不是Meta属性

class TripForm(ModelForm):

    CHOICES = (('1', 'First',), ('2', 'Second',))
    trip_rating = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)

    class Meta:
        model = Trip
        exclude = ['user']

应该这样做。