Python3+django2 Developing Easy Language network verification (top)

Source: Internet
Author: User
Tags mysql command line

Creation background:

In a forum to download a set of PHP development Easy Language Network verification tutorial, looked down, took two days, the results found that the tutorial developed network authentication, as well as the tutorial with the source code for the students, there is no bug!  I want to see if I can change on the basis of the original, but there are a lot of pits, not here is less a $, that is, less; Or it is not what {} package is wrong, wipe, not to say that PHP is the best language in the world? How does it feel to be the world's most pit language?

Perhaps because the general programmers are from the C enlightenment, and then C + +, and then to Java, suddenly see PHP, immediately feel simple and lively, like to see loved ones, and I Easy language enlightenment, and then learn Python, with JavaScript I am bored to get so many curly braces, Also want to declare variables what, it is absolutely troublesome, not to mention PHP, I think PHP is a baked with the Kraft sugar, sticky sticky, a piece of code to come over, there are always some edge corner of the bug made you uncomfortable.

So, I had to rage and use Python, to sacrifice Django, develop a easy language network verification! In fact, this is forced helpless, after all, PHP garbage is a point, fortunately, the deployment is very simple, and the Django Project on-line deployment is ... It's long story.

First step: General operation, create a new Django project and connect to the MySQL database

(download install MySQL, download install python3, download install pycharm registration activation What, here will not repeat, as we all know ha)

1. Create a new database:

1. Open MySQL Command line Client (Windows desktop → start → All programs →mysql→mysql Server5.7 directory)

2. Enter the database password, enter the database, and then tap the code:

show databases; #看看mysql中已经有的数据库名, the newly created database does not name the Create databases Netauth; #创建数据库 Netauth (Netauth is the database name and can be customized)
2. New Django Project: 1. Create a new Django project: Open Pycharm→file→new preject→django→ take a project name: Netauth→more settings→ take the app name: Yanzheng

2. New static file directory: Static, media, log

1. Create a new directory

2. In the settings.py configuration directory, at the end of settings.py, find the relevant code, complete the following code:

Static_url = '/static/' staticfiles_dirs= (Os.path.join (base_dir,  ' static '),) Template_dirs = (Os.path.join (base_ DIR,  ' templates '), media_url= "/media/" Media_root=os.path.join (Base_dir, "MEDIA")

3. In the project Netauth directory, configure the media path in the urls.py, add the code, complete the following:

From Django.contrib import adminfrom django.urls import pathfrom django.views.static import Servefrom netauth.settings im Port media_rooturlpatterns = [    path (' admin/', admin.site.urls),    #配置上传文件的访问处理函数    path (' Media/<path: Path> ', serve,{' document_root ': Media_root}),]

Added: Add template file path in settings.py:

View Code3. Create a Django project with a MySQL database link:

1. Add the code to the __init__.py in the Project Netauth directory:

Import Pymysqlpymysql.install_as_mysqldb ()

The database in the 2.settings.py configuration file is found to be overwritten:

  

DATABASES = {'    default ': {        ' ENGINE ': ' Django.db.backends.mysql ',        ' NAME ': ' Netauth ',        ' USER ': ' Root ',        ' PASSWORD ': ' (Database Password) ',        ' HOST ': ' 127.0.0.1 ',        ' PORT ': ' 3306 ',        ' OPTIONS ': {' Init_command ': ' SET Default_storage_engine=innodb; '}}    }

3. Open the terminal to perform the two classic commands to update the database:

Python manage.py Makemigrationspython manage.py Migrate

4. In Pycharm intuitive management database (similar to PHP phpadmin, however not so difficult to use):

1. Click the database button → click + sign → click MySQL

2. Enter the database name, database user name, database password → Click on the test Connection button, prompt successful link success, click OK!

3. View: Click database→ Click [Email protected]→ click on the Netauth to see the Django automatically generated 10 tables, you can click into the view, to do additions and deletions.

5. Create a custom user table:

1. Write code in yanzheng/models.py: from django.db import models

 fromDjango.dbImportModels fromDjango.contrib.auth.modelsImportAbstractuser fromDatetimeImportdatetime#Create your models here.classuserprofile (abstractuser): End_time=models. Datetimefield (Default=datetime.now, verbose_name='Expiry Time')    classMeta:verbose_name='User Information'verbose_name_plural=Verbose_namedef __str__(self):returnSelf.username

2. Add the code to the settings.py:

Auth_user_model='Yanzheng. UserProfile'

3. Start → All programs →mysql→mysql Server 5.7→ open MySQL command line Client.exe Enter the password, enter the operator interface, execute the following command:

# Delete Netauth database, rebuild Netauth, two database names must be the same drop database netauth;create database Netauth;

4. Back to the Django project, open the terminal terminal and execute the classic Update data command:

Python manage.py Makemigrationspython manage.py Migrate
6. Create a new super User:

1. Open the terminal terminal and execute:

Python manage.py createsuperuserusername: Username Email: mailbox Password: Customize a password of not less than 8 bits (password not shown) Password (again): Confirm password

2. In settings.py find Language_code, change the relevant code to use Chinese:

' Zh-hans '  'asia/shanghai'== False

3. Run the Django Project:

Method One: Click the Pycharm Run button

Method Two: Execute the command:

Python manage.py runserver

After successful operation, as long as the browser access: Http://127.0.0.1:8000/admin can come to the Xadmin admin interface, you can login with the Super user account password you just created.

Step Two: Install the configuration xadmin what is xadmin:

There are many definitions and explanations on the Internet, basically let the people who do not know Xadmin read the more confused! Since it is an explanation, it is necessary for the reader to understand it suddenly!

Xadmin in the field of Python is equivalent to the PHP domain of the DZ Forum and WordPress highly customizable version of the backstage!

More popular point, Xadmin is like your QQ space, but more than QQ space can be customized 1000 times times higher, can easily manage your various data (analogy to your QQ space in the journal, say, signature, photos ...) )

1.django2 under Installation Xadmin

1.xadmin of Django2:https://github.com/sshwsfc/xadmin/tree/django2

2. Open address → confirm the download is django2, click Clone or download→ click Download zip→ Select Download to a directory without Chinese → Click to download

3. Open terminal to execute the installation command:

Pip Install--cache-dirpip install D:/xadmin-django2.zip

4. Install some of the necessary library files:

Pip Crispy_formspip reversion

5. Open settings.py Find Installed_apps append:

Installed_apps = [    'Django.contrib.admin',    'Django.contrib.auth',    'Django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'Django.contrib.staticfiles',    'Yanzheng.apps.YanzhengConfig', #Append code:    'Xadmin',    'crispy_forms',    'reversion',]

6. Add two lines of code to the urls.py, even if the xadmin is configured for routing:

 from  django.contrib import   admin  from  django.urls import   path  #   Introducing Xadmin  import   xadminurlpatterns  = [path ( "  admin/  "  #   Configure Xadmin route  path ( " xadmin/ "  , Xadmin.site.urls),] 

7. Install the configuration, do not forget to update the database, open terminal, execute the classic two commands:

Python manage.py Makemigrationspython manage.py Migrate

8. Re-run the project, the browser access to http://127.0.0.1:8000/xadmin/can see the Xadmin login interface (the last login to the admin if not logout, because of the cookie, will directly appear the login interface. )

2.django2 configuration xadmin1. This is a successful login, but since you will also need to customize some of the xadmin plugins (such as the one-click Export generated card secret plugin), you want to import xadmin into the project:

1. Under the project Netauth directory, create new apps and Extra_apps, and drag Yanzheng into the Apps directory.

2. Locate the downloaded Xadmin-django2.zip in the D-disk directory, right-click Unzip the file → OK, unzip the folder, locate the Xadmin folder under the Xadmin-django2/xadmin-django2 directory, and copy to the project Extra_ Apps directory, note that search for reference and open moved files in Editer are not checked!

3.extra_apps Right-→mark directory as→sources root ( same thing to the Apps directory )

4. In settings.py, locate: Base_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath)), import sys add complete code:

