django我看不到我的表格

时间:2018-07-03 14:39:21

标签: python django django-forms

我不明白为什么我看不到自己的表格。

我想创建一个带有下拉菜单的表单,其中以“骑手模型”的display_name作为选择。

我的模型。py:

class Rider(models.Model):
    first_name = models.CharField(max_length = 256,blank= True)
    last_name = models.CharField(max_length = 256,blank= True)
    display_name = models.CharField(max_length = 256,blank= True)
    birth = models.DateTimeField(default=timezone.now)
    place_of_birth = models.CharField(max_length = 256,blank= True)
    age = models.IntegerField(default = 0,blank= True)
    nationality = models.CharField(max_length = 256,blank= True)
    height = models.FloatField(default = 0.0 ,blank= True)
    weight = models.FloatField(default = 0.0 ,blank= True)
    team = models.CharField(max_length = 256, blank= True)
    team_code = models.CharField(max_length = 256, blank= True)
    cost = models.IntegerField(default = 0,blank= True)


    def __str__(self):
        return self.display_name

我的form.py:

class ScoreForm(forms.ModelForm):
   riders =forms.ModelChoiceField(queryset=Rider.objects.all(),to_field_name="display_name")
   class Meta:
      model = Rider
      fields = ('display_name',)

我的view.py:

class ScoreView(TemplateView):
    form_class = ScoreForm
    model=Rider
    template_name = 'blog/score.html'

我的score.html:

{% extends 'blog/base.html'%}
{% block content %}
<h1>Score page</h1>
<form method="POST" >
    {% csrf_token %}
    {{form}}
    <button type="submit" class="save btn btn-default" name="button">Save</button>
</form>
{% endblock %}

截屏: Screenshot

1 个答案:

答案 0 :(得分:1)

要在模板上下文中自动包含表单,请子类FormView而不是TemplateView。表单视图将根据form_class自动创建一个表单实例,并将其插入模板上下文中,您可以在其中使用标签{{ form }}来呈现它。

from django.views.generic.edit import FormView

class ScoreView(FormView):
    ...

https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#form-handling-with-class-based-views