我想更新使用model_formset取消的model_field。为了“通知”用户,我还想显示值first_name, last_name & ticket_reference
。但是,这迫使必须包含{{ form.ticket_reference }}
等,以便将其隐藏在__init__
中。有更好的方法吗?
views.py
RefundFormSet = modelformset_factory(
Attendee,
form=CancelTicketForm,
extra=0,
)
order = Order.objects.get(
order_reference=order_reference,
)
attendee = [{'attendee': attendee} for attendee in order.attendees.all()]
if request.method == 'POST':
formset = RefundFormSet(
request.POST,
queryset=order.attendees.all(),
)
if formset.is_valid():
# do something with the formset.cleaned_data
print("FORMSET SUCCESS")
instances = formset.save(commit=False)
for instance in instances:
instance.save(update_fields=['canceled'])
print(instance, "SAVED...")
else:
form = RefundForm()
formset = RefundFormSet(
queryset=order.attendees.all(),
)
forms.py
class CancelTicketForm(forms.ModelForm):
class Meta:
model = Attendee
fields = ['canceled', 'first_name', 'last_name', 'ticket_reference', ]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['ticket_reference'].widget = forms.HiddenInput()
self.fields['first_name'].widget = forms.HiddenInput()
self.fields['last_name'].widget = forms.HiddenInput()
template.html
<form method="post">
{{ formset.management_form }}
{% csrf_token %}
{% for form in formset %}
{{ form.id }}
{{ form.canceled }}
{{ form.first_name.value }}
{{ form.first_name }}
{{ form.last_name.value }}
{{ form.last_name }}
{{ form.ticket_reference.value }}
{{ form.ticket_reference }}
{% endfor %}
<button class="btn btn-primary" type="submit">
{% trans "Refund" %}
</button>
</form>