Home > OS >  Django ModelForm with Access to More than One Model
Django ModelForm with Access to More than One Model

Time:10-01

So, i want to know if it possible to have a django modelform access more than 1 django model... i currently have 2 models relating to the product and they are shown below...the reason i made 2 models is to allow each product to have multiple images

class Product(models.Model):
    title = models.CharField(max_length=255)
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    thumbnail = models.ImageField(upload_to='uploaded_products/', blank=True, null=True)
    description = models.TextField(max_length=255, null=True, blank=True)
    categories = models.ManyToManyField(Category,related_name='products', blank=True, help_text="Select One or More Categories that the product falls into, hold down ctrl to select mutiple categories")
    tags = models.ManyToManyField(Tag, blank=True)
    stock = models.PositiveIntegerField(default=1, blank=True)
    notes = models.TextField(null=True, blank=True)
    ownership = models.FileField(blank=True, null=True, upload_to='product_files', help_text='Optional : provide valid document/picture to proof ownership (presence of this document increases the reputation of your product).Note: Provided Document if invalid or incorrect can be invalidated after upload')
    verified = models.BooleanField(default=False, blank=True, null=True)
    uploader = models.ForeignKey(Account, on_delete=models.CASCADE, blank=True)
    serial_number = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        ordering = ['-updated']

    def __str__(self):
        return self.title

class Product_Image(models.Model):
    name = models.CharField(max_length=255, blank=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='uploaded_products/')
    default = models.BooleanField(default=False, blank=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.name:
            self.name = self.product.title
        super().save(*args, **kwargs)

Now i want to be able to access both models in a modelform and edit appropriate..currently i tried adding the second model to the model Meta class attribute and it clearly showed that it is not possible that way.... if accessing 2 models is not possible, what possible solution can i apply to my current model structure to maintain the ability to allow a product to have multiple images . thanks as i look forward to a working solution.

CodePudding user response:

forms.py:

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = [add your field from this model here]

class ImagePostForm(ProductForm):
    #define the field your want here from Product_Image(using forms)
    image = forms.ImageField(label='Image',widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta(ProductForm.Meta):
        fields = ProductForm.Meta.fields   ['image',#add the field your want from Product_Image here]

Now inside your views.py you can just call ImagePostForm.you can do something like this
views.py

from .forms import ImagePostForm
from .models import Product,Product_Image
def your_view(request):
    if request.method=='POST':
            form=ImagePostForm(request.POST or None,request.FILES or None)
            files = request.FILES.getlist('image')
            if form.is_valid():
                post = form.save(commit=False)
                #add the things your want to add here after that you can save it  
                post.save()
                if files:
                        for f in files:
                            Product_Image.objects.create(product=post,image=f)
                redirect('the view here')
    else:
         form = ImagePostForm()
         return render(request,'your-template',{'form':form})
  • Related