How To Store A Value In Django Template
In our getting started with Django tutorial, I showed yous how to get a Django site upward and running. The templates we rendered were very basic though.
This is definitely not how you desire your site to wait like.
How do you become your site to look amend? Simple! Add some styling. In this tutorial, I volition show you how to add some CSS and JavaScript to your Django templates in guild to make them look much better. To practice that, you get-go need to understand the concept of static files in Django.
Setting upwardly a Django Project
Let's ready our test Django projection. First, create a folder chosen projects which is where our app will live.
mkdir projects && cd projects Inside projects, let'due south utilize virtualenv to create an environment for our app's dependencies.
virtualenv env --python python3 NOTE: If you practice not accept virtualenv installed, install it using the command pip install virtualenv.
Once that is done, activate the environment by running the actuate beat out script.
source env/bin/activate If that command works, you should see an (env) prompt on your terminal.
#(env)~/projects $ Everything await fine? Awesome! Permit's now use pip to install Django into our environment.
#(env)~/projects $ pip install django That command should install Django into your environment. As of the time of writing, the Django version is i.x.4.
We are so going to telephone call the django-admin script to create our Django app. Permit's do that like this:
#(env)~/projects $ django-admin startproject djangotemplates If you check your projects folder structure, you lot should at present take a new folder called djangotemplates created by Django in addition to the earlier env binder nosotros created.
cd into djangotemplates.
Your folder construction should now be similar to this:
djangotemplates --djangotemplates ----**init**.py ----settings.py ----urls.py ----wsgi.py --manage.py All done? Y'all are now fix to begin!
Settings for managing static files
Static files include stuff like CSS, JavaScript and images that you lot may want to serve alongside your site. Django is very opinionated about how you should include your static files. In this article, I volition testify how to go about adding static files to a Django awarding.
Open the settings.py file inside the inner djangotemplates folder. At the very bottom of the file you lot should encounter these lines:
# djangotemplates/djangotemplates/settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.x/howto/static-files/ STATIC_URL = '/static/' This line tells Django to append static to the base url (in our case localhost:8000) when searching for static files. In Django, y'all could have a static binder well-nigh anywhere you want. You can even have more than than ane static binder due east.g. 1 in each app. All the same, to keep things uncomplicated, I will use just one static binder in the root of our project binder. Nosotros will create ane later. For at present, permit'southward add some lines in the settings.py file and then that it looks like this.
# djangotemplates/djangotemplates/settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/ane.10/howto/static-files/ STATIC_URL = '/static/' # Add these new lines STATICFILES_DIRS = ( bone.path.join(BASE_DIR, 'static' ) , ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles' ) The STATICFILES_DIRS tuple tells Django where to wait for static files that are not tied to a particular app. In this case, we but told Django to also expect for static files in a folder called static in our root folder, not merely in our apps.
Django also provides a mechanism for collecting static files into ane place so that they can be served hands. Using the collectstatic command, Django looks for all static files in your apps and collects them wherever you told it to, i.due east. the STATIC_ROOT. In our case, we are telling Django that when we run python manage.py collectstatic, assemble all static files into a folder called staticfiles in our projection root directory. This characteristic is very handy for serving static files, peculiarly in production settings.
App setup
Create a folder called static on the same level as the inner djangotemplates folder and the manage.py file. You should at present have this structure:
djangotemplates --djangotemplates ----**init**.py ----settings.py ----urls.py ----wsgi.py --static --manage.py Inside this folder is where we will take any custom CSS and JS nosotros choose to write. On that notation, let's add two folders inside the static binder to hold our files, 1 called css and the other called js. Within css, create a file called main.css. Add a main.js in the js folder as well. Your static folder should now look like this:
--static ----css ------master.cs ----js ------main.js In one case that is done, let's create a new Django app chosen instance that we will be working with. Do yous recollect how to practice that? Don't worry, information technology's quite simple.
#(env)~/projects/djangotemplates $ python manage.py startapp example In one case that is done, y'all should accept a binder called example alongside djangotemplates and static. And of course you should notwithstanding exist able to see the manage.py file.
djangotemplates --djangotemplates ----**init**.py ----settings.py ----urls.py ----wsgi.py --example --static --manage.py We need to tell Django about our new app. Get to the inner djangotemplates folder, open up settings.py and look for INSTALLED_APPS. Add example under the other included apps.
# djangotemplates/djangotemplates/settings.py DEBUG = True ALLOWED_HOSTS = [ ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'example' , # Add this line ] Just to recap, we at present have the following folder structure:
djangotemplates --djangotemplates ----**init**.py ----settings.py ----urls.py ----wsgi.py --example ----migrations ------**init**.py ----admin.py ----apps.py ----models.py ----tests.py ----views.py --static ----css ------main.cs ----js ------main.js --manage.py URL definition
Permit'south define a URL to go to our new app. Let'southward edit djangotemplates/djangotemplates/urls.py to effect that.
# djangotemplates/djangotemplates/urls.py from django.conf.urls import url, include # Add include to the imports here from django.contrib import admin urlpatterns = [ url( r'^admin/' , admin.site.urls) , url( r'^' , include( 'case.urls' ) ) # tell django to read urls.py in instance app ] After that, in the case app folder, create a new file called urls.py and add the following code:
# djangotemplates/example/urls.py from django.conf.urls import url from instance import views urlpatterns = [ url( r'^$' , views.HomePageView.as_view( ) , proper noun= 'abode' ) , # Notice the URL has been named url( r'^virtually/$' , views.AboutPageView.as_view( ) , name= 'almost' ) , ] The lawmaking we have only written tells Django to match the empty route (i.e localhost:8000) to a view called HomePageView and the road /about/ to a view chosen AboutPageView. Call back, Django views accept in HTTP requests and render HTTP responses. In our case, we shall utilize a TemplateView that returns a Home Folio template and another i for the Virtually folio. To do this, inside your example app folder, create another folder called templates. Inside the new templates binder, create two new files called index.html and virtually.html. Your example app folder should now have this structure:
--example ----migrations ------**init**.py ----templates ------alphabetize.html ------near.html ----admin.py ----apps.py ----models.py ----tests.py ----urls.py ----views.py Within the index.html, paste the following code:
<!-- djangotemplates/example/templates/index.html--> <! DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-viii" > <title > Welcome Dwelling </title > </head > <body > <p > "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </p > <a href = "{% url 'dwelling' %}" > Go Home </a > <a href = "{% url 'well-nigh' %}" > Nigh This Site </a > </body > </html > Add this lawmaking to well-nigh.html:
<!-- djangotemplates/example/templates/about.html--> <! DOCTYPE html > <html lang = "en" > <caput > <meta charset = "UTF-viii" > <championship > Most Us </title > </caput > <body > <p > Nosotros are a group of Django enthusiasts with the following idiosyncrasies: <ol > <li > We only consume bananas on Saturdays. </li > <li > Nosotros love making playing football on rainy days. </li > </ol > </p > <a href = "{% url 'domicile' %}" > Go Home </a > <a href = "{% url 'nigh' %}" > Virtually This Site </a > </body > </html > Notice how nosotros are referring to our links for Go Home and About This Site in our templates. Nosotros can employ Django's automatic URL reverse lookup because we named our URLs in our urls.py. Corking, huh!
We shall see the result of this code in the next section.
Wiring upward the views
Let'south add the final code to serve up our templates. We need to edit djangotemplates/instance/views.py for this.
# djangotemplates/instance/views.py from django.shortcuts import render from django.views.generic import TemplateView # Import TemplateView # Add together the ii views we have been talking nigh all this time :) class HomePageView (TemplateView) : template_name = "index.html" class AboutPageView (TemplateView) : template_name = "about.html" Now we tin can run our app. Nosotros first need to make Django's default migrations since this is the outset time we are running our app.
#(env)~/projects/djangotemplates $ python manage.py migrate Once that is done, first your server.
#(env)~/projects/djangotemplates $ python manage.py runserver Open your browser and navigate to http://localhost:8000. You should be able to see our home folio.
Clicking the links at the bottom should exist able to navigate you betwixt the pages. Hither is the About page:
Template Inheritance
Allow's shift our focus to the templates folder within the case app folder. At the moment, it contains two templates, index.html and about.html.
We would like both these templates to have some CSS included. Instead of rewriting the aforementioned code in both of them, Django allows united states of america to create a base template which they will both inherit from. This prevents us from having to write a lot of repeated code in our templates when we need to modify annihilation that is shared.
Let's create the base template now. Create a file called base.html in djangotemplates/example/templates. Write this lawmaking inside it:
<!-- djangotemplates/example/templates/base of operations.html --> {% load static %} <! DOCTYPE html > <html > <caput > <meta charset = "utf-eight" > <title > Django Sample Site - {% block championship %}{% endblock %} </title > <script src = "{% static 'js/chief.js' %}" > </script > <!-- This is how to include a static file --> <link rel = "stylesheet" href = "{% static 'css/main.css' %}" type = "text/css" /> </head > <body > <div class = "container" > {% cake pagecontent %} {% endblock %} </div > </body > </html > The very starting time line in the file, {% load static %}, uses Django's special template tag syntax to tell the template engine to use the files in the static folder in this template.
In the title tag, nosotros use a Django block. What this ways is that in whatsoever Django template which inherits from this base template, any HTML which is inside a block named title will be plugged into the title block. The same goes for the body tag'southward pagecontent block. If this sounds confusing, don't worry. Yous will come across it in action before long.
If you are not running your Django server, run it past executing python manage.py runserver in your terminal. Go to http://localhost:8000. You should see the previous template.
Now edit the alphabetize.html template to inherit from the base template.
<!-- djangotemplates/instance/templates/index.html --> {% extends 'base.html' %} <!-- Add together this for inheritance --> <! DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-8" > <title > Welcome Home </title > </head > <body > <p > "Lorem ipsum dolor sit down amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim advertizing minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </p > <a href = "{% url 'habitation' %}" > Go Home </a > <a href = "{% url 'nearly' %}" > About This Site </a > </torso > </html > Reload the page in your browser. Cipher appears! This is because Django expects your content to be written inside the blocks we divers in the base template and then that they can be rendered. Edit the alphabetize.html to add together the blocks:
<!-- djangotemplates/case/templates/index.html --> {% extends 'base.html' %} <! DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-viii" > <title > {% block title %}Welcome Home {% endblock %} </title > </head > <body > {% block pagecontent %} <p > "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat not proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </p > <a href = "{% url 'home' %}" > Go Home </a > <a href = "{% url 'about' %}" > About This Site </a > {% endblock %} </trunk > </html > Reload the folio in the browser and voila! Your content should announced again!
We tin too edit the well-nigh.html template to employ the aforementioned.
<!-- djangotemplates/instance/templates/about.html --> {% extends 'base.html' %} <!-- Add this for inheritance --> <! DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-viii" > <title > {% block title %}About Us {% endblock %} </championship > </head > <trunk > {% block pagecontent %} <p > We are a group of Django enthusiasts with the post-obit idiosyncrasies: <ol > <li > We only consume bananas on Saturdays. </li > <li > We love making playing football on rainy days. </li > </ol > </p > <a href = "{% url 'home' %}" > Go Home </a > <a href = "{% url 'well-nigh' %}" > About This Site </a > {% endblock %} </body > </html > You should now come across this on the Near page:
Which is exactly the same as before!
However, now since both templates inherit from a base template, I can easily style them. Open up upward master.css in your css binder and add these styles:
.container { background : #eac656; margin : 10 10 ten 10; border : 3px solid blackness; } This volition mode the container div which nosotros are loading our content into. Refresh your browser. You lot should come across this:
The Domicile Page:
The About Page:
Rendering templates with data from views
You tin use Django'due south template engine to display data in very powerful ways. In this section, I will create a Django view that will laissez passer data into a template. I will then evidence you how to access that information in the template and brandish it to the user.
Kickoff things get-go, open up views.py in the instance app folder. We will add a new view to serve data into our yet to exist data.html template. Modify the views.py file to look like this:
# djangotemplates/example/views.py from django.shortcuts import render from django.views.generic import TemplateView class HomePageView (TemplateView) : template_name = "index.html" class AboutPageView (TemplateView) : template_name = "about.html" # Add this view form DataPageView (TemplateView) : def get (self, request, **kwargs) : # we will pass this context object into the # template so that we can access the data # list in the template context = { 'data' : [ { 'name' : 'Celeb 1' , 'worth' : '3567892' } , { 'name' : 'Celeb 2' , 'worth' : '23000000' } , { 'proper name' : 'Celeb 3' , 'worth' : '1000007' } , { 'proper noun' : 'Celeb iv' , 'worth' : '456789' } , { 'proper noun' : 'Celeb 5' , 'worth' : '7890000' } , { 'name' : 'Celeb 6' , 'worth' : '12000456' } , { 'name' : 'Celeb 7' , 'worth' : '896000' } , { 'name' : 'Celeb 8' , 'worth' : '670000' } ] } return render(asking, 'data.html' , context) Nosotros are using the same kind of view we used to render the other templates. However, we are now passing a context object to the render method. The key-value pairs defined in the context volition be available in the template being rendered and we can iterate through them just like whatsoever other list.
To finish this upward, go to the urls.py file in the hi app and add together the URL pattern for our new view and then that it looks like this:
# djangotemplates/instance/urls.py from django.conf.urls import url from example import views urlpatterns = [ url( r'^$' , views.HomePageView.as_view( ) , name= 'habitation' ) , url( r'^about/$' , views.AboutPageView.as_view( ) , name= 'about' ) , url( r'^data/$' , views.DataPageView.as_view( ) , proper noun= 'data' ) , # Add this URL pattern ] Finally, let's create the template. In the templates folder, create a file called data.html and write this lawmaking inside it.
<!-- djangotemplates/case/templates/data.html --> {% extends 'base of operations.html' %} <! DOCTYPE html > <html > <head > <meta charset = "utf-viii" > <championship > </title > </head > <torso > {% block pagecontent %} <div course = "table-div" > <!-- We will display our information in a normal HTML table using Django's template for-loop to generate our table rows for us--> <table class = "table" > <thead > <tr > <th > Celebrity Proper name </thursday > <th > Internet Worth </th > </tr > </thead > <tbody > {% for celebrity in data %} <tr > <td > {{ celebrity.name }} </td > <td > {{ celebrity.worth }} </td > </tr > {% endfor %} </tbody > </table > </div > {% endblock %} </body > </html > In data.html, you can see that we use what is essentially a for loop to get through the data list. Binding of values in Django templates is washed using {{}} curly brackets much similar in AngularJS.
With your server running, go to http://localhost:8000/information/ to see the template.
Including snippets into your templates
Nosotros now have three templates, index.html, nearly.html and data.html. Let'due south link them together using a unproblematic navigation bar. First up, let's write the lawmaking for the navigation bar in another HTML template.
In the templates folder inside the instance app, create a new folder chosen partials. Inside it, create a file called nav-bar.html. The templates binder construction should at present be like this:
templates ----index.html ----about.html ----information.html ----partials ------nav-bar.html Edit the nav-bar.html partial then that it contains this code:
<!-- djangotemplates/instance/templates/partials/nav-bar.html --> <div form = "nav" > <a href = "{% url 'home' %}" > Go Home </a > <a href = "{% url 'well-nigh' %}" > About This Site </a > <a href = "{% url 'information' %}" > View Data </a > </div > Including snippets in a template is very simple. We use the includes keyword provided by Django'south templating engine. Go ahead and modify index.html to this:
<!-- djangotemplates/example/templates/index.html --> {% extends 'base of operations.html' %} <! DOCTYPE html > <html lang = "en" > <caput > <meta charset = "UTF-viii" > <championship > {% cake title %}Welcome Home {% endblock %} </title > </head > <body > {% block pagecontent %} <p > "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim advertizement minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </p > {% include 'partials/nav-bar.html' %} <!--Add this--> <!-- Remove these ii lines -- > <!-- <a href="{% url 'home' %}">Go Abode</a> --> <!-- <a href="{% url 'about' %}">About This Site</a> --> {% endblock %} </body > </html > Modify about.html to this:
<!-- djangotemplates/example/templates/near.html --> {% extends 'base.html' %} <! DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-8" > <title > {% block title %}About U.s. {% endblock %} </championship > </head > <torso > {% cake pagecontent %} <p > Nosotros are a group of Django enthusiasts with the post-obit idiosyncrasies: <ol > <li > We merely eat bananas on Saturdays. </li > <li > We love making playing football on rainy days. </li > </ol > </p > {% include 'partials/nav-bar.html' %} <!--Add this--> <!-- Remove these 2 lines -- > <!-- <a href="{% url 'habitation' %}">Go Domicile</a> --> <!-- <a href="{% url 'about' %}">About This Site</a> --> {% endblock %} </torso > </html > Lastly, modify data.html to this:
<!-- djangotemplates/example/templates/data.html --> {% extends 'base.html' %} <! DOCTYPE html > <html > <caput > <meta charset = "utf-8" > <championship > </championship > </head > <body > {% block pagecontent %} <div class = "table-div" > <table course = "table" > <thead > <tr > <th > Glory Name </th > <th > Cyberspace Worth </thursday > </tr > </thead > <tbody > {% for celebrity in data %} <tr > <td > {{ celebrity.name }} </td > <td > {{ celebrity.worth }} </td > </tr > {% endfor %} </tbody > </table > </div > {% include 'partials/nav-bar.html' %} <!--Add together this--> {% endblock %} </trunk > </html > Time to bank check out our work! Open your browser and navigate to http://localhost:8000. You should see this:
All the pages are at present linked with the navbar so you lot can easily navigate dorsum and forth through them, all with minimal code written. Here is the information.html template:
And here is almost.html:
Notation: I accept added the post-obit CSS to syle the links in the navbar. Feel free to use it or play with your own styles:
// djangtotemplates/static/css/main.css .container { groundwork : #eac656; margin : x ten 10 ten; border : 3px solid black; } .nav a { groundwork : #dedede; } Filters
Filters take data piped to them and output it in a formatted fashion. Django templates have access to the humanize collection of filters, which make data more than human readable. Let's brand the glory'south networth field in the data template more than readable past using some of these filters.
To use Django'southward humanize filters, you first demand to edit some settings. Open up up djangotemplates/settings.py and edit the INSTALLED_APPS list to this:
# djangotemplates/djangotemplates/settings.py ALLOWED_HOSTS = [ ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'django.contrib.humanize' , # Add this line. Don't forget the trailing comma 'instance' , ] Nosotros tin can at present use a filter in our templates. We are going to use the intcomma filter to add comma's in large numbers to brand them easier to read. Allow's alter information.html to this:
<!-- djangotemplates/example/templates/data.html --> {% extends 'base.html' %} {% load humanize %} <!-- Add this--> <! DOCTYPE html > <html > <head > <meta charset = "utf-8" > <title > </title > </head > <body > {% block pagecontent %} <div class = "tabular array-div" > <table class = "table" > <thead > <tr > <thursday > Celebrity Name </th > <thursday > Internet Worth </th > </tr > </thead > <tbody > {% for glory in information %} <tr > <td > {{ celebrity.name }} </td > <td > $ {{ glory.worth | intcomma }} </td > <!--Modify this line--> </tr > {% endfor %} </tbody > </table > </div > {% include 'partials/nav-bar.html' %} {% endblock %} </body > </html > When you go to http://localhost:8000/data/, you should now accept a more friendly list of internet worth values:
There are many more filters included in the humanize package. Read almost them hither
Collecting Static Files
Remember nosotros talked about collecting static files? Try the post-obit control:
python manage.py collectstatic You lot should see a prompt like the following:
You have requested to collect static files at the destination location every bit specified in your settings: /Users/amos/projects/djangotemplates/staticfiles This will overwrite existing files! Are yous sure you desire to do this? Type 'yes' to continue, or 'no' to cancel: Go ahead and say yes.
This command will tell Django to go through all your project folders, look for all static files and store them in ane place (the static root we defined in the settings). This is very efficient especially if you are deploying your site to production.
When you run the command collectstatic, y'all should see a new binder called staticfiles created in the root of your project binder. Y'all can alter this location to something else by editing the static root setting in your projection'southward settings.py file. To use these staticfiles, in your templates you lot volition say load staticfiles instead of load static. Everything else is the same as with using the previous static folder.
Decision
Congratulations on reaching the terminate of this tutorial! By now y'all should have a more detailed understanding of how Django templates work. If you need deeper information, call up the docs are your friend. You tin can notice the full code for this tutorial here. Brand sure to get out any thoughts, questions or concerns in the comments below.
How To Store A Value In Django Template,
Source: https://www.digitalocean.com/community/tutorials/working-with-django-templates-static-files
Posted by: johnsonroon1987.blogspot.com

0 Response to "How To Store A Value In Django Template"
Post a Comment