问题
I am currently struggling with Django forms. Based on the tickets model I generate this formset where users can choose the qty of tickets they want. After they will be redirected to the checkout page.
My problem is, when I use {{ form.ticket }} I get a select field but that's not what I'm looking for. I just want to print out the tickets as seen in the screenshot below.
Can anyone help me on that?
How it should be:
How it currently looks like:
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>
What I also tried was this here, but unfortunately, this didn't work either as my form couldn't be validated anymore and all ticket types have been printed together:
{% for choice in form.ticket.field.choices %}
{{choice.1}}
{% endfor %}
回答1:
Try this
Add a templatetag get_ticket.py
in app/templatetags (Add a __init__.py
too)
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?
In your template
{% 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>
回答2:
Looks like you want to display the value of the field:
<li>{{ form.ticket.value }}</li>
来源:https://stackoverflow.com/questions/49798621/django-form-rendering-data-from-model