vendredi 5 juillet 2019

Multiple models inlineformset django

I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store)

A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus

So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User")

  1. The second is "Product" that has as foreignKey the "ProductPlace" model
  2. The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model

I created formsets associated to these three models in the "forms.py" file. But i don't know how to do for "views.py"

#models.py

from django.db import models
from django.core.validators import FileExtensionValidator
from .validators import validate_file_extension
from django.contrib.auth import get_user_model

User = get_user_model()

# Create your models here.
class ProductPlace(models.Model):
    name = models.CharField(max_length=50)
    num_road = models.IntegerField(blank=False, null=False)
    name_road = models.CharField(max_length=50)
    postal_code = models.IntegerField(blank=False, null=False)
    city =  models.CharField(max_length=50)
    country =  models.CharField(max_length=50)
    acquired_by = models.ForeignKey(User, related_name="product_places", 
                            null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField(blank=False, null=False)
    place = models.ForeignKey(ProductPlace,related_name="products", on_delete=models.CASCADE)
    class Meta:
        ordering = ('name',)
    def __str__(self):
        return self.name

class Menu(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField(blank=False, null=False)
    place = models.ForeignKey(ProductPlace, related_name="menus", on_delete=models.CASCADE)
    class Meta:
        ordering = ('name',)
    def __str__(self):
        return self.name


#forms.py

from django import forms
from .models import *
from django.forms.models import inlineformset_factory, modelformset_factory
from django.contrib.auth import get_user_model

User = get_user_model()

ProductPlaceFormSet = inlineformset_factory(
    User, ProductPlace, fields=['name', 'num_road', 'name_road', 'postal_code', 'city', 'country'], 
    extra=1, can_delete=True
)       


ProductFormSet = inlineformset_factory(
    ProductPlace, Product, fields=['name', 'price'], 
    extra=1, can_delete=True
)       

MenuFormSet = inlineformset_factory(
    ProductPlace, Menu, fields=['name', 'price'], 
    extra=1, can_delete=True
)       

I would like to obtain a form view with add button and delete button for product place, product and menu




Aucun commentaire:

Enregistrer un commentaire