Difference between revisions of "Add data into a model in Django"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(views.py)
(views.py)
Line 50: Line 50:
 
         return render(request, '/addproduct.html', {'form':form})
 
         return render(request, '/addproduct.html', {'form':form})
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
I have commented the key parts of the code above.
  
 
=urls.py=
 
=urls.py=
 
=addproduct.html=
 
=addproduct.html=

Revision as of 13:58, 17 September 2019

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']

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.

views.py

Now within your app folder we need to use 'views.py' to create a view for our add product form.

def addproduct(request):
    if request.method=='POST': # this means the form has data
        form = ProductForm(request.POST) # get the form and it data
            if form.is_valid(): # check if it is valid
                name = form.cleaned_data.get('name') # clean the data
                manufacturer = form.cleaned_data.get('manufacturer') # clean the data
                description = form.cleaned_data.get('description') # clean the data
                form.save() # save the data to the model
                messages.success(request, 'Your product has been added!')
                return redirect('\products')
            else: # form not valid so display message and retain the data entered
                form = ProductForm(request.POST)
                messages.success(request, 'Error in creating your product, the form is not valid!')
                return render(request, '/addproduct.html', {'form':form})
    else: #the form has no data
        form = ProductForm() #produce a blank form
        return render(request, '/addproduct.html', {'form':form})

I have commented the key parts of the code above.

urls.py

addproduct.html