Django 表单和模型渲染数据

Django form & rendering data from model

我目前正在为 Django 表单苦苦挣扎。基于门票模型,我生成了这个表单集,用户可以在其中选择他们想要的门票数量。之后他们将被重定向到结帐页面。

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

谁能帮我解决这个问题?

应该如何:

目前的样子:

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 %}

您似乎想要显示字段的值:

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

试试这个

在 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>