Add data into a model in Django

From TRCCompSci - AQA Computer Science
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.TextField(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. We need to import your form and a few other functions, so add:

from .forms import ProductForm
from django.contrib import messages
from django.shortcuts import redirect

And then add the following method for the functionality:

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

Now in the 'urls.py' file in the project folder we need to add a new urlpattern. So add the following:

path('addproduct/', myapp_views.addproduct, name='addproduct'),

addproduct.html

In the 'templates' folder in the 'MyApp' app, create the following 'html' page:

{% extends "MyApp/base.html" %}

{% block content %}
<h2>Add Product</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Add</button>
</form>
{% endblock %}

Testing

Run your server and visit your webapp, add '/addproduct' to the address bar to access your new add product page.