django build a voting websites (a)

Write in front, before fragmented seen django, but due to the more complex, school foggy, it stopped a paragraph, but I recently found a book django, django entry is Li compiled the and practice, therefore, intends to step shining on the book written by a website, hoping to understand in the end and know how to use django it, encourage each other

 

Man of few words said, the book written in front of a very detailed html, js, css, and python programming basics, I started directly from django part of it

Before you begin be sure to install django

1. Create a Django project

  First, create a file named demo, and then enter cmd in the demo directory, enter the django-admin startproject mysite. Creates a file in the demo file mysite directory

  note:

    1. You can not create test as the project name, because the conflict will be built with python bag, nor can django, because it will conflict with django, short note down the names of naming.

    2. Do not be django project file code files in the project file together with other sites, might django code is exposed in the browser

  Create a good directory should look like this

  

  Mysite at the same level, there should be a manage.py file.

2. Run django project

  cd mysite file in cmd, then type python manage.py runserver test is running correctly

  

  Appear as shown above is a normal operation, the input image above http://127.0.0.1:8000/ browser should pop up is successfully created, and a small rocket django

3. Create polls Applications

  Django project has already been successfully created, and then need to do is to create an application, each application contains a django package python, django-admin and use manage.py can help you quickly create an application file

  We will then place the application in python where the path can be recognized, here and on the same book, on the same level manage.py directory to find the same level in the directory manage.py cmd, type python manage.py startapp polls create an application polls.

  note:

    The difference between engineering and applications, application components is the real work, the project is a collection of websites that contain configuration information and applications, and a project can contain more than one application, an application can be lost on multiple projects Oh

  Here you can see the code and the code created above projects, there are a number of different startproject and startapp, I think the former is to say you create a project, which is to create app, namely applications to help remember it

4. Development of a view

  As long as view.py modify files in the polls like a directory, copy this code into it

from django.http Import HttpResponse 

DEF index (Request):
     return HttpResponse ( " Hello, here is the voting system " ) 

# the Create your views here Wallpaper.

  Then the view is successfully created, the meaning here is to return the contents of the matter,

  But now can not access, you need to add routes in alluding to the url, create a file in the polls urls.py file, at the contents copied into

from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
]

  prompt:

    The Path () method can accept four parameters, two mandatory parameters and View route, and two optional parameters name kwargs

  

  With this document urls then light is not enough, you also need to return to the urls file in the root directory, the application polls / urls.py in there, change mysite / urls.py follows

from django.contrib import admin
from django.urls import include,path

urlpatterns = [
    path('polls/',include('polls.urls')),
    path('admin/', admin.site.urls),
]

  The above code include () method may be used to refer to other URLconfs (urls.py). All url entire site can be assigned by the rational use of this method to multiple files, make the code more reasonable Introduction

  prompt:

    In addition to admin.site.urls, at all times should apply other methods include the use of the routing module

  Then, we have the first view of the project, though not hello world. Restart web service using runserver command, and then enter it http://127.0.0.1:8000/polls/ you will see the following screen

Of course, if the input index will appear the following interface, as shown below, you can tell there is a jump of admin, then it will be talked about is django management background

 

 

 5. Configuration Database mysql

  由于django提供了对mysql的支持,所以不需要做任何额外的工作了,当然,当你没有MySQL或者版本低于5.8建议重装一下,可以看下我的教程https://www.cnblogs.com/afei123/p/11247215.html

  至于为什么低于5.8,建议重装呢,因为django不支持,这个书上没有提,我在配置mysql的时候做了很久才发现的,然后又花了很久去重装mysql。。。。。

  言归正传,在mysite/setting,py文件中设置databases节点,至于为什么,想必做过工程的比较了解,把数据库连接配置好,然后只要调用就可以了,

DATABASES = {
    'default': {
        'ENGINE':'django.db.backends.mysql',#mysql数据库支持引擎
        'NAME':'数据库名',
        'USER':'数据库用户名',
        'PASSWORD':'数据库密码',
        'HOST':'127.0.0.1',#数据库所在的主机名
        'PORT':'3306',#数据库端口号
    }
}

   这些参数的具体含义,有兴趣的同学可以自己去查一下哦(因为书上写了,而且我觉得不必要。。。)

  数据库配置完之后,开始创建模型,修改polls/models.py文件如下(你们还能直接复制,我可全是照着书打,诶)

from django.db import models
import datetime
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedalta(days = 1)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)

    votes = models.IntegerField(default = 0)

    def __str__(self):
        return self.choice.choice_text

# Create your models here.

  这段文字其实是为了在数据库创建表使用的,我想不用注释应该也看的明白吧

  然后去修改mysite/setting.py内容,(书上没说,可让我好找)

  找到这两个选项,改成这样,分别对应的是时区和语言。

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

然后,找到下图位置,把最下面那句加进去,这是为了让django能够识别polls

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls.apps.PollsConfig',
]

在polls/apps.py文件内修改

from django.apps import AppConfig


class PollsConfig(AppConfig):
    name = 'polls'

然后用命令创建用于生成数据库的python脚本,

python manage.py makemigrations polls,之后再migrations文件目录下会出现类似0001的文件,文件目录如下,

 

 执行命令将django中的数据库更改写入mysql

python manage.py migrate,出现如下即为ok。如果缺少mysqlclient的话,安装下就好了,如果碰巧和我一样安装不了的话,可以看看这个https://www.cnblogs.com/afei123/p/11240182.html

 

这篇就到此为止了,下一篇再详细的讲一下admin

 

Guess you like

Origin www.cnblogs.com/afei123/p/11247681.html