我想访问通过formset输入的模板中的数据。 表单集中的数据在Django Admin中显示为TabularInline。 我想从created.html模板中的表单集中获取数据。 根据Trip模型和Buchungen模型的数据,我可以轻松访问。 我只能访问该人员模型中的数据。 我怎样才能最好地解决这个问题?
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.views.generic import CreateView
from django.forms import modelformset_factory
from daytrips.models import Trip
from .models import Buchungen, Person
from .forms import BuchungForm
from .forms import PersonenFormset
from .forms import BasePersonFormSet
def buchung(request, id):
trip = get_object_or_404(Trip, id=id)
if request.method == 'POST':
form = BuchungForm(request.POST, initial={'preis': trip.preis, 'reiseziel': trip.reiseziel, 'datum_abfahrt': trip.datum_abfahrt} )
formset = PersonenFormset(request.POST)
if form.is_valid() and formset.is_valid():
buchung = form.save()
for form in formset:
person = form.save(commit=False)
person.buchung = buchung
person.save()
return render(request, 'buchung/created.html', {'buchung': buchung, 'person': person, 'trip': trip})
else:
form = BuchungForm(initial={'preis': trip.preis, 'reiseziel': trip.reiseziel, 'datum_abfahrt': trip.datum_abfahrt})
formset = PersonenFormset()
return render(request, 'buchung/create_detail.html', {'trip': trip, 'form': form, 'formset': formset, })
created.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Ihre Buchung ist abgeschlossen
{% endblock %}
{% block content %}
{% include "buchung/orders_created_header.html" %}
<div class="main main-raised">
<div class="container">
<h3>Reisedaten</h3>
<p>{{ trip.reiseziel }}</p>
<p>{{ trip.datum_abfahrt }}</p>
<h3>Ihre Daten</h3>
<p>{{ buchung.vorname }}</p>
<p>{{ buchung.nachname }}</p>
<p>{{ buchung.adresse}}</p>
<p>{{ buchung.plz }}</p>
<p>{{ buchung.personenanzahl }}</p>
<p>{{ buchung.gesamt }} € inkl. Mwst.</p>
<p>Reiseteilnehmer</p>
{% for buchung in buchungen %}
<p>{{buchung.person.vorname }}</p>
<p>{{person.buchung.nachname }}</p>
<p>{{person.geburtsdatum }}</p>
{% endfor %}
</div>
</div>
{% endblock %}
谢谢您的努力。