Как подключить тему с bootstrap к django
Перейти к содержимому

Как подключить тему с bootstrap к django

  • автор:

Integrating Bootstrap to Django

Now that you have Django web application ready either with PostgreSQL database installed or deployed to either Heroku or custom domain or just a plain local Django application, you want to have frontend look of a Bootstrap theme that you saw. Of course, Bootstrap framework comes with it’s own goodies of responsiveness and much of heavy lifting of front-end work done for you. I was bit curious/afraid how a standalone template could be integrated into Django’s regimented project layout. Hence, this tutorial is for this purpose and … it’s straightforward!

This github repository has the completed tutorial. This is how a project layout for only directory looks before and after integrating bootstrap:

As you see we have added a bunch of directories in static directory of Django framework.

For this article, I am using startbootstrap-bare theme. Cloned the theme’s github repository. This is how the theme’s layout for only directory looks like:

As you can see, I copied the vendor and its children directory to static directory of Django. I had cloned the theme in the root level of my Django project. So before copying the vendor directory to static folder of Django, href ed files in vendor directory by giving a relative path. Alas, it didn’t work. Got 404 Page not found. Well, that was a pretty straightforward try though. ��

After some re-reading Django’s managing static files documentation, copied vendor directory to static folder and rest of addendum of the theme eg. README , License to vendor-license directory under static folder. That took care of where to keep Bootstrap folders in Django.

Now taking care of template. Copied Bootstrap’s index.html file to polls directory that is under templates directory. Now here I need to href to Bootstrap theme’s css and js files. As per Django, loaded static template tag and href static files. This is an overview of how href ing vendor ‘s files looks like in the index.html file.

Here is a screenshot of local running of the application:

After it, did rest of refactoring of the index.html file to base.html , extended it to index.html file and put polls questions there. This is how it looks after initial customization of the theme.

I am wondering how other frontend framework such as React or Vue is integrated to Django. Process must be pretty similar.

Anyways, Congratulation for integrating Bootstrap theme to your Django app! Hope this helps with your development!

Using Bootstrap to Style a Django App

Using the crispy tag and Bootstrap 5 for nicer styling of Django apps.

Feb 3, 2021 • 4 min read

Django allows building simple (and complex) web apps quickly, using Django Templates for rendering. By default, forms, buttons, and other elements are not styled and look quite ugly:

Django form without Bootstrap.

Django form without styling.

Using Bootstrap and django-crispy-forms , the rendered templates can easily be improved to look much nicer, without having to adjust styling manually. For example:

Django form styled with Bootstrap.

Django form styled with Bootstrap.

As an example, I extend my Django “Hello World” App (described in a previous post) by adding a simple form and rendering it with Bootstrap and django-crispy-forms . All it does is asking for the user’s name and a date and then displaying <username> says «Hello World!» on <date> and a counter of how often the button has been clicked. Still, the small example illustrates how to use Bootstrap and django-crispy-forms . Especially with many or large forms, django-crispy-forms becomes useful to reduce repetitive boilerplate.

Installing django-crispy-forms

Install the dependency and also add it to requirements.txt .

Add crispy_forms inside settings.py :

Enable the Bootstrap 4 template pack, adding the following line to settings.py :

So far, there is no official ‘bootstrap5’ template pack, but the ‘bootstrap4’ pack also seems to work with Bootstrap 5, which I use later.

Building a crispy Form

Creating a Django Form

As an example, I create a new form that allows users to specify their name and an arbitrary date that will be displayed in the “Hello World” app. For that, I create helloworld/forms.py with the following content:

Most field arguments are optional but provide additional information for django-crispy-forms to display in the Bootstrap form.

I then use this form inside views.py for my index view (the only view of the “Hello World” app so far):

Finally, show the form in the index.html template:

Now, when running the development server, the app shows the new form:

Django form without Bootstrap.

The “Hello World” message should display the entered username and date as well as the total click count. However, the form does not yet use Bootstrap and is still quite ugly!

Making the Form Pretty

To make the form look nicer, I first include Bootstrap. For using Bootstrap, simply include the Bootstrap CCS and JavaScript inside the head of the Django app’s main/base template. The Bootstrap website has the latest instructions.

For my “Hello World” Django app, I simply add the following lines inside helloworld/templates/helloworld/index.html :

This loads the new Bootstrap 5 from the JSDeliver CDN network so it can be used within the Django app templates. Now, the alert and button should already look nicer, but the form fields will still look ugly.

To also render the form fields with Bootstrap, I use django-crispy-forms . All it takes, is loading crispy and passing the form to crispy inside index.html :

Now, the Django app should be rendered with Bootstrap and already look much nicer:

Django form styled with Bootstrap.

