Getting started with django --- Building the first django website

Posted by Tobeon on Fri, 19 Jul 2019 08:44:02 +0200

background

Recently, I have been learning Java and dealing with all kinds of objects every day. When it's enough, it suddenly reminds me that I haven't written python for a long time. After all, python is my favorite. In addition, we are building a caffe+tensorflow+digits environment in ubuntu recently. Teachers also let us learn flask and django by ourselves. To tell you the truth, digits is really not easy to build. The nvidia driver on ubuntu is a headache. When I wanted to curse people, I started to write a basic django website. It took about two hours to relax. In addition, I would correct the code problems in the book. Finally, I successfully completed it.

First of all, the result chart


Now start building

My environment is win10 + Python 3.7 + django 2.2.3 (I'll talk about django later)

1. Establishment and preparation of virtual environment

First, create a new folder named learning_log.
Open cmd and switch to this directory with cd.

#After successful handover, create a virtual environment named ll_env in cmd using the following command
python -m venv ll_env
#Activate ll_env as a virtual environment
ll_env\Scripts\activate

#Install Django after activation
pip install Django

#View the installed version of Django
python -m django --version
#It shows the version of django.


Note that if the virtual environment is used, it will be shown before (ll_env), otherwise the virtual environment will not be activated.

2. Create projects

Start with a new project

django-admin.py startproject learning_log .
#Note that the following endpoints must be written so that the project has an appropriate directory structure
#Look at the directory structure with dir or open the folder by yourself. There should be three files, ll_env, management.py and learning_log.
#Look at learning_log again
dir learning_log
#It should be _init_ py, set. py, urls. py and wsgi.py.

Because I've already done it, there are many more things in the catalogue, so I won't show them here.

Create a database

Also in the activated virtual environment, use the following commands

python manage.py migrate

Then you will find an additional db.sqlite3 file in learning_log, which is the database.

Check whether the project was successfully created

#Or input in an active virtual environment
python manage.py runserver

Open the browser, enter the address localhost:8000, you should see the welcome interface of django, as follows

If you want to stop the service, just hold down ctrl+c in cmd

Now, make sure that everything is all right and you can start writing your own content.

3. Create applications and web pages

After ctrl+c stops servicing, it starts to create its own app in cmd

python manage.py startapp learing_logs
#Note that I'm learing_logs here. The book was learning_logs originally. I'm missing n just for my own sake. If you press the book, add n to the corresponding place in the code behind me.

Open models.py when learning_logs are created successfully

#models.py under learing_logs

from django.db import models
# Create your models here.
class Topic(models.Model):
    """User Learning Topics"""
    text=models.CharField(max_length=200)
    #max_length: Sets the length of the topic name
    date_added=models.DateTimeField(auto_now_add=True)
    #Role of True: Automatically set the current date and time whenever a new topic is created

    def __str__(self):
        """String representation of return model"""
        return self.text

class Entry(models.Model):
    """Specific knowledge learned about a subject"""
    topic=models.ForeignKey(Topic,on_delete=models.CASCADE)
    #There is no on_delete=models.CASCADE in the book, but Django2.X needs this, otherwise it will report an error.
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural='entries'

    def __str__(self):
        """String representation of return model"""
        return self.text[:50]+"..."

Activate this model

Edit the set.py file

#/ Set.py under learning_log/learning_log
"""
Django settings for learning_log project.

Generated by 'django-admin startproject' using Django 2.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'raeaahi)wo(*d99e+a!dfc+p5qbnt#ew9*r_k(hmbj$vhc!6$x'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
#Add the following two lines here
    #My application
    'learing_logs',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'learning_log.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'learning_log.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

Modify the database to store and migrate the model you defined
Remember to do this every time a new model is defined

#Input in cmd
python manage.py makemigrations learing_logs
python manage.py migrate

Get superuser privileges

python manage.py createsuperuser

Just fill in one username at will. Mailbox can be filled out without filling in. Password should be filled in and remember by yourself. It will be used later when landing.

Registration of models

Open admin.py

#admin.py under learing_logs
from django.contrib import admin

# Register your models here.
from learing_logs.models import Topic,Entry
admin.site.register(Topic)
admin.site.register(Entry)

Running the project at this time, or python manage.py runserver
Open localhost:8000/admin
Click add to add Topic and Entries content (just as you like)
Remember to save.

Finally, create homepages, maps, and other pages

Quickly completed, a little excitement, not much nonsense directly on the code

#/ urls.py under learning_log/learning_log

"""learning_log URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import include,url

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'',include(('learing_logs.urls','learing_logs'), namespace='learing_logs')),
    """All the books here are used. url(),however Django2.X Start with both path()Instead,
    //There's also the parameter problem in include(), which started with an error here.
    //It took a long time to read the relevant documents to solve the problem. At present, the above code is correct.“
]

Create a new urls.py file under learing_logs

#urls.py under learing_logs

"""Definition learing_logs Of url Pattern"""
from django.conf.urls import url
from . import views
from django.urls import path,re_path

app_name='learing_logs'

urlpatterns=[
"""The following is used#All of them are path() codes, but I don't know why some of them run incorrectly.
//Especially the topic_id matching, which was not matched at first, was tried a lot and succeeded in the end.
//Uncommented code I run successfully, if not, try replacing the commented code.
//I don't know why the url was mismatched when it jumped. It's embarrassing.“
    #homepage
    url(r'^$',views.index,name='index'),
    #path('',views.index,name='index'),

    #Detail pages for specific topics
    #re_path('topics/(?P<topic_id>\d+)/',views.topic,name='topic'),
    url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),
    #path('topics/(?P<topic_id>\d+)/', views.topic, name='topic'),
    
    #Display all topics
    url(r'^topics/$',views.topics,name='topics'),
    #path('topics',views.topics,name='topics'), 
]

