2.3 Start Writing your First Django APP (Part 1)

Let’s start with an example:

With this document, we will help you create a basic voting APP with Walk Throuth.

The APP has two parts: (1) a public web page where people can see and vote for voting options; ② an admin url that allows you to add, change and delete votes. Python -m Django –version. If Django is not installed, error “No module named Django” will be reported.

This document is written for django4.0 and supports version 3.8 or later. If the version doesn’t work, you’ll need to consult your documentation for that version. If you’re using older versions of Python, you’ll need to look for a Version of Python that works with Django.

If you have questions about this document, please check the FAQ Getting Help section

2.3.1 Creating a project

If youre using Django for the first time, youll need to pay attention to the laundry initialization Settings. That is, you need to automatically create some code to create a DJAN project — a collection of Settings for a Django instance, including database parameters, Django-related options, and application-specific Settings.

From the command line, go to the folder where you want to save the code and run the command

django-admin startproject mysite
Copy the code

A folder named “mysite” will be created in the current directory. If this does not work, query: Problems running Django-admin.

Note: You should avoid creating project names using Python or Django built-in commands, especially. Names like “Djano” (which conflicts with Django itself) or “text” (which conflicts with Python’s built-in modules)

If your background is a plain old PHP language (without a modern framework), you might be comfortable writing code to the web services file root (e.g. /var/www). But with Django, you won’t have to do that anymore. It is not wise to put Python code in the web service file root, because it is not safe for someone else to access your code via the Web.

Create a style for the new project

Introduction to the document:

  • site/The root directory is the collection folder of your project. The name has nothing to do with Django and can be updated
  • manage.py Django-admin is a command-line application that allows you to interact with Django in a variety of ways, including information from n Django-admin and manage.py
  • The outer mysite /The name of the actual Python package for your project is the name of the Python package you will use to import the required files.

-mysite /__init__.py: is an empty file that tells Python that the directory is a Python package. If you’re new to Python, you can read more about packages from the Official Python documentation

  • mysite/settings.py: Set up (configure) the Django project,Django settingsOr tell you how to configure the work
  • mysite/urls.py: a declaration of the URL path to a Django project, django-the “directory” that drives the site. For more information about urls, see URL Dispatcher.
  • mysite/asgi.py: is an entry point to asGi-compatible web services.
  • mysite/wsgi.py: is an entry to WSGI compatible network services. See How to deploy with WSGI.

2.3.2 Development Service (The Development Server)

To make sure your Django project works, go to the external mysite directory. If not, run the command

    python amnage.py sunserver
Copy the code

You will see the following information

#The system displaysPerforming system checks... System check identified no issues (0 silenced). You have unapplied migrations; Your app may not work until they are ˓→applied. Run 'python manage.py migrate' to apply them. May 18, Django Version 4.0, Using Settings 'mysite. Settings' Starting development server at http://127.0.0.1:8000/ Quit the server with control-c.Copy the code

Note: Ignore the application’s database migration warning, we will deal with the database later

You’ve started a Django development service, a lightweight Web service written in Python. We’ve included this so you can quickly develop without having to deal with the various configurations of a production server (like Apache) until you’re ready for production services. Now, one caveat: do not use this server in anything like production. It is only used during development (we are busy building web frameworks, not web services). Now, the server is up and running, the browser goes to http://127.0.0.1:8000/ and you will see the “welcome” page and a rocket is being launched. The server is running!

Modifying a Port (port)

By default, the runServer command service has an initial IP wide port of 8000. If you want to change the service port, use the command line:

python manage.py runserver 8080
Copy the code

If you want to change the IP address, use the command line

Python manage.py runServer 0:8080Copy the code

Listen on all available public IP addresses; 0 is 0.0.0.0. For details, see “runServer”.

Automatically reloads runServer

slightly

2.3.3 Creating the Polls app

Your new environment (project) is now set up and ready to work. Each application you write is made up of a Python package in a particular context. Django is built to automatically generate a basic directory structure for an APP, so you can focus on writing code instead of creating folders.

  • The difference between project and APP

What’s the difference between a project and an APP? APP is a Web application with certain functions, such as weblog system is a database of public records, or a small voting APP. A project is a collection of configurations and apps for a particular website. A project can have multiple apps, and an APP can also be subordinate to multiple projects.

Your APP should run as long as it has a Python path. In this document, we will create a voting application that is applied to manage.py in the same directory, so that it can import sub-habits in the same directory, rather than in the mysite directory. Create the app command line in the same directory as manage.py

python manage.py startapp polls
Copy the code

This creates a directory

This directory is the structure of the Poll APP application.

2.3.4 Write your first view

Let’s write our first view: open polls/views.py and write the following code

from dejang.http import HttpResponse
def insex(request) :
    return HttpResponse('hello,world. you're ate he polls index.')
Copy the code

This is the simplest view in Django. To call this view, we need to map it to a URL; To map it to the URL, we need to configure (URLconf). We create a file called url.py in the poll directory to configure the URL, and the directory looks like this.

Polls/urls. Py writes:

# polls/urls.py 
from django.urls import path
from . import views
urlpatterns = [
    path(' ', views.index, name='index'),]Copy the code

The next step is to say that the root URL configuration points to the polls/urls.py file. In the mysite/urls.py file, import django.urls.include and insert an include() into the list of urlpatterns, which looks like this:

from django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls), 
 ]
Copy the code

The include () function

The include() function covers other URL configurations. Whenever Django encounters a function called include(), Django cuts out that part of the URL that matches the store. The rest of the string is also sent to the URL configuration decorated by the include function for further processing.

The central idea of the include() function is to make it easy to plug and play the URL path. Since the polls APP’s path and URL are in the same directory, they can be placed in any of the following directories: “/polls/”, “/fun_polls/”, /content/polls/ “, or any other directory, and the APP will work.

  • When to use include () :

You should use the include() function whenever you have other URL paths, except admin.site.urls

You have now arranged the URL configuration for the path of the Index view. The following command line ensures that it works

python manage.py runsever
Copy the code

The browser to http://localhost:8000/polls/, then you will see “‘ hello, world. You ‘r e ate he polls index. The” content. That’s the index view you defined

  • Can’t find the view?

If you find that can’t open the page, check http://localhost:8000/polls/, replace the http://localhost:8000/.

The path () function

The path() function takes four arguments, two of which are mandatory: View and root, and two optional: kwargs and name

  • Rout parameters:

Rout is a string containing a URL path. When making a request, Django starts at the first path in the UrlPatterns pattern, compares it to the requested URL, and works its way down the list until it finds the first path that matches the pattern.

Paths do not care about GET or POST parameters, nor do they care about domain names. For example, if the requested address is https://www. example.com/myapp/, the URL configuration will look up myapp/; The requested address is www.example.com/myapp/?page… , the URL configuration also queries myapp/.

  • The view parameter

When Django finds a path that meets the criteria, it calls the view function through an Httprequest object as the first argument, and then captures the value as a keyword argument.

  • Kwars parameters

Any keyword argument in the dictionary can be passed to the target view. This feature of Django will not be covered in this article

  • The name parameter

Naming urls from either Django location makes it easier to query them, especially inside templates. This powerful feature allows you to change the URL path of a project globally with just X touch of a file.

Once you understand the basic request and response process, read the next chapter to start working with the database.