Django formsets:在保存表单/数据之前分配值

时间:2018-06-01 09:03:50

标签: django

我创建了一个formset,之后将保存在数据库中。该套装有两个字段' ticket' &安培; '量&#39 ;.在我的模型中,还有两个附加字段' order_reference'和' ticket_name',应在保存表单之前分配。你能帮助我实现这个目标吗?

models.py

class ReservedItem(models.Model):
    order_reference = models.CharField(
        max_length=10
        #unique=True
    )
    ticket = models.ForeignKey(
        Ticket,
        on_delete=models.PROTECT,
        related_name='reserved_tickets'
    )
    ticket_name = models.CharField(max_length=100)
    quantity = models.IntegerField(default=0)

views.py

def event_detail(request, event, organiser):
    queryset = Event.objects.filter(organiser__slug=organiser)
    event = get_object_or_404(queryset, slug=event)

    tickets = []
    for ticket in Ticket.objects.all():
        tickets.append({'ticket': ticket})

    ReserveFormSet = formset_factory(ReserveForm, extra = 0)
    formset = ReserveFormSet(
        initial=tickets
        # Example with qty how tickets above looks [{'quantity': 1}, {'quantity': 4}, {'quantity': 2},]
        )

    if request.method == 'POST':
        formset = ReserveFormSet(request.POST, initial=tickets)

        if formset.is_valid():
            for form in formset:
                if form.cleaned_data['quantity'] > 0:

                    # QUESTION: How do I assign the values 'order_reference' & 'ticket_name' before saving the form in the database

                    form.save()
                    print("SAVED.")

    return render(request, 'events/event_detail.html', {'event': event, 'formset': formset})

forms.py

class ReserveForm(forms.ModelForm):

    class Meta:
        model = ReservedItem
        fields = ['ticket', 'quantity']

1 个答案:

答案 0 :(得分:2)

我发布它的那一刻,我在另一篇文章中找到了解决方案。解决方案如下。对不必要的帖子抱歉。

if formset.is_valid():
            for form in formset:
                if form.cleaned_data['quantity'] > 0:
                    obj = form.save(commit=False)
                    obj.ticket_name = 'ticket_name'
                    obj.order_reference = 'order_reference'
                    obj.save()
                    print("SAVED.")