Write view views.py

#views.py under learing_logs

from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
    """Home Page for Learning Notes"""
    return render(request,'learing_logs/index.html')

def topics(request):
    """Display all topics"""
    topics=Topic.objects.order_by('date_added')
    context={'topics':topics}
    return render(request,'learing_logs/topics.html',context)

def topic(request, topic_id):
    """Display a single topic and all its entries"""
    topic=Topic.objects.get(id=topic_id)
    entries=topic.entry_set.order_by('-date_added')
    context={'topic':topic,'entries':entries}
    return render(request,'learing_logs/topic.html',context)

Finally, there are all kinds of template html files.
Create a new template folder under learing_logs, and then create a new learing_logs folder inside to save various HTML files, a total of four are base.html,index.html,topic.html and topics.html.

Here's the code for the html file
index.html

{% extends "learing_logs/base.html" %} {% block content %}
<p>Learning Log helps you keep track of learning,for any topic you're learning about.</p>
{% endblock content %}

base.html

<p>
    <a href="{% url 'learing_logs:index' %}">Learning Log</a> -
    <a href="{% url 'learing_logs:topics' %}">Topics</a>
</p>
{% block content %} {% endblock content %}

topic.html

{% extends 'learing_logs/base.html' %} {% block content %}

<p>Topic:{{ topic }}</p>
<p>Entries:</p>
<ul>
    {% for entry in entries %}
    <li>
        <p>{{ entry.date_added|date:'M d,Y H:i' }}</p>
        <p>{{ entry.text|linebreaks }}</p>
    </li>
    {% empty %}
    <li>
        There are no entries for this topic yet.
    </li>
    {% endfor %}
</ul>

{% endblock content %}

topics.html

{% extends "learing_logs/base.html" %} {% block content %}
<p>Topics</p>

<ul>
    {% for topic in topics %}
    <li>
        <a href="{% url 'learing_logs:topic' topic.id %}">{{ topic }}</a>
    </li>
    {% empty %}
    <li>No topics have been added yet.</li>
    {% endfor %}
</ul>

{% endblock content %}

Direct python after all preservation manage.py runserver Startup Service
Open the page localhost:8000/topics, and you can see my results map from the beginning.
Click Learning_Log to jump to the home page (localhost:8000)

4. End

After that, I'm going back to Ubuntu to build digits. As I said, I hope that every day can be stronger, busy up to forget a lot of troubles, but also hope that as a program ape everyone can slowly realize their dreams, as a seven-year tiger pounce JR, I hope to work early to reach the street salary. If you encounter any problems during the construction, you can comment on the message. I see that you will reply in time. At the same time, I hope that the big guys in machine learning, in-depth learning and data analysis can guide me to learn how to best adapt to market demand and take less detours. Of course, postgraduate entrance examination is still the first step. Without a postgraduate diploma, it feels that the interview will be brushed off directly in the field of artificial intelligence. The reality is still cruel and helpless.

Topics: Django Python Database Ubuntu