Django - 渲染模型在不使用Forms或ModelForms时在模板中选择

时间:2018-02-04 12:09:37

标签: django django-templates html-form

我创建了一个模型,其中一个字段有选择。我在模板中创建了一个选择表单,但未显示选项。我出于几个原因没有使用Forms或ModelForms。但我的理解是,我应该能够在模型中使用CHOICES,在模板中构建表单并使用对象管理器保存信息。我如何获得填充表单的选择?

Models.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>

使用{%表示评分%}         {{rating.choices}}         {%endfor%}无效。如果我正在构建自己的表单,我可以在模型中设置选项吗?如果是的话,我做错了什么,这不是渲染?

3 个答案:

答案 0 :(得分:0)

如果您严格不想使用FormModelForm,则需要选择可以通过enum进行迭代。 您可以查看我的示例代码,了解如何使用枚举here实现选择。

完成此操作后,您必须对上下文和模板进行一些调整。 您可能希望查看how to get the list of choices with enum

答案 1 :(得分:0)

试试这个

{% for rating in ratings %}
<select name="ratings">
    <option value="">Choose From List</option>
    {% for x, y in rating._meta.get_field('rating').choices %}
        <option value="{{ x }}">{% if rating.rating == x %} selected{% endif %}> 
            {{ y }}
        </option>
    {% endfor %}
</select>
{% endfor %}

确保此代码在

之外
{% for rated in time %}
...
{% endfor %} 

答案 2 :(得分:0)

最简单,最简单且100%的工作方法是:

使用[lets say 'my_Model_with_choices']获取对象my_Model_with_choices = yourModel.objects.first(),然后使用my_Model_with_choices._meta.get_field('your_foreign_key_variable_name').choices

获取选择。
def f_page(request, Function_id):
     assignments = Function.objects.get(id=Function_id)
     ratings = NewRating.RATING_CHOICES

context = {
    'ratings' : ratings,
}
return render (request, 'project/pager.html', context)

内部HTML模板:

<select class="custom-select col-md-5" name="ratings" id="ratings" required>
    <option disabled selected value="">Ethnic Group</option>
    {% for value, ratings_group in ratings  %}
    <option value='{{value}}'>{{ratings_group}}</option>
    {% endfor %}
</select>