Home > Software design >  Django modal autoimplement
Django modal autoimplement

Time:08-01

Can anyone advise on how to deal with retrieving data from other models in Django? I was able to put information with the name of the company in the form, but after choosing from dropdown, I would like the tax identification number from database to be completed automatically. The problem is both the automatic completion and the binding and extraction of data.

p[1]: https://i.stack.imgur.com/V3TJ7.png p[2]: https://i.stack.imgur.com/qZYAG.png

Model:

klient_lista = Klient.objects.all().values_list("nazwa_firmy", "nazwa_firmy")

class Faktura(models.Model):
    numer = models.CharField(max_length=260, blank=False, null=False, unique=True)
    klient = models.CharField(max_length=260, choices=klient_lista)
    NIP = models.CharField(max_length=260)
    kwota_netto = models.FloatField(blank=False, null=True)
    VAT = models.FloatField(blank=False, null=True)
    kwota_brutto = models.FloatField(blank=False, null=True)

views:

@login_required
def Faktury(request):
    faktura = Faktura.objects.all()
    faktura_Form = Faktura_Form(request.POST or None)
    if faktura_Form.is_valid():
        faktura_Form.save()
        return redirect(Faktury)
    return render(request, 'Faktury.html', {'form': Faktura_Form, 'faktura': faktura})

CodePudding user response:

You don't need to store klient objects in a variable instead use foreign key to connect the two tables. I hope you refer to the "number" field by tax identification number and it is defined in klient model.

class Faktura(models.Model):
    klient = models.ForeignKey(Klient,on_delete=models.CASCADE)
    NIP = models.CharField(max_length=260)
    kwota_netto = models.FloatField(blank=False, null=True)
    VAT = models.FloatField(blank=False, null=True)
    kwota_brutto = models.FloatField(blank=False, null=True)

To use client name include following in you client model

class Klient(models.Model):
    ...model fields
    
    def __str__(self):
        return self.name

replace name with the field which stores client name

CodePudding user response:

I stores it in the Klient model, same as the company name.

  • Related