【发布时间】:2018-07-14 10:37:27
【问题描述】:
我创建了一个模型,其中一个字段有选择。我在模板中创建了一个选择表单,但未显示选择。出于几个原因,我没有使用 Forms 或 ModelForms。但我的理解是,我应该能够在模型中使用 CHOICES 来完成这项工作,在模板中构建一个表单并使用对象管理器保存信息。如何获得填充表单的选项?
模型.py
class NewRating(models.Model):
EXCELLENT = 'EX'
GOOD = 'GD'
FAIR = 'FR'
BAD = 'BD'
RATING_CHOICES = (
(EXCELLENT, 'Excellent'),
(GOOD, 'Good'),
(FAIR, 'Fair'),
(BAD, 'Bad')
)
function = models.ForeignKey(Function, related_name='frating')
timeline = models.ForeignKey(Timeline, related_name='trating')
rating = models.CharField(max_length=25,choices=RATING_CHOICES)
Views.py
def f_page(request, Function_id):
assignments = Function.objects.get(id=Function_id)
time = Timeline.objects.all()
ratings = NewRating.objects.all()
context = {
'assignments': assignments,
'time' : time,
'ratings' : ratings,
}
return render (request, 'project/pager.html', context)
HTML
<div id=for_rat>
{% for rated in time %}
<form action= "/project/rated" method='POST'>
{% csrf_token %}
{{rated.segment}}
<input type="hidden" name="year" value="{{rated.year}}">
<input type="hidden" name="month" value= "{{assignments.id}}">
<select name="ratings">
<option value="">Choose From List</option>
{% for rating in ratings %}
<option value="{{rating.choices}}">{{rating.choices}}</option>
{% endfor %}
</select>
{% endfor %}
<input type="submit" value="Save">
</form>
</div>
使用 {% for rating in rating %} {{评分.选择}} {% endfor %} 不工作。如果我正在构建自己的表单,我可以在模型中设置选项吗?如果是,我做错了什么,这不是渲染?
【问题讨论】:
-
choices不是您的NewRating模型的属性。你应该在你的模板中显示{{ rating.rating }} -
它没有用。向下滚动中没有选择。
-
你让事情变得比他们需要的更难。没有什么理由不使用表单。
标签: django django-templates forms