Add data into a model in Django

From TRCCompSci - AQA Computer Science
Revision as of 11:58, 17 September 2019 by Admin (talk | contribs) (Created page with "This will assume you have created a model for 'Products' from the previous tutorial. =forms.py= Within your app folder you should have a file called 'forms.py', if you haven'...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This will assume you have created a model for 'Products' from the previous tutorial.

forms.py

Within your app folder you should have a file called 'forms.py', if you haven't you need to create it.

You will need to import the following:

from django import forms
from .models import Product

You can then create a new class for your product form:

class ProductForm(forms.ModelForm):
    name = forms.CharField(required=True)
    manufacturer = forms.CharField(required=True)
    description = forms.CharField(required=True)

    class Meta:
        model=Product
        fields = ['name','manufacturer','description']
from .models import Product

The 'ProductForm' class specifies data types and that some fields are required. The 'date_added' was set up to be automatic so no input is required.

The internal class 'Meta' binds the model to the form, and you can also specify which fields to show.