大家好,我是天空之城,今天给大家带来小福利,django搭建个人博客网站源码(二)
首先是项目总目录
首先是views视图文件
from django.contrib.auth import logout,login,authenticate
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Q
from django.shortcuts import render, redirect
# Create your views here.
from django import forms
from utils import util_sendmsg
from .forms import RegisterForm, LoginForm
from .models import UserProfile
from .forms import UserRegisterForm
def index(request):
rform = RegisterForm()
return render(request, 'user/index.html')
#注册
def user_register(request):
if request.method=='GET':
return render(request, 'user/register.html')
else:
rform = RegisterForm(request.POST) #使用form获取数据
if rform.is_valid():
username = rform.cleaned_data.get('username')
email = rform.cleaned_data.get('email')
mobile = rform.cleaned_data.get('mobile')
password = rform.cleaned_data.get('password')
#注册到数据库
if not UserProfile.objects.filter(Q(username=username)|Q(mobile=mobile)).exists():
password=make_password(password)
user=UserProfile.objects.create(username=username,password=password,email =email,mobile=mobile)
if user:
return HttpResponse('注册成功')
else:
return render(request,'user/register.html',context={'msg':'用户名或者手机号已经存在'})
return render(request,'user/register.html',context={'msg':'注册失败,重新填写'})
from .forms import UserRegisterForm
from django.http import HttpResponse, JsonResponse
def user_zhuce(request):
if request.method == 'GET':
# rform=UserRegisterForm()
rform = RegisterForm()
print("双杠",rform)
return render(request, 'user/zhuce.html',context={'rform':rform})
else:
rform=UserRegisterForm(request.POST)
# print('单杠',rform)
print(rform.is_valid())
print(rform.errors)
if rform.is_valid():
print(rform.cleaned_data)
username = rform.cleaned_data.get('username')
email = rform.cleaned_data.get('email')
mobile = rform.cleaned_data.get('mobile')
password = rform.cleaned_data.get('password')
if not UserProfile.objects.filter(Q(username=username)|Q(mobile=mobile)).exists():
#注册到数据库中
password=make_password(password)
user=UserProfile.objects.create(username=username,password=password,email=email,mobile=mobile)
if user:
return HttpResponse('注册成功')
else:
return render(request,'user/register.html',context={'msg':'用户名或者手机号已经存在'})
return render(request,'user/register.html',context={'msg':'注册失败,重新填写'})
#数据库注册
def user_login(request):
if request.method=='GET':
return render(request, 'user/login.html')
else:
lform=LoginForm(request.POST)
if lform.is_valid():
username=lform.cleaned_data.get('username')
password=lform.cleaned_data.get('password')
# 进行数据库的查询
# user=UserProfile.objects.filter(username=username).first()
# flag=check_password(password,user.password)
# if flag:
# #保存session信息
# request.session['username']=username
# # return HttpResponse('用户登录成功')
# return redirect('/')
#第二种方法,前提是继承了Abstractuser
user=authenticate(username=username,password=password)
if user:
login(request,user)#将用户对象保存在底层的request中(session)
return redirect('/')
return render(request,'user/login.html',context={'errors':lform.errors})
# 用户注销
def user_logout(request):
# request.session.clear()
# request.session.flush()#删除diango_session表+本地cookie+字典
logout(request)
return redirect('/')
#发送验证码
def send_code(request):
mobile=request.GET.get('mobile')
#发送验证码,第三方
json_result=util_sendmsg(mobile)
status=json_result.get('code')
data={}
if status==200:
check_code=json_result.get('obj')
#使用session保存
request.session[mobile]=check_code
data['status']=200
data['msg']='验证码发送成功'
else:
data['status'] = 500
data['msg'] = '验证码发送失败'
return JsonResponse(data)
#手机验证码登录
def code_login(request):
if request.method=='GET':
return render(request,'user/codelogin.html')
else:
mobile=request.POST.get('mobile')
code=request.POST.get('code')
#根据mobile去session中取值
check_code=request.session.get(mobile)
if code== check_code:
# return redirect('/')
user=UserProfile.objects.filter(mobile=mobile).first()
# user=authenticate(username=user.username,password=user.password)
if user:
login(request,user)
return redirect('/')
else:
return HttpResponse('验证失败')
else:
return render(request, 'user/codelogin.html',context={'msg':'验证码有误'})
def user_about(request):
return HttpResponse('我是老大')
其次是model文件
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
mobile=models.CharField(max_length=11,verbose_name='手机号码',unique=True)
icon= models.ImageField(upload_to='uploads/%Y/%m/%d') #FileField任何文件
class Meta:
db_table = ' userprofile'
verbose_name = '用户表'
verbose_name_plural = verbose_name
然后是project/url文件和app/url文件
"""myblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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 import settings
from django.conf.urls.static import static
from django.conf.urls import url,include
#
# from user.views import index
#
# urlpatterns = [
# path('admin/', admin.site.urls),
# path('',index,name='index'),
# ]
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('user.urls',namespace='user')),
]
# + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
=================================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/2 20:48
# @Author : tiankongzhicheng
# @File : urls.py
# @Software: PyCharm
app_name='user'
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# url(r'^meinv$', views.indexfunc),
url(r'^$', views.index,name='index'),
url(r'^register/$', views.user_register,name='register'),
url(r'^zhuce/$', views.user_zhuce,name='zhuce'),
url(r'^login/$', views.user_login,name='login'),
url(r'^logout/$', views.user_logout,name='logout'),
url(r'^codelogin/$', views.code_login,name='codelogin'),
url(r'^send_code/$', views.send_code,name='send_code'),
url(r'^about/$', views.user_about,name='about'),
]
# + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
最后settings文件
"""
Django settings for myblog project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ne4264$go@d051x^l+vf_)6$#la5u6y#^iip!4h=c7^abxcrr!'
# 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',
'user',
]
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 = 'myblog.urls'
#修改auth_user的模型
AUTH_USER_MODEL='user.UserProfile'
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',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'myblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "blog",
'USER': "root",
'PASSWORD': "qwer123456",
'HOST': "localhost",
'PORT': "3306"
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'/media/')
# print(MEDIA_ROOT)
import os,sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# #查看项目BASE_DIR(自我认为是跟路径)
# print(BASE_DIR)
import os,sys
#查看未追加前的项目导包路径
# print(sys.path)
#追加导包路径
sys.path.insert(0,os.path.join(BASE_DIR,'user/'))
##这里的0表示的是未追加前的第一个导包路径
#查看追加后的项目到导包路径
project/__init__文件
import pymysql
pymysql.version_info = (1, 4, 13, "final", 0) # 将版本信息改为1.3.13
pymysql.install_as_MySQLdb() # 驱动设置为pymysql
admin文件
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from .models import UserProfile
admin.site.register(UserProfile)
自定义的forms文件
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/9 21:29
# @Author : tiankongzhicheng
# @File : forms.py
# @Software: PyCharm
from django.core.exceptions import ValidationError
from django.forms import Form,ModelForm
from django import forms
import re
class UserRegisterForm(Form):
username=forms.CharField(max_length=50,min_length=6,error_messages={'min_length':'用户名长度至少6位',},label='用户名')
email=forms.EmailField(required=True,error_messages={'required':'必须填写邮箱'},label='邮箱')
mobile=forms.CharField(required=True,error_messages={'required':'必须填写手机号码'},label='手机')
password=forms.CharField(required=True,error_messages={'required':'必须填写密码'},label='密码',widget=forms.widgets.PasswordInput)
repassword = forms.CharField(required=True, error_messages={'required':'必须填写确认密码'}, label='密码',
widget=forms.widgets.PasswordInput)
favorite_colors=forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple,
choices=(('blue','Blue'),('red','Red'),('green','Green'),('yellow','Yellow')),label='最喜欢的颜色'
)
def clean_username(self):
username=self.cleaned_data.get('username')
result=re.match(r'[a-zA-Z]\w{5,}',username)
if not result:
raise ValidationError('用户名必须以字母开头')
return username
from .models import UserProfile
class RegisterForm(ModelForm):
repassword=forms.CharField(required=True, error_messages={'required': '必须填写确认密码'}, label='确认密码',
widget=forms.widgets.PasswordInput)
class Meta:
model=UserProfile
# fields='__all__'
# exclude=['first_name','date_joined','last_time']
fields=['username','email','mobile','password']
def clean_username(self):
username=self.cleaned_data.get('username')
result=re.match(r'[a-zA-Z]\w{5,}',username)
if not result:
raise ValidationError('用户名必须以字母开头')
return username
# class LoginForm(ModelForm):
# class Meta:
# model=UserProfile
# fields=['username','password']
#
# def clean_username(self):
# username=self.cleaned_data.get('username')
# if not UserProfile.objects.filter(username=username).exists():
# raise ValidationError('用户名不存在')
# return username
class LoginForm(Form):
username = forms.CharField(max_length=50, min_length=6, error_messages={'min_length': '用户名长度至少6位', }, label='用户名')
password = forms.CharField(required=True, error_messages={'required': '必须填写密码'}, label='密码',
widget=forms.widgets.PasswordInput)
def clean_username(self):
username=self.cleaned_data.get('username')
if not UserProfile.objects.filter(username=username).exists():
raise ValidationError('用户名不存在')
return username