[Answer]-What is the best way to create a parent/master entry in a DJANGO CRUD database app and then add associating data fields to the parent/master?

1👍

No. You don’t need multiple barcode models. The fact that you have a ForeignKey from barcode to hardware already allows you to have multiple barcodes for each hardware: a ForeignKey defines a many-to-one relationship. Also, it doesn’t make any sense to name the foreignkey after the model it is in: it needs to be named for the model it is pointing to, ie hardware. Finally, don’t prefix your field names with the model name: that’s unnecessary.

class Hardware(models.Model):
    text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=timezone.now)
    def __unicode__(self):             
        return self.text

class Barcode(models.Model):
    hardware = models.ForeignKey(Hardware)
    text = models.CharField(max_length=50)
    #pub_date = models.DateField(default=timezone.now)
    def __unicode__(self):             
        return self.text

Now, in order to enter the barcodes along with the hardware, you need to use an inline formset.

from django.forms.models import inlineformset_factory

def get_barcode(request):
    BarcodeFormSet = inlineformset_factory(Hardware, Barcode, form=BarcodeForm)
    hardware = Hardware()
    if request.method == 'POST':
        form = HardwareForm(request.POST, instance=hardware)
        formset = BarcodeFormSet(request.POST, instance=hardeware)
        if form.is_valid() and formset.is_valid():
            hardware = form.save()
            barcodes = formset.save()
            return redirect('/successpage/')
    else:
        form = HardwareForm(instance=hardware)
        formset = BarcodeFormSet(instance=hardeware)
   return render(request, 'get_barcode.html', {'form': form, 'formset': formset}) 

Leave a comment