简体   繁体   中英

Best practice for accessing submitted form data in django for use before saving to database

I am developing an app in Django where I am suppose to save user Invoice details to database. One of the inputs from the user is a selection of payment type. I am supposed to pick this selection value and retrieve amount from database before I save to invoice. This what I have done so far. It is working well, but I am really doubting if this is the right way to do it.

Models.py

class Invoice(models.Model):
    invoice_status_choices = [
        ('1', 'Pending'),
        ('2', 'Paid'),
        ('3', 'Cancelled')
    ]
    invoice_number = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)
    description = models.CharField(max_length=100, blank=True)
    customer = models.ForeignKey(User, on_delete=models.CASCADE)
    payment_date = models.DateTimeField(blank=True, null=True)
    paid_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    invoice_status = models.IntegerField(choices=invoice_status_choices, default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.invoice_number)


class InvoiceItem(models.Model):
    invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE)
    listing = models.ForeignKey('listings.Listing', on_delete=models.CASCADE)
    payment_type = models.ForeignKey('SubscriptionType', on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=6, decimal_places=2)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f'{self.invoice.invoice_number} Items'


class SubscriptionType(models.Model):
    subscription_type = models.CharField(max_length=20)
    frequency = models.PositiveIntegerField()
    period = models.ForeignKey(PeriodNames, on_delete=models.CASCADE)
    rate = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.subscription_type

Here is the view that I need help with. The point of concern is the first function: get_invoice_item_amount . The complete view functions are:

view.py

def get_invoice_item_amount(payment_type):
    subscription_type = SubscriptionType.objects.get(id=payment_type)
    amount = subscription_type.rate
    return amount


@login_required
def create_invoice(request):
    """
    Allows a user to select list items.
    """
    user = request.user
    invoice_form = InvoiceForm()
    InvoiceItemFormset = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=1)

    if request.method == 'POST':
        invoice_form = InvoiceForm(request.POST)
        formset = InvoiceItemFormset(request.POST, request.FILES)
        if invoice_form and formset.is_valid():
            # try:
            #     with transaction.atomic():
            #
            # except IntegrityError: #If the transaction failed
            #     messages.error(request, 'There was an error creating an invoice.')
                # return redirect(reverse('profile-settings'))
            # return redirect("my_property_detail", property.id)
            invoice = invoice_form.save(commit=False)
            invoice.customer = request.user
            invoice_data = invoice.save()

            for f in formset:
                # amount = get_invoice_item_amount(f.cleaned_data['payment_type'].id)
                invoice_item = InvoiceItem(
                                invoice=invoice,
                                listing=f.cleaned_data['listing'],
                                quantity=f.cleaned_data['quantity'],
                                payment_type=f.cleaned_data['payment_type'],
                                amount = get_invoice_item_amount(f.cleaned_data['payment_type'].id))
                invoice_item.save()
            print("Data saved successfully!")
        else:
            print("Failed to validate")

    else:
        form = InvoiceForm()
        formset = InvoiceItemFormset()
        for n in formset:
            n.fields['listing'].queryset = Listing.objects.filter(status=False, listing_owner=user)

    context = {
        'form': invoice_form,
        'formset': formset
    }

    return render(request, 'payments/create_invoice.html', context)

I am calling the function inside the formset just before I save the invoice_item . Is that the right way? Or there is a recommended way of doing it.

This is a perfectly valid use case for cleaned_data . Accessing cleaned_data is no problem at all.

Just be aware that if you somehow modify values inside cleaned_data , it might cause errors when saving an instance based on it.

But in this case, where you're only reading a value, there is no problem at al..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM