Creating a website with Django and installing a template and passing data to the template from form ( Part 2 )
Part 2 :
- Connecting Feedback Form and Linking it to Visitors’ Feedback block
- Display our Database to our website
- Now connecting our form to our feedback block and to our database
Continuation of part 1. If you’ve not read part 1 please do , Part 1
Connecting Feedback Form and Linking it to Visitors’ Feedback block
Ok so here’s Our website after some fixes and restructuring
We are going to connect the form as show above to the Visitors’ Feedback as show below. Yes whatever feedback a visitor enters would be stored in our database and display on our feedback section.
Now looking inside Article folder you will see a file named models.py. we need to add models to it.
What is a model?
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. — source : Django doc
With all that .. it’s just data for your database :)
so let’s create our first model. We have to create fields that are same as in our feedback form.
Editing models.py :
Our model must be a class and must always pass models.model into it.
import our models library
from django.db import models
models.Model
calls django.db
and creates a table in our sqlite3 database.
We’ll define a variable that allows us to enter in text. We need one for Name, Email and Feedback.
In Pic 24 as you can see the fields I’ve created.
Our name field have a max_lenght of characters of 30.
Email have a lenght of 50 because sometimes email can be long.
Feedback is a text field where our visitors can enter their feedback.
Both Created and UUID are automatically created. UUID is a index key for our feedbacks because using the default key is too easy to get.
Now we define a function called__str__
which returns our data. Please note that our __str__ function always passes string item so if you’re passing an int or number pls use str() function to convert it to string.
from django.db import models
import uuidclass feedback(models.Model):
Name = models.CharField(max_length = 30)
Email = models.CharField(max_length= 50)
Feedback = models.TextField(null = False, blank = False)
Created = models.DateTimeField(auto_now_add = True)
UUID = models.UUIDField(default = uuid.uuid4,
unique = True,
primary_key = True,
editable = False
)
def __str__(self):
return str(self.Name)
Save it, and Now we make the migrations to the database by entering the following command :
python manage.py makemigrations
and then migrating it to our database with
python manage.py migrate
We will get the following :
We need to register our model , to do this we go to our admin.py file and enter the following code :
The code outside the red box is what we added and as you can see django makes things super easy for us, it imports the admin library for us without having to do that.
from django.contrib import adminfrom .models import feedback# Register your models here.
admin.site.register(feedback)
You may be wondering why we register the app well let’s see why.
In our webbrowser with our local server running go to http://127.0.0.1:port/admin
Ok we end up to this login page
We don’t have a credentials so we would need to make one. In order to do this, in our cmd we run the following command :
python manage.py createsuperuser
This would create an account in our database for us.
It will ask you for the following information:
- Username
- Password
- Password (again)
Now after doing this we can now sign in our admin page.
Here’s our panel
As you can see under article we have a section called Feedbacks.
All our models that we create must be in singular form and when it shows in django admin page , it’ll be plural
If we did not register our model it would not show in our admin panel.
Let’s Add 2 more feedbacks. Just click on the _ Add Feedback _ button on the right.
Display our Database to our website.
Now in order to do this we need to go to our views.py in Article ( our application folder )
from django.shortcuts import render
from .models import feedback# Create your views here.def Home(request) :FBacks = feedback.objectscontext = {
'Feedbacks' : FBacks,
}return render(request,'Article/index.html', context)
The following modifications are made. So what we did was import our models library to our views.py file and call our feedback class as show above. we then add it to a dictionary called context and pass it to the render function.
Now we go to our index.html file template and look for the following codes :
We now would modify this and render it in our website.
In the the line between div and article where single slide is located , we’ll implement {% %}
so that we can write python code.
Since we could have multiple feedbacks, we’ll use a for
statement.
{% for feedback in Feedbacks.all %}
and we must always end a for loop with
{% endfor %}
for each variables we get it by calling it in double curly brackets
eg {{feedback.Name}}
Our html code would look like this
As you can see we inherited our classes and used it where it’s necessary so now our rendered website would look like this :
Isn’t it amazing how django renders our feedback and displays it in our template. It’s so wow.
Now connecting our form to our feedback block and to our database
We need to create a new python file in our Article folder meaning our application folder
so we create a new file named forms.py and import forms from django
from django import forms
We now create a new class called Feedbackform and pass forms.Forms into it
We then do the following :
Pic 38 : shows how we got the form structure from above. As you can see we create 3 variables, each variables have its own attributes and lengths
Here’s raw code :
from django import formsclass FeedbackForm(forms.Form):
Name = forms.CharField(
max_length = 30,
widget = forms.TextInput(
attrs={'class' : 'form-control',
'type' : 'text',
'id' : 'name',
'placeholder' : 'Enter Your Name',
'name' : 'name',
}
)
)
Email = forms.CharField(
max_length = 50,
widget = forms.TextInput(
attrs={'class' : 'form-control',
'type' : 'text',
'id' : 'email',
'placeholder' : 'Enter Your Email',
'name' : 'email',
}
)
)
Feedback = forms.CharField(
max_length = 1000,
widget = forms.TextInput(
attrs={'class' : 'form-control',
'id' : 'message',
'placeholder' : 'Enter Your Feedback',
'name' : 'message',
'rows' : '3',
}
)
)
After finishing up with our forms.py we now need to go to our views in our application folder and edit it.
We need to import additional libraries
from django.shortcuts import redirect
from .forms import FeedbackForm
from django.views.decorators.http import require_POST
We imported these libraries as they would be useful in our form post request.
we now need to instantiate our class
We need to create a new function that would add our post information to our database. We add this in the following method :
Most forms would look similar to this format.the @required_Post
is a decorator variable that lets a view only accepts the POST method. So that others don’t exploit this method.
Our whole code now :
from django.shortcuts import render, redirect
from .models import feedback
from .forms import FeedbackForm
from django.views.decorators.http import require_POST# Create your views here.def Home(request) :FBacks = feedback.objects.order_by('Created')
form = FeedbackForm()
context = {
'Feedbacks' : FBacks,
'Form' : form,
}return render(request,'Article/index.html', context)@require_POST
def addFeedbackItem(request):
form = FeedbackForm(request.POST)
if form.is_valid():
new_feedback = feedback(Name = request.POST['Name'],
Email = request.POST['Email'],
Feedback = request.POST['Feedback']
)
new_feedback.save()
return redirect('Home')
As you can see we return a redirect('home')
We would need to add this new url to our urls.py file in our application folder ( Article ).
We add the following code
"""Article URL Configuration
"""from django.urls import path
from . import viewsurlpatterns = [
path('', views.Home, name = "Home"),
path('add', views.addFeedbackItem, name = 'Add'),
]
Editing our form data in our html file
Now let’s edit our form html
Looking at our html we can see that form does not have an action attribute. We would need to add one and then also declare a variable called csrf
This is a token for our post request
Our code would look like this
As you can see the codes that are in the rectangle is what we add and modify in our form code block. You notice in the first part action="{% url 'Add' %}"
this is another way to call our url function in urls.py. the Name Add is a direct link to our html data instead of calling the entire path name.
After modifying our form block we now save and refresh our website
When we press submit or enter we would get an error. If you happen to get an error or nothing happens then go down to the javascript section at the bottom of the body and comment out this line :
<script type="text/javascript" src="{% static 'Article/js/jquery.validate.min.js' %}"></script>
Now refresh and try again and it should work fantastic !!
What Part 3 will have :
- Webscraping my medium profile for the amount of articles I have
- Setting up another model to save the data that was scraped
- Rendering the data that was scraped and saved into the website
- Adding links connected to articles.
End of PART 2
— — — — — — — — — — — — — — — — — — — — — — — —
Resources :
You can find the resources in my github repo:
Here’s a link to the git repo : https://github.com/surenjanath/Django-Medium-Article
Do note that if you want to start from scratch I’ve put the original template inside my repo folder called IMPORTANT
Other resources :
Please see part 1 : Creating a website with Django and installing a template and passing data to the template from form ( Part 1 )