Django:Formset不保存,因为条目已存在

时间:2019-01-22 23:47:49

标签: python django

我有一个面对这些情况之一的表单集。 1)不存在数据库条目。每个“表单”的新条目都被创建。 2)数据库条目已存在,但将被更新。

1)使用我的代码,我在此处附加。 2)不起作用。我总是收到错误“已经存在”。 (没关系,它已经存在,但是在那种情况下,它应该更新条目,而不是向我显示错误)

有人可以帮助我吗?

forms.py

class SocialTixForm(forms.ModelForm):
        class Meta:
            model = SocialTix
            fields = (
                'coin_mode',
            )

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            for visible_field in self.visible_fields():
                visible_field.field.widget.attrs['class'] = 'form-control'

class SocialTixCoinAllocationForm(forms.ModelForm):

    class Meta:
        model = Coins
        fields = (
            'ticket',
            'coins',
        )

views.py

class AdminIncluencerPreferences(AdminPermissionRequiredMixin, AdminBaseAmbassadorView, TemplateView):
    """
    This view will show the ambassador preferences
    """
    template_name = 'influencer/admin/preferences.html'
    success_message = _("Settings have been successfully created.")

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['social_form'] = self.social_form
        context['social_coin_allocation_formset'] = self.social_coin_allocation_formset
        return context

    @cached_property
    def social_form(self):
        return SocialTicketingForm(
            instance=self.request.event.event_extension,
            data=self.request.POST or None,
        )

    @cached_property
    def social_coin_allocation_formset(self):
        CoinAllocationFormset = formset_factory(
            SocialTicketingCoinAllocationForm,
            extra=0
        )
        return CoinAllocationFormset(
            data=self.request.POST or None,
            initial=self.request.event.tickets.tickets_as_list(),
        )

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        if (self.social_form.is_valid() and
                self.social_coin_allocation_formset.is_valid()):

            self.social_form.save()
            self.social_coin_allocation_formset.save()

models.py

    class Coins(TimeStampedModel):
                ticket = models.OneToOneField(
                    Ticket,
                    on_delete=models.PROTECT,
                    related_name='coins',
                )
                coins = models.PositiveIntegerField(
                    verbose_name='Coins',
                )

    class TicketManager(models.Manager):
            """
            Used for AdminAmbassadorPreferences to allocate coins for tickets
            """
            def tickets_as_list(self):
                tickets = self.get_queryset()
                ticket_list = [{'ticket': ticket} for ticket in tickets]
                return ticket_list


    class Ticket(TimeStampedModel):

            event = models.ForeignKey(
                Event,
                on_delete=models.CASCADE,
                related_name='tickets',
            )  # CASCADE = delete the ticket if the event is deleted
            tax = models.ForeignKey(
                'Tax',
                on_delete=models.PROTECT,
                related_name='tickets',
                blank=True,
                null=True,
            )  # PROTECT = don't allow to delete the ticket tax if a ticket exists
            name = models.CharField(
                max_length=100,
                verbose_name=_("Ticket Name"),
            )
            objects = TicketManager()

0 个答案:

没有答案