Skip to main content

Django – Getting Data from PostgreSQL and Showing it to Template

In this Django tutorial, we’ll see how we can get the data stored in the database and display it to the template.

Prerequisites

Have a look on the previous article, in which we’ve seen how to create an app, model and create a super user to work with admin interface.

https://www.thecrazyprogrammer.com/2019/01/django-models.html

So let’s start.

Getting Data from PostgreSQL and Showing it to Template

1. Upload Data First

We’ve already created a model Job inside jobs app, which is having two fields ImageField and CharField, ImageField for storing a picture for a particular job and TextField to store the summary about that job.

Screenshot of Model Job:

Getting Data from PostgreSQL and Showing it to Template 1

Screenshot of Admin Panel:

Getting Data from PostgreSQL and Showing it to Template 1

Getting Data from PostgreSQL and Showing it to Template 3

Currently we have no data inside our database. So let’s upload some data using the admin panel. (we’ll also see how to upload data using templates in later articles). So click on ADD JOB button and upload some pics and text.

Getting Data from PostgreSQL and Showing it to Template 4

So I’ve added two Job objects. Now let’s see how to get them and print them on the template.

Getting Data from PostgreSQL and Showing it to Template 52. Create a Template

Now I am going to create a template inside the jobs App. You can also create outside the App as we have created in the previous article. But as we’re going to show jobs on that template so its a good idea to create the templates related to the jobs App inside the App.

So to create a template inside app, first create a directory named as templates inside the jobs app, then create a directory with the same name as app inside templates. So our directory structure will look like this:

Getting Data from PostgreSQL and Showing it to Template 6

Inside this jobs folder we’ll create a HTML file named as myjobs.html.

Getting Data from PostgreSQL and Showing it to Template 7

3. Create a URL Path for Template

To create a url path, open your urls.py file and add a path for our newly created template myjobs.html.

Currently we’ve only one path in our urls.py, which we have also used to open admin panel.

Getting Data from PostgreSQL and Showing it to Template 8

And now add this line to load images from MEDIA_ROOT:

+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

To use static and settings in above line we’ve to import:

from django.conf.urls.static import static

from django.conf import settings

So finally our urls.py will look like:

from django.contrib import admin
from django.urls import path
from jobs import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('admin/', admin.site.urls),
    path('myjobs/', views.showjobs),
 ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

Now we’ll add one more path to navigate to myjobs template.

urls.py:

from django.contrib import admin
from django.urls import path
from jobs import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myjobs/', views.showjobs),
]

So I’ve added a new path for my jobs have two parameters, first is the URL to navigate to myjobs.html and second one is a functions name which will describe what to do when someone open the URL ‘domain-name.com/myjobs’, in our case it is https://localhost:8000/myjobs.

So now we’ve to create a function named as showjobs inside the views.py of jobs app. If you’re wondering that how we can access views.py file of jobs app in urls.py, then take a look on the third line in above code where I had imported views of jobs app.

4. Create a Function to Return the Template

Open views.py file and add a function named as showjobs.

views.py:

from django.shortcuts import render
from .models import Job

def showjobs(request):
    jobs = Job.objects
    return render(request, 'jobs/myjobs.html', { 'jobs':jobs } )

Getting Data from PostgreSQL and Showing it to Template 9

In the second line we’ve imported our model Job to get access to all the Job objects stored in our database. In Line 5, we’re getting all the objects from database and store it into the new variable called jobs. At last we’re passing that jobs variable with the same key name to the template.

5. Edit Template File to Show Jobs

myjobs.html:


Now run the server and open the link below:

 http://localhost:8000/myjobs/

Getting Data from PostgreSQL and Showing it to Template 10

So that’s all. Finally we got our data from database and displayed it on the template.

How it is Working

Let’s say, a user want to access a web-page on our website, his/her request will be redirected to the urls.py. For example – user tries to access domain-name.com/myjobs/ (https://localhost:8000/myjobs) so his request will be redirected to urls.py looking for a path having ‘myjobs/’ after domain name.

  • In urls.py, we have a path for myjobs (line 10)

  path(‘myjobs/’, views.showjobs),

After requested URL found, the request will be redirected to the function written along with the path. In our case it is views.showjobs.

  • In views, we have a functions called showjobs

Getting Data from PostgreSQL and Showing it to Template 11

which is receiving the request and return a HTML template myjobs.html to the user along with the all the objects stored in the database.

So now myjobs.html will be displayed to the user.

  • On myjobs.html page:

on template we’ve all the objects of model Job sent from the showjobs function. So we’ll loop through all the objects using for loop and display it.

Getting Data from PostgreSQL and Showing it to Template 12

To display the image we’ve used <img> tag and to print the summary, the <p> is used.

So that’s all for this tutorial.

If you’ve any confusion related with this topic, let us know in the comment box.

The post Django – Getting Data from PostgreSQL and Showing it to Template appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2019/02/django-getting-data-from-postgresql-and-showing-it-to-template.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and

Top Tips For PCB Design Layout

Are you thinking about designing a printed circuit board? PCBs are quite complicated, and you need to make sure that the layout that you choose is going to operate as well as you want it to. For this reason, we have put together some top tips for PCB design layout. Keep reading if you would like to find out more about this. Leave Enough Space One of the most important design tips for PCB layout is that you need to make sure that you are leaving enough space between the components. While many people might think that packing components closely is the best route to take, this can cause problems further down the line. This is why we suggest leaving extra space for the wires that will spread. This way, you’ll have the perfect PCB design layout. Print Out Your Layout Struggling to find out if your components sizes match? Our next tip is to print out your layout and compare the printed version to your actual components. Datasheets can sometimes come with errors, so it doesn’t hurt to do