Django Model and Form that I want to make
Hello. I'm fairly new to Django and I have a hard time understanding which model field to use. I didn't post any code because my code is so messy right now and most of it still following "Django for Beginner" book by William S. Vincent.
I have an app consisting 2 models, Product
model and Production
model. Some fields on production model are linked to product model. Then from production model, I make a form for user input using ModelForm
. (There's a link to an image to help understanding model and form relation.)
I have several questions regarding this matter.
- If I set
product_id
onProduction
Model asForeignKey
toProduct
, what field should I use forproduct_name
andmaterial
? - When I use
CharField
for bothproduct_name
andmaterial
, there are entry for bothproduct_name
andmaterial
on form and I don't want that. How to change it to readonly and have value updated based onproduct_id
? (I'm not sure if this is related to Django form or not.) - Right now I'm using
ModelForm
to makeProduction
form and then usingFormView
to render the form. Is it the right approach? What is the difference between this one andCreateView
from model?
Thank you in advance for any comments and answers.
CodePudding user response:
If you have a name and a material on the product model, you don't need those on the production model unless they relate to the production object. If I were you, I'd have a foreign key on Production
to the product. It might look something like;
class Production(models.Model):
product = models.ForeignKey(
to=Product,
verbose_name=_("Product"),
on_delete=models.CASCADE
)
machine = models.CharField(
verbose_name=_("Machine No"),
max_length=255
)
date = models.DateTimeField(
verbose_name=_("Date"),
blank=True,
null=True
)
Then your form might be;
class ProductionForm(forms.ModelForm):
class Meta:
model = Production
fields = (
'product',
'machine',
'date',
)
I would recommend using the django admin to get your models as you want them before you start working with views. If you know the data is being stored in a way you need, then you can worry about building the frontend. The admin is around page 70 of that book you've got. You can also do readonly fields with that.