Django形式&从模型中渲染数据

时间:2018-04-12 14:01:37

标签: django forms django-forms formset

我目前正在努力使用Django表单。基于票证模型,我生成了这个表单集,用户可以在其中选择所需票证的数量。将它们重定向到结帐页面后。

我的问题是,当我使用{{form.ticket}}时,我会得到一个选择字段,但这不是我想要的。我只想打印出票,如下面的截图所示。

任何人都可以帮助我吗?

应该如何:

enter image description here

目前情况如何:

enter image description here

views.py

from django.forms import formset_factory
from django.shortcuts import redirect, render

from .forms import EntryModelForm
from .models import Ticket
from orders.models import Order, Entry

# Create your views here.
def choose_ticket_and_quantity(request):

    tickets = []
    for ticket in Ticket.objects.all():
        tickets.append({'ticket': ticket})

    EntryFormSet = formset_factory(EntryModelForm, extra=0)
    formset = EntryFormSet(initial=tickets)

    if request.POST:
        o = Order.objects.create()
        request.session['order_id'] = o.order_id

        formset = EntryFormSet(request.POST, initial=tickets)

        if formset.is_valid():
            for form in formset:
                if form.cleaned_data['quantity'] > 0:
                    entry = form.save(commit=False)
                    entry.order = o
                    entry.save()

            return redirect('http://127.0.0.1:8000/checkout')

    return render(request, "tickets/choose_ticket_and_quantity.html", {'formset': formset})

forms.py

from django import forms

from orders.models import Entry

class EntryModelForm(forms.ModelForm):

    class Meta:
        model=Entry
        fields = ['ticket', 'quantity']

choose_ticket_and_quantity.html

<form method="post" action="">
    {% csrf_token %}
    {{ formset.management_form }}

    {% for form in formset %}
        <ul>
            <li>{{ form.ticket }}</li>
            <li>{{ form.quantity }}</li>
        </ul>

    {% endfor %}

    <p><input type="submit" value="Checkout"></p>
</form>

我在这里也尝试了这一点,但遗憾的是,由于我的表格无法再被验证并且所有票证类型已经打印在一起,因此无法正常工作:

{% for choice in form.ticket.field.choices %}
{{choice.1}}
{% endfor %}

2 个答案:

答案 0 :(得分:0)

您希望显示该字段的值:

<li>{{ form.ticket.value }}</li>

答案 1 :(得分:0)

试试这个

在app / templatetags中添加模板标签get_ticket.py(也添加__init__.py

from django import template
register = template.Library()
# import Ticket model

@register.simple_tag
def get_ticket(pk):
    ticket = Ticket.objects.get(pk=int(pk))
    return ticket.name # is it name?

在您的模板中

{% load get_ticket %}
<form method="post" action="">
    {% csrf_token %}
    {{ formset.management_form }}
    <ul>
    {% for form in formset %}
        <li>
            <strong>{% get_ticket form.ticket.value %}</strong><br>
            <input type="hidden" name='{{form.ticket.name}}' value='{{form.ticket.value}}'>
            {{ form.quantity }}
        </li>
    {% endfor %}
    </ul>
    <p><input type="submit" value="Checkout"></p>
</form>