Start!!!!!

Django novice? New to web development? Well, you’ve come to the right place, read on to get up and running quickly.

1.1 the Django person

Because Django was developed in a block-paced press office-like environment, it was designed to be quick and easy to develop web tasks. Here is an informal overview of how to write a database-driven web APP using Django. The goal of this article is to help you understand how Django works by providing enough technical expertise, but its not just instructional or referential — it is both.

2.1.1 Design your model

Even if you don’t use a database, it still has object relational mapping (ORM) functionality, where you can set up a database in Python code. The ‘data-model’ code provides a rich way to present your model — so far, it has solved multiple database schema problems.

Such as: mysite/news/models. Py

from django.db import models
class Reporter(models.Model) :
    full_name = models.CharField(max_length=70)
    
    def __str__(self) :
        return self.full_name
class Article(models.Model) :
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter,on_delete = models.CASCADE)

    def __str__(self) :
        return self.headline
Copy the code

2.1.2 installation

Next, run the Django command line to automatically create the database tables

python manage.py makemigrations
python manage.py migrate
Copy the code
  • The makemigbar command line finds all available models and creates tables that do not exist.
  • The Migrate run runs Names, Hoisting and creates tables in the database

2.1.3 using API

With the tables above, you have a free but rich API to work with your data. The API is created very quickly with no unnecessary code

# Import the models we created from our "news" app
>>> from news.models import Article, Reporter
# No reporters are in the system yet.
>>> Reporter.objects.all() <QuerySet []>
# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
>>> r.save()
# Now it has an ID.
>>> r.id 1
# Now the new reporter is in the database.
>>> Reporter.objects.all() <QuerySet [<Reporter: John Smith>]>
# Fields are represented as attributes on the Python object.
>>> r.full_name 'John Smith'
# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith='John') <Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains='mith') <Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist.
# Create an article.
>>> from datetime import date
>>> a = Article(pub_date=date.today(), headline='Django is cool'. content='Yeah.', reporter=r) >>> a.save()
# Now the article is in the database.
>>> Article.objects.all()
<QuerySet [<Article: Django is cool>]>
# Article objects get API access to related Reporter objects.
>>> r = a.reporter >>> r.full_name 'John Smith'
# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
<QuerySet [<Article: Django is cool>]>
# The API follows relationships as far as you need, performing efficient # JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John". >>> Article.objects.filter(reporter__full_name__startswith='John') <QuerySet [<Article: Django is cool>]>
# Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat' >>> r.save()
# Delete an object with delete().
>>> r.delete()
Copy the code

2.1.4 Dynamic Admin interface: Not just scaffolding — the whole house

Once you’ve defined your model, Django automatically creates a professional artifact, the Administrative Interface, a web site that allows authorized users to add, delete, and modify. The only step we need to do is to register the model at the admin point:

# mysite/news/models.py

from django.db import models
class Article(models.Model) :
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
Copy the code
# mysite/news/admin.py
from django.contrib imort admin
from . import models

admin.site.register(models.Article)
Copy the code

A typical process for creating a Django project is to create a Model and run it immediately after admin is set up so that other people can start fetching data. Then develop a user-facing approach.

2.1.5 set the urls

A clean, elegant COMBINATION of urls is an important detail in building a high-quality web application. Django encourages beautiful urls and doesn’t add any redundancy like other languages (PHP, ASP).

To design urls for your app, you need to create A Python model called URLconf, which is your app’s A Table of contents, Contains mapping between URLs and Python callback functions, and URLconfs decouples URLs from Python code. Example:

#mysite/news/urls.py

from django.urls import path
from . import views
urlpatterns=[
path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail),
]
Copy the code

The code map above takes the URL path to the callback function in “View”. The path string “captures” the value of the URLs via parameter markers. When a user makes a request to a web page, Django runs each path in turn until it finds the first URL that matches the request. (If no URL matches the request, Django brings up a 404 view.) As paths are being loaded, these paths are compiled into regular expressions. Once a URL path matches, Django calls this view function. Each view function passes a request object (containing request metadata) and the data retrieved from that path. For example: If a user sends a URL request to “/articles/2005/05/39323/,” Django calls news.views.article_detail(request,year=2005,month=5,pk = 39239)

2.1.6 Write down your view

Each view can perform the following tasks: return an HTTPResponse object containing the content of the requested page, or return an HTTP404 result. How you implement it after that is up to you. Typically, view functions first retrieve data through parameters, then load the template, and finally render the template with the retrieved data. Such as:

#views.py

from django.shortcuts import render
from .models import Article
def year_archive(request, year) :
    a_list = Article.objects.filter(pub_date__year=year) 
    context = {'year': year, 'article_list': a_list}
    return render(request, 'news/year_archive.html', context)

Copy the code

This example uses Djangos tampalte system, which is very simple for non-programmers.

2.1.7 Design your template

The following code loads the news/year_archive.html template. Django has a template query path that allows you to reduce query redundancy across a large number of templates. In your Django setup, you can specify a list of directories to search for templates in that directory, or if there aren’t any in the first directory, go to the second until the search ends

{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p> <p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %} {% endblock %}

Copy the code

Variables are defined by double curly braces. {{article. Headline}} outputs the value of the article title property. But dian dian (.) Not only for querying attributes, but also for dictionary queries, index queries, and function calls. {{article. Pub_date | date: “F, j, Y”}} using the Unix type pipe (|), is called a template filter, is a way of filtering variable values. In this case, the date is filtered out using a Python Datetime object in the given format. You can link as many filters as you like. You can also customize template filters. You can write custom template tags that run custom Python code. Finally, Django also supports template inheritance. {% extends “base.html” %} extends a template called “base “and then completes it with the following code. In short, it drastically reduces the redundancy of templates: each template must define its uniqueness.” The base.html” template uses static files as follows:

{% load static %} <html>
<head>
<title>{% block title %}{% endblock %}</title> </head>
<body>
<img src="{% static 'images/sitelogo.png' %}" alt="Logo"> {% block content %}{% endblock %}
 </body>
</html>
Copy the code

In simple terms, templates define the look-and-feel of a site, including the site logo, and provide ‘holes’ for children to inherit. In this way, a site can be redesigned simply by modifying a simple file, the template file. Note: If you have a preference, you dont have to use Djangos templating system. While the Django template system works perfectly with Django’s model layer, nothing forces you to use these templates. Also, you dont have to use Djangos database API. You can use another final database abstraction layer, you can read XML files, you can delete them from disk, or you can do whatever you want with them. Every layer of Django — the model layer, the view layer, and the template layer — is decoupled from each other

2.1.8 This is just the surface