How to create app django
How to create app django
Get started
It’s quick & easy to get up and running with Django.
Getting started with Django
Depending how new you are to Django, you can try a tutorial, or just dive into the documentation.
Want to learn more about Django? Read the overview to see whether Django is right for your project.
Install Django
Before you can use Django, you’ll need to install it. Our complete installation guide covers all the possibilities; this guide will get you to a simple, minimal installation that’ll work while you walk through the introduction.
Write your first Django app
Installed Django already? Good. Now try this tutorial, which walks you through creating a basic poll application. It’s got two parts:
Sharpen your skills
The official Django documentation covers everything you need to know about Django (and then some).
Join the community
You can help make us better. Find out about upcoming Django events, learn what’s on other Django developers’ minds, find and post jobs, and more.
Intro to Django
Object-relational mapper
Define your data models entirely in Python. You get a rich, dynamic database-access API for free — but you can still write SQL if needed.
URLs and views
To design URLs for an application, you create a Python module called a URLconf. Like a table of contents for your app, it contains a simple mapping between URL patterns and your views.
Templates
Django’s template language is designed to strike a balance between power and ease. It’s designed to feel comfortable and easy-to-learn to those used to working with HTML, like designers and front-end developers. But it is also flexible and highly extensible, allowing developers to augment the template language as needed.
Forms
Django provides a powerful form library that handles rendering forms as HTML, validating user-submitted data, and converting that data to native Python types. Django also provides a way to generate forms from your existing models and use those forms to create and update data.
Authentication
Django comes with a full-featured and secure authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. This lets you easily build sites that allow users to create accounts and safely log in/out.
Admin
One of the most powerful parts of Django is its automatic admin interface. It reads metadata in your models to provide a powerful and production-ready interface that content producers can immediately use to start managing content on your site. It’s easy to set up and provides many hooks for customization.
Internationalization
Django offers full support for translating text into different languages, plus locale-specific formatting of dates, times, numbers, and time zones. It lets developers and template authors specify which parts of their apps should be translated or formatted for local languages and cultures, and it uses these hooks to localize web applications for particular users according to their preferences.
Security
Django provides multiple protections against:
Documentation
Writing your first Django app, part 1¶
Let’s learn by example.
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
It’ll consist of two parts:
If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module named django”.
This tutorial is written for Django 4.0, which supports Python 3.8 and later. If the Django version doesn’t match, you can refer to the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update Django to the newest version. If you’re using an older version of Python, check What Python version can I use with Django? to find a compatible version of Django.
See How to install Django for advice on how to remove older versions of Django and install a newer one.
Where to get help:
If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.
Creating a project¶
If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.
From the command line, cd into a directory where you’d like to store your code, then run the following command:
You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).
Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the web server’s document root (in a place such as /var/www ). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your web server’s document root, because it risks the possibility that people may be able to view your code over the web. That’s not good for security.
Let’s look at what startproject created:
These files are:
The development server¶
Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:
Documentation
Writing your first Django app, part 2¶
This tutorial begins where Tutorial 1 left off. We’ll set up the database, create your first model, and get a quick introduction to Django’s automatically-generated admin site.
Where to get help:
If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.
Database setup¶
By default, the configuration uses SQLite. If you’re new to databases, or you’re just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won’t need to install anything else to support your database. When starting your first real project, however, you may want to use a more scalable database like PostgreSQL, to avoid database-switching headaches down the road.
If you wish to use another database, install the appropriate database bindings and change the following keys in the DATABASES ‘default’ item to match your database connection settings:
For databases other than SQLite
If you’re using a database besides SQLite, make sure you’ve created a database by this point. Do that with “ CREATE DATABASE database_name; ” within your database’s interactive prompt.
Also make sure that the database user provided in mysite/settings.py has “create database” privileges. This allows automatic creation of a test database which will be needed in a later tutorial.
Also, note the INSTALLED_APPS setting at the top of the file. That holds the names of all Django applications that are activated in this Django instance. Apps can be used in multiple projects, and you can package and distribute them for use by others in their projects.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.
Some of these applications make use of at least one database table, though, so we need to create the tables in the database before we can use them. To do that, run the following command:
For the minimalists
Creating models¶
Now we’ll define your models – essentially, your database layout, with additional metadata.
These concepts are represented by Python classes. Edit the polls/models.py file so it looks like this:
Each field is represented by an instance of a Field class – e.g., CharField for character fields and DateTimeField for datetimes. This tells Django what type of data each field holds.
The name of each Field instance (e.g. question_text or pub_date ) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.
A Field can also have various optional arguments; in this case, we’ve set the default value of votes to 0.
Activating models¶
That small bit of model code gives Django a lot of information. With it, Django is able to:
But first we need to tell our project that the polls app is installed.
Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute apps, because they don’t have to be tied to a given Django installation.
Now Django knows to include the polls app. Let’s run another command:
You should see something similar to the following:
You should see something similar to the following (we’ve reformatted it for readability):
Note the following:
If you’re interested, you can also run python manage.py check ; this checks for any problems in your project without making migrations or touching the database.
Now, run migrate again to create those model tables in your database:
The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also usable by other developers and in production.
Read the django-admin documentation for full information on what the manage.py utility can do.
Playing with the API¶
Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your mysite/settings.py file.
Once you’re in the shell, explore the database API :
Wait a minute. Question object (1)> isn’t a helpful representation of this object. Let’s fix that by editing the Question model (in the polls/models.py file) and adding a __str__() method to both Question and Choice :
It’s important to add __str__() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.
Let’s also add a custom method to this model:
Save these changes and start a new Python interactive shell by running python manage.py shell again:
Introducing the Django Admin¶
Generating admin sites for your staff or clients to add, change, and delete content is tedious work that doesn’t require much creativity. For that reason, Django entirely automates creation of admin interfaces for models.
Django was written in a newsroom environment, with a very clear separation between “content publishers” and the “public” site. Site managers use the system to add news stories, events, sports scores, etc., and that content is displayed on the public site. Django solves the problem of creating a unified interface for site administrators to edit content.
The admin isn’t intended to be used by site visitors. It’s for site managers.
Creating an admin user¶
First we’ll need to create a user who can login to the admin site. Run the following command:
Enter your desired username and press enter.
You will then be prompted for your desired email address:
The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.
Start the development server¶
The Django admin site is activated by default. Let’s start the development server and explore it.
If the server is not running start it like so:
Now, open a web browser and go to “/admin/” on your local domain – e.g., http://127.0.0.1:8000/admin/. You should see the admin’s login screen:
Enter the admin site¶
Now, try logging in with the superuser account you created in the previous step. You should see the Django admin index page:
Make the poll app modifiable in the admin¶
But where’s our poll app? It’s not displayed on the admin index page.
Only one more thing to do: we need to tell the admin that Question objects have an admin interface. To do this, open the polls/admin.py file, and edit it to look like this:
Explore the free admin functionality¶
Click “Questions”. Now you’re at the “change list” page for questions. This page displays all the questions in the database and lets you choose one to change it. There’s the “What’s up?” question we created earlier:
Click the “What’s up?” question to edit it:
Things to note here:
The bottom part of the page gives you a couple of options:
Change the “Date published” by clicking the “Today” and “Now” shortcuts. Then click “Save and continue editing.” Then click “History” in the upper right. You’ll see a page listing all changes made to this object via the Django admin, with the timestamp and username of the person who made the change:
When you’re comfortable with the models API and have familiarized yourself with the admin site, read part 3 of this tutorial to learn about how to add more views to our polls app.
Your first Django project!
Parts of this chapter are based on the django-marcador tutorial licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. The django-marcador tutorial is copyrighted by Markus Zapke-Gründemann et al.
We’re going to create a small blog!
The first step is to start a new Django project. Basically, this means that we’ll run some scripts provided by Django that will create the skeleton of a Django project for us. This is just a bunch of directories and files that we will use later.
The names of some files and directories are very important for Django. You should not rename the files that we are about to create. Moving them to a different place is also not a good idea. Django needs to maintain a certain structure to be able to find important things.
Remember to run everything in the virtualenv. If you don’t see a prefix (myvenv) in your console, you need to activate your virtualenv. We explained how to do that in the Django installation chapter in the Working with virtualenv part. Typing myvenv\Scripts\activate on Windows or source myvenv/bin/activate on Mac OS X or Linux will do this for you.
/djangogirls$ part shown here is just example of the prompt that will be inviting your input on your command line.
django-admin.py is a script that will create the directories and files for you. You should now have a directory structure which looks like this:
Note: in your directory structure, you will also see your myvenv directory that we created before.
manage.py is a script that helps with management of the site. With it we will be able (amongst other things) to start a web server on our computer without installing anything else.
The settings.py file contains the configuration of your website.
Let’s ignore the other files for now as we won’t change them. The only thing to remember is not to delete them by accident!
Changing settings
It would be nice to have the correct time on our website. Go to Wikipedia’s list of time zones and copy your relevant time zone (TZ) (e.g. Europe/Berlin ).
A language code consist of the language, e.g. en for English or de for German, and the country code, e.g. de for Germany or ch for Switzerland. If English is not your native language, you can add this to change the default buttons and notifications from Django to be in your language. So you would have «Cancel» button translated into the language you defined here. Django comes with a lot of prepared translations.
If you want a different language, change the language code by changing the following line:
We’ll also need to add a path for static files. (We’ll find out all about static files and CSS later in the tutorial.) Go down to the end of the file, and just underneath the STATIC_URL entry, add a new one called STATIC_ROOT :
Note: If you’re using a Chromebook, add this line at the bottom of your settings.py file: MESSAGE_STORAGE = ‘django.contrib.messages.storage.session.SessionStorage’
First, we are going to create a random secret key. Open the Glitch terminal again, and type the following command:
Then update the Django settings file to inject this secret value and set the Django web site name:
And a little further down in the same file, we inject the name of your new Glitch website:
The PROJECT_DOMAIN value is automatically generated by Glitch. It will correspond to the name of your project.
Set up a database
This is already set up in this part of your mysite/settings.py file:
To create a database for our blog, let’s run the following in the console: python manage.py migrate (we need to be in the djangogirls directory that contains the manage.py file). If that goes well, you should see something like this:
And we’re done! Time to start the web server and see if our website is working!
Starting the web server
You need to be in the directory that contains the manage.py file (the djangogirls directory). In the console, we can start the web server by running python manage.py runserver :
If you are on a Chromebook, use this command instead:
or this one if you are using Glitch:
Now you need to check that your website is running. Open your browser (Firefox, Chrome, Safari, Internet Explorer or whatever you use) and enter this address:
If you’re using a Chromebook and Cloud9, instead click the URL in the pop-up window that should have appeared in the upper right corner of the command window where the web server is running. The URL will look something like:
Congratulations! You’ve just created your first website and run it using a web server! Isn’t that awesome?
Note that a command window can only run one thing at a time, and the command window you opened earlier is running the web server. As long as the web server is running and waiting for additional incoming requests, the terminal will accept new text but will not execute new commands.
We reviewed how web servers work in the How the Internet works chapter.
Ready for the next step? It’s time to create some content!
Создаём первое веб-приложение с Джанго
Напишем простое веб-приложение на Django.
Джанго — это Open Source фреймворк для создания веб-приложений различной сложности на Python. Одним из его основных преимуществ является то, что вам нужно позаботиться только о логике будущего веб-приложения, остальное сделает Django.
Мы создадим приложение, у которого будет панель администратора и возможность загружать загадки, а у пользователей, соответственно, возможность отвечать на них. Во время разработки будут использоваться Python 3.4.3 и Django 1.9.1.
Устанавливаем Django
Создаём проект
Как только создание проекта будет завершено, взглянем на директорию нашего проекта:
Пишем веб-приложение на Django
Определим различие между проектом и приложением. Приложение — это программа, которая что-то делает, а проект — это группа приложений.
В urls.py мы должны написать следующее:
Установка базы данных
По умолчанию в Django используется SQLite, если она вас не устраивает, то вы можете ознакомиться с нашей статьей, в которой мы рассказываем, как безболезненно перейти с SQLite на MySQL.
Данная модель обеспечивает Django информацией, необходимой для создания схемы базы данных и database-access API для доступа к объектам. Теперь нам нужно привязать наше приложение к нашему проекту, делается это следующим образом:
Так мы говорим Django, что в моделях были сделаны некоторые изменения, и их нужно сохранить в качестве миграции.
Проверить, что сделает миграция, можно так: python manage.py sqlmigrate riddles 0001 (0001 — версия миграции, которую мы хотим проверить). На выходе мы получим:
Заметьте, что команда sqlmigrate нужна только для проверки, каждый раз ее запускать необязательно.
Теперь дадим админу возможность изменять наши модели. Делается это так:
Вот что получится в итоге:
Возьмите небольшую паузу и поиграйтесь с панелью администратора. Вы будете приятно удивлены тем, что умеет Джанго.
Главная страница
Что нам нужно для создания главной страницы?
Теперь создадим макет для ответов:
Давайте пройдемся по каждой функции веб-приложения на Django отдельно:
Теперь добавим наши функции в urls.py :
Стили
Немного изменим наши шаблоны:
Первая строка загружает статические файлы, потом мы используем <% static '#' %>, где # — путь к вашему файлу. Аналогичная процедура проводится и для JavaScript.
Теперь вы можете создавать свои веб-приложения на Django. В качестве подсказки на старте работы с фреймворком воспользуйтесь одной из наших шпаргалок по Python.
Исходный код нашего приложения можно скачать по этой ссылке.
Если этот веб-проект на Django показался сложным, попробуйте пройти двухчасовой видеокурс. На нём вы пошагово создадите 3 веб-приложения: сокращатель ссылок, ToDo List и словарь английских слов.