Python3 + DJANGO2 Development Easy Language network verification (UP)

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 average programmer is enlightened from C, and then C + +, then to Java, suddenly see PHP, suddenly feel simple and lively, as if to see relatives, and I easy language enlightenment, and then learn python, used to JavaScript I am bored to get so many curly braces, but also to declare variables what, it is absolutely troublesome, not to mention PHP, I think PHP is baked together with the Kraft sugar, sticky sticky, a piece of code to come over, there are always some edge corner of the bug to make 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中已有的数据库名, don't name the new database.

Create database Netauth; Netauth (Netauth is the database name, you can customize

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, configure the directory in settings.py, at the end of settings.py, find the relevant code, complete the 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

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

 fromDjango.contribImportAdmin fromDjango.urlsImportPath fromDjango.views.staticImportServe fromNetauth.settingsImportMedia_rooturlpatterns=[Path ('admin/', Admin.site.urls),#configuring access handlers for uploaded filesPath'media/<path:path>', serve,{'Document_root': Media_root}),
View Code

Added: Add template file path in settings.py:

TEMPLATES = [    {        'Backend':'django.template.backends.django.DjangoTemplates',        'DIRS': [Os.path.join (Base_dir,'Templates'),],        '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',              #Add Media path                'Django.template.context_processors.media',            ],        },    },]
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 Pymysql
Pymysql.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

From django.db import modelsfrom django.contrib.auth.models import abstractuserfrom datetime import datetime# Create your Models Here.class UserProfile (abstractuser):    end_time=models. Datetimefield (Default=datetime.now, verbose_name= ' expiry time ')    class Meta:        verbose_name= ' user information '        verbose_ Name_plural=verbose_name    def __str__ (self):        return Self.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:

#删除netauth数据库, re-netauth, two database names must be the same as the drop databases Netauth;create db 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:

Language_code = ' Zh-hans ' time_zone = ' Asia/shanghai ' use_i18n = trueuse_l10n = Trueuse_tz = 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 ', #追加代码:       ' 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 adminfrom django.urls import path# introduced xadminimport xadminurlpatterns = [    path (' admin/', Admin.site.urls), #配置xadmin路由       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, the list of network validation related tables is built (both tables, in fact, are simple):

From django.db import modelsfrom django.contrib.auth.models import abstractuserfrom datetime import datetime# Create your Models Here.class UserProfile (abstractuser): Is_ban=models. Booleanfield (default=false,verbose_name= ' is forbidden ') end_time=models. Datetimefield (Default=datetime.now, verbose_name= ' expiry time ') class meta:verbose_name= ' User information ' Verbose_name_plu Ral=verbose_name def __str__ (self): return Self.usernameclass Cards (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= ' duration ') is_used=models. Booleanfield (default=false,verbose_name= ' is already used ') add_time=models. Datetimefield (default=datetime.now,verbose_name= ' Spawn time ') class Meta:verbose_name= ' card secret ' verbose_name_plural =verbose_name def __str__ (self): return Self.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.

Python3 + DJANGO2 Development Easy Language network verification (UP)

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.