问题
I am currently trying to bring my function-based view into a class-based view. The question I am currently struggling with is if I should either trying to move it into a TemplateView with FormMixin or in a FormView with ContextMixin. Do you have any tips on how to decide what's best?
def event_detail_view(request, event, organizer):
queryset = Event.objects.filter(organizer__slug=organizer)
event = get_object_or_404(queryset, slug=event)
tickets = collect_all_tickets(event, organizer)
ReserveFormSet = formset_factory(ReserveForm, formset=BaseReserveFormSet, extra=0)
formset = ReserveFormSet(
initial=tickets,
# Example [{'ticket': "Early Bird"}, {'ticket': "Regular Ticket"},]
form_kwargs={'organizer_slug': organizer}
)
if request.method == 'POST':
formset = ReserveFormSet(
request.POST,
initial=tickets,
form_kwargs={'organizer_slug': organizer}
)
if formset.is_valid():
order_reference = unique_order_reference_generator()
for form in formset:
ticket_name = form.cleaned_data['ticket'].name
int_or_empty = form.cleaned_data['quantity']
qty = is_int_or_zero(int_or_empty)
if qty > 0:
obj = form.save(commit=False)
obj.ticket_name = ticket_name
obj.order_reference = order_reference
obj.save()
return redirect('organizers:index', organizer=organizer)
ticket_status = {}
ticket_status['sold_out'] = TicketStatus.SOLD_OUT
ticket_status['on_sale'] = TicketStatus.ON_SALE
return render(request, 'events/event_detail.html', {
'event': event,
'formset': formset,
'ticket_status': ticket_status,
'tickets': tickets
})
回答1:
Class-based-views are not automatically better than function-based-views. If you have a function-based-view, then think carefully about whether you want to convert it to a class-based-view.
Django's generic CBVs are not designed for formsets. I often see people trying to process formsets in UpdateView
or CreateView
and in my opinion it leads to complicated code that is difficult to understand.
If you must use a class based view to handle your formset, you might want to look at django-extra-views which contains some views you might find useful.
来源:https://stackoverflow.com/questions/50857793/django-templateview-or-formview