Import os,sys# Build paths inside the project like This:os.path.join (Base_dir, ...) Base_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.insert (0,os.path.join (Base_dir, ' Apps ') Sys.path.insert (1,os.path.join (Base_dir, ' Extra_apps '))

.5. Open the terminal terminal and uninstall the first installed Xadmin

Pip Uninstall Xadminy
Do not feel that the first installation, and import, and uninstall, the process has what can be omitted, one step can not be less, or fall into the pit, climb not up oh. Step Three: Database development

1. In apps/yanzheng/models.py, complete the Network validation related tables (in fact, both tables are simple):

 fromDjango.dbImportModels fromDjango.contrib.auth.modelsImportAbstractuser fromDatetimeImportdatetime#Create your models here.classuserprofile (abstractuser): Is_ban=models. Booleanfield (default=false,verbose_name='whether or not to be banned') End_time=models. Datetimefield (Default=datetime.now, verbose_name='Expiry Time')    classMeta:verbose_name='User Information'verbose_name_plural=Verbose_namedef __str__(self):returnSelf.usernameclassCards (models. Model):"""Prepaid Card"""User=models. ForeignKey (userprofile,verbose_name='User', on_delete=models. CASCADE) Kacode=models. Charfield (max_length=50,verbose_name='Card Secret', default="') Time=models. Integerfield (default=3600,verbose_name='Length of Time') is_used=models. Booleanfield (default=false,verbose_name='have you already used') Add_time=models. Datetimefield (default=datetime.now,verbose_name='Build Time')    classMeta:verbose_name='Card Secret'verbose_name_plural=Verbose_namedef __str__(self):returnSelf.kacode

Open terminal, perform the Data Update command:

Python manage.py Makemigrationspython manage.py Migrate
Here is a pit:

When the data is updated, if there is a Datetimefield field in the data class, the Data Update command succeeds only when it is first created, and if the Data Update command has been executed and the default value of the Datetimefield field is modified, the time-format error is very annoying!

Workaround: The Apps/yanzheng/makemigrations directory, in addition to __init__.py files are deleted, and then execute the Data Update command, you can.

Limited space, the entire Network validation development tutorial, I plan to be divided into three pieces to write: The first one is written today, the server-side MTV in the Mt part has been written, the second part of the service side of the V, and the client easy language part; The third plan is to write a Django project on-line deployment.

Python3+django2 Developing Easy Language network verification (top)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.