About Django, How to start? ▷ Questions and Answers

5/5 - (1 vote)

How to start with Django?

Django and Flask are the 2 most popular Python web frameworks.
Django is a full-stack framework for web app development, available open-source under the BSD license.
Get the latest official version 3.1 with pip (The Python Package Installer)

pip install Django==3.1

How to know the version of pip?

pip –version
pip -V

Why to use Virtual Environment for your Django Projects?

A Virtual Environment or a ‘venv’ is a Python module that creates a unique environment for each project.
What Virtual Environment does is to create an isolated environment (for example, a Django project) from others.

A Virtual Environment it’s not just a Django component. It can be used for other projects as well.

After creating a Virtual Environment we can install the packages that we need and are unique to that project, keeping your projects neatly organized.
I remember how my first Django project was installed globally on my computer and I had a lot of headaches when I wanted to put it live on a shared web server.

There are many advantages and it is recommended to start a new Django project in a virtualenv.

Find some below:

  • Using the virtual environment You can have multiple versions of python on your machine without them colliding, each version can be considered a development environment, and you can have different versions of libraries and python modules, all isolated from each other.
  • When you want to deploy your site on a host, will need to generate the requirements.txt file need for your project. Using a Virtual Environment You will list only the packages you need for your project inside venv, and not all global packages from your computer

How to create and activate a virtual environment in a project folder?

1. First, install the virtual environment it is not already installed.

pip install virtualenv

After,

2. Create a project directory

3. Change into the project directory

4. From that directory, run
on Linux

python3 -m venv name_of_virtualenv

on Windows

python -m venv name_of_virtualenv

After, activate the virtualenv:

Activate the virtualenv on Windows

  1. virtualenv creates a batch file
  2. inside from venv folder run Scripts\activate.bat

From the virtualenv directory install Django

pip install django

How to create a Django project?

To create a Django project, open the command prompt windows inside the desired folder and then type:

django-admin startproject name-of-project

The above instruction will create a folder named “name-of-project”.
If You will open this folder, will see the files that the script generated.
First, there’s a file called manage.py.

Beside it, there’s an inner folder called “name-of-project” that contains five files: __init__.py, asgi.py, settings.py, urls.py, wsgi.py.

The __init__ file tells Python that this folder contains Python files.

The settings file settings.py configures Django, and the urls file urls.py routes requests based on the URL.

How to Create an App in Django?

What is a Django app?

A Django application is a component within an overall Django project.

Each Django app supplies a set of related features for a specific purpose: a blog, an API server, a forum, etc.

An overall project might have one or many apps.

1. To create a new app, inside the project folder, where the manage.py file is located, type:

python manage.py startapp the_app_name

This instruction will create a new folder inside, which will contain the necessary files for Your Python application:

apps.py, the apps file controls settings specific to this app.

models.py, the models file provides the data layer, which Django uses to construct the database schema and queries.

A Django model is a class inheriting from django.db.models.Model with attributes that define the schema or underlying structure of a database table. Read more about models in Django

admin.py, the admin file defines an administrative interface for the app.

views.py, the views file defines the logic and control flow for handling requests and defines the HTTP responses that are returned.

Each view is represented by a Python function (or method, in the case of class-based views).

Each view can use templates.

A Django template is a separate file that consists of HTML code and syntax for variables, loops, and other control flows.

tests.py, the tests file can be used for writing unit tests for the functionality of the app.

The migrations folder holds files which Django uses to migrate the database.

2. Add the newly created app to the list of installed applications

Add the application in the INSTALLED_APPS, from the settings.py file, which was created when we launched the new project.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'the_app_name'
]

How to start the server, run the app?

To run the Django project, inside the project directory folder that contains the manage.py file type:

For Linux

python3 manage.py runserver

For Windows use python without the 3

python manage.py runserver

After in cmd will see

System check identified no issues (0 silenced).
March 24, 2021 - 01:06:17
Django version 3.1.7, using settings 'your_app_name.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Go to localhost http://127.0.0.1:8000/ in your browser

You will see the Django app working fine, like in the image below:

django run server

How to access the Django admin panel?

If you want to access the Django admin panel create a superuser from the command line:
Be sure you are in the directory that contains the manage.py file.

python manage.py createsuperuser

Fill in the required fields, only the password and username are required, email is optional.

Restart the server and You can log to the admin panel http://127.0.0.1:8000/admin/ with the chosen data.

How to create and use a Requirements.txt file for a Django Project?

A requirements.txt file is a file that lists all of the packages needed for the Django project to work. To create a requirements.txt file run the command below:

pip freeze > requirements.txt

Important!!

To list only the packages you need for your project inside venv, and not all global packages from your computer, first you have to activate the virtualenv, and from (venv) to run `pip freeze > requirements.txt` command.

pip freeze > requirements.txt

How to install all files in the requirements.txt file?

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

How to format a date in a Django template?

You can use filters built into Django. The format in Django is similar to PHP’s date() function with some differences. Read here how to formats a date.

Also if you want to translate the date into a specific language, not globally, but in a template, you can use:

{% load i18n %}
{% language 'ro' %}{{catalog.date_start|date:"d E Y" }}{% endlanguage %}

How to delete an old image when update ImageField?

Unfortunately, in Django when updating an image field, the original image file isn’t deleted from the hard.

Therefore, in order not to take up unnecessary disk space, you must delete it. There are several ways to do this:

Use django-cleanup package

The django-cleanup app automatically deletes files for FileField, ImageField, and subclasses. When a FileField’s value is changed and the model is saved, the old file is deleted.

When a model that has a FileField is deleted, the file is also deleted. A file that is set as the FileField’s default value will not be deleted.

First, install django cleanup package:

pip install django-cleanup

Then, add django_cleanup app in your settings.py INSTALLED_APPS:


INSTALLED_APPS = (
    ...
    'django_cleanup', # should go after your apps

)

Find here Django packages that I use in my projects

How to filter objects by ignoring upper and lower case letter?

Use iexact which takes all the arguments ignoring upper and lower case.

if ProductBrand.objects.filter(name__iexact=brand).exists():

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net