The nice thing is that crispy will handle all the overhead of styling each form field with bootstrap, which is particularly useful when having many large forms inside a Django app.

What Next?

Small example apps I built with Django and deployed on Heroku, using Bootstrap:

How can I use Bootstrap with Django?

I’m learning python and Django coming from PHP. This is all really exciting, and I would love to use Bootstrap with Django to create sexy web pages.

As I understand it (I’m following the Django tutorial on their website), Django uses «apps» which can be included in your settings.py file. I did a quick search and found several bootstrap-themed apps, but have no knowledge on how to pick the right one. Is there a standard app most people use? All I need are the bootstrap.css and bootstrap.js files.

I’m sure I could manually place them in my root, but I’d enjoy an «all inclusive» setup within my Django install.

4 Answers 4

Re-reading your question, it seems that you’re searching for a way to install Twitter Bootstrap as a Django app. While there are some apps out there that facilitate using Twitter Bootstrap with Django, you don’t really need to use any of them.

You can simply include the Twitter Bootstrap CSS and JS at either the project or app level and refer to them in your Django templates.

To include Twitter Bootstrap in a Django app, your best bet is to:

Use Static Files

In your settings.py , add the path to Bootstrap (which you should download and place in your Django app under a folder named static :

Also, make sure your STATIC_URL prefix is set:

Now, download Twitter Bootstrap and place it in the path there:

Include Twitter Bootstrap in your templates

I would link to Twitter Bootstrap documentation, but there isn’t any, really. Your best bet is to take a look at the source of their starter template. Using the Django templating system is a bit beyond the scope of this question, but I’ll give you this hint: Anywhere in the starter template where you find a link to a .css or .js, replace it with your STATIC_URL.

I use the starter template as my base.html and include <% block content %>blocks in base.html that can be replaced by the actual content in my templates, which <% extend base.html %>.

Or, use a 3rd party app to guide you

You might investigate is the Django Bootstrap Toolkit, which I have not used myself. I would suggest doing it yourself manually first, however, as a way to explore the project and to really understand what is going on. It’s not too hard at all!

How to use Bootstrap 5 with Django the right way

There’s a more preferred and easy way to use Bootstrap 5 with Django.

Please enable JavaScript

In the past, you would use Bootstrap CDN service as the source for the Bootstrap CSS & JavaScript files, and often only Bootstrap version 4 would be supported by Django.

But, there’s a new and simpler way to add Bootstrap 5 to your Django project.

How to add Bootstrap 5 to your Django web application?

You add Bootstrap as the frontend CSS framework for your Django web application using a Python package called django-bootstrap5. You install django-bootstrap5 by opening the Terminal, activating the virtual environment you have installed Django, and running pip install django-bootstrap5.

The preferred way to install the Bootstrap framework for your Django application is using the django-bootstrap5 Python package that can be installed using pip.

  1. The new syntax
  2. You do not need additional packages like Django Crispy Forms to style your forms.

So, let’s get started and show you a step-by-step process to how you can use Bootstrap 5 with Django application to style the frontend of your web application and the forms.

How to add Bootstrap 5 to your Django project

First, let’s create a new Django project.

Open a new Terminal window, navigate into the Desktop folder, and create a new folder for our new Django project.

You may create a Django project folder anywhere on your file system.

Create a new environment that you will use to install Django and the django-bootstrap5 package

Use the command below if you already have a particular directory for all your virtual environment.

/.virtualenvs directory to store all my virtual environments. Use your preferred directory

If you want to create the same directory I use for all my virtual environments, use the command below:

After creating the virtual environment, activate it and install Django and django-bootstrap5 packages

After installing the packages and their dependencies, create a new Django project in the same folder that you had created earlier. I used the Desktop directory earlier.

I used DjangoWoof as the name of my project, but you can use any name for your Django project.

After successfully creating a new Django project, open the project’s folder with your favourite IDE or editor.

Add django_bootstrap5 to list of installed apps

Open the main project settings.py file and add django_bootstrap5 to your installed apps.

Next, create a new templates folder inside the main directory of your Django project (directory with the manage.py file).

Inside the templates directory, create a new file and name it base.html

You can use the Terminal to create the folder and file or use the IDE.

Using the Terminal, type the following:

If you are using the IDE, click File, then New File or New Folder

After creating the templates directory and base.html, open the main settings.py file and replace the following line in the TEMPLATES variable inside the DIRS dictionary key

Initially, your TEMPLATES variable will look like this:

Configure TEMPLATES variable to render templates on Django project

Replace ‘DIRS’: [] with this line

Your final TEMPLATES variable should now look like this

Configure Django to use templates folder for the base template

Open the base.html file you had created earlier and add the following lines at the top of the file – inside the <head> tag.

Create a template block that you will use for your project’s templates – add the following lines to the <body> tags

You can name the template block any name you want.

Your final file should look like this:

Your Django application is ready to use Bootstrap as the frontend framework to style your pages.

If you are at this point, you can skip ahead and start using Bootstrap tags to style your Django application pages.

For demonstration, let’s create a simple Django application that allows users to send information using a contact form.

How to Build a Contact Form for Django Application with Boostrap 5 Styling

Missing a contact form for your Django web application must be very unusual – you will need a way for your users to communicate with you without having to open an email app.

Besides, you can use a contact form to receive important feedback on your website’s user experience.

You can use a Django contact form to receive users’ contact information and store it in the database for future communication.

If you want to know more about how to develop websites with Django, you should definitely check out Django for Beginners: Build Websites with Python and Django OR this resource page that includes books, courses, and a career path that takes you from a complete beginner to a professional full-stack web developer.

Let’s dive right into making a new contact form.

You can create a new app to create a functionality only designed for processing contact information.

Taking this approach allows you to add functionality to your contact form later.

For example, you may opt to integrate your Django application with MailChimp – then, it will be easier when you have a separate app.

Create a new contact app.

Open the Terminal and type the following:

How to add an app in Django

Add the contact app to your installed apps

Let’s start by creating the model forms for the contact app. Open the models.py files inside the contact folder and add the following lines of code:

Here, we are using the name, email, and message fields as the attributes of the Contact table.

Django makes it easy to create tables, attributes, and relationships using the model.

The model will allow us to use the database to create persistent contact information.

After defining the models, you should run the makemigrations command to translate the above Python code into SQL statements.

With that, we use the python manage.py makemigrations command.

Open the Terminal and run the following:

However, we have only translated the SQL statement, but we have not made any changes to the database that would remain permanent in the database we are using.

Use the migrate command to run the actual SQL commands generated by the makemigrations commands.

The result should indicate that the contact database table has been successfully created.

Now let’s create the form that will send data to the database table, contact.

The one thing I love about Django is how easily you can use boilerplates to extend functionality.

Instead of creating new forms, we can use model forms to render the attributes we defined in the database.

A model form provides an interface you can use to create an HTML form from an existing database model with a few lines of code. Find more information about Django models in this article I have written.

Let’s define a model form for our Contact model.

Inside the contact folder, create a new file and name it forms.py.

Open forms.py and add the following lines of code:

The ContactForm instance will create an HTML form that we will use to collect data and save it to our contact table in the database.

The subclass ModelForm defines the specific form fields and corresponding HTML form widgets used across the form.

The Python class Meta defines the connection to which model to connect to and the fields that we want on our form.

In this case, we use all the fields in the database table.

You may use the exclude attribute to keep the default attribute from appearing on the form.

Now, the form is complete, and we need to render the HTML form code to our template. We need to set up the views to render the generated form HTML.

Open the views.py file that is inside the contact folder and add the following lines:

Here, we’re importing the generated form HTML, adding it to the context dictionary, and defining the template that the view will use to display the dynamic data on the front end of our web application.

Create a new folder inside the contact app and name it templates. Inside the templates folder, create a new file and name it contact.html.

Open the contact.html file and add the following code

We cannot view the generated form template because we do not have a URL for the contact form. Let’s create the URL endpoint for our contact form.

Open the main urls.py file that is inside the project folder. Add the following line at the top:

Under the admin endpoint, add the following line of code:

Your final urls.py file should look like this:

how to register app url endpoints on Django

Here, we are instructing Django to include the contact app URL endpoints in its URL endpoints. Without these lines, we cannot be able to access the contact form URL endpoint.

After that, create another urls.py file inside the contact folder.

The urls.py file of the contact app will include all the URLs used by the contact app. Mostly, any URL that starts with /contact will live inside this file.

Open the contact urls.py file and add the following lines of code:

The code above imports the contact form view we will render when one visits the /contact page of our website.

However, we have not included another contact/ because we already included it in the main urls.py file.

Otherwise, the file URL will be /contact/contact/ if we were to include that here.

Run Django development server:

If we open the /contact URL, 127.0.0.1:8000/contact/, you can see the name, email, and message attribute rendered on our HTML template.

Rendering Django forms on a HTML template

However, our form doesn’t look nice.

Let’s try to style it up – which was the purpose of this tutorial.

Open the contact.html template inside the contact/templates folder and replace the whole file with the following lines of code:

Rendering Django forms using Bootstrap 5 frontend framework

And voila! You have a very nice contact form for your web application.

We can go into deeper details on how to customize the form and use the Bootstrap 5 frontend framework on your Django app.

The code used in this tutorial is available on GitHub, be sure to check it out or use it as a template for your new Django projects.

If you want to be a professional Django web developer, you should read these books.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *