系统:Windows 10
IDE:PyCharm
Python:3.7.1
Django:2.2
mysql:mysql-8.0.15-winx64
Python3使用Django创建网站并使用mysql(第一部分)
Python3使用Django创建网站并使用mysql(第二部分)
Python3使用Django创建网站并使用mysql(第三部分)
这次第四部分主要建立一个适当的表,与Django网站一起完成注册与登录的功能,看到这里,我觉得学习的也差不多了,这应该就是最后一部分了。
from django.db import models
# Create your models here.
class UserInfo(models.Model):
username = models.CharField(max_length=20, default='')
password = models.CharField(max_length=20, default='')
nickname = models.CharField(max_length=20, null=True)
admin = models.BooleanField(null=True)
gold = models.IntegerField(null=True)
counter = models.IntegerField(null=True)
address = models.CharField(max_length=20, null=True)
email = models.CharField(max_length=20, null=True)
photo = models.CharField(max_length=50, null=True)
然后运行命令更新数据库,在Terminal执行python manage.py makemigrations,再执行python manage.py migrate就更新完成了。
注(没遇到不用看 ) : 我遇到了一个BUG就是model.py已经更改,但仍运行以前的代码,这时候需要打开你建立的APP文件夹(我的是login),找到__pycache__
文件夹删除models.cpython-37.pyc
文件(要去资源管理器)。
注册
from django.contrib import admin
from django.urls import path
from login import views
from django.conf.urls import include, url
urlpatterns = [
path(r'', views.index),
path(r'admin/', admin.site.urls),
path(r'index/', views.index),
path(r'userlist/', views.userlist),
path(r'register/', views.register),
]
第一行是说没有指向url,默认去index,第二行是超级用户后台的url(可以去百度一下就懂了,不想要可以删去)
from django.shortcuts import render
from django.shortcuts import redirect
from login import models
# Create your views here.
def index(request):
return render(request, 'index.html')
def userlist(request):
if request.method == 'POST':
username = request.POST.get('username', None)
password = request.POST.get('password', None)
try:
data_pass = models.UserInfo.objects.get(username=username).password
if password == data_pass:
temp = {'username': username, 'password': password}
return render(request, 'userlist.html', {'data': temp})
else:
return render(request, 'index.html')
except:
return render(request, 'index.html')
def register(request):
try:
if request.method == 'POST':
username = request.POST.get('username', None)
password = request.POST.get('password', None)
nickname = request.POST.get('nickname', None)
address = request.POST.get('address', None)
email = request.POST.get('email', None)
models.UserInfo(username = username,password = password,nickname = nickname,
admin = False,gold = 500,counter = 100,address = address,
email = email,photo = 'photoo_path').save()
temp = {'username': username, 'password': password,'msg': '注册成功'}
return render(request, 'userlist.html',{'data': temp})
else:
return render(request, 'register.html')
except:
return render(request, 'register.html')
这里更新了登录方法,并且新写了注册方法
用户登录后第一个页面
{{ data.username }}
{{ data.password }}
{{ data.msg }}