Difference between revisions of "Add data into a model in Django"
(→urls.py) |
(→addproduct.html) |
||
Line 61: | Line 61: | ||
=addproduct.html= | =addproduct.html= | ||
+ | In the 'templates' folder in the 'MyApp' app, create the following 'html' page: | ||
+ | |||
+ | <syntaxhighlight lang=html> | ||
+ | {% 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 %} | ||
+ | </syntaxhighlight> |
Revision as of 14:04, 17 September 2019
This will assume you have created a model for 'Products' from the previous tutorial.
Contents
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
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 %}