一、新建项目以及app名字
在pycharm左上角file中点击 new project... 点击左侧django 在右面板写项目名、app名以及选择Python解释器,点击apply 再确定
之后新建静态文件夹static,在static文件夹下新建CSS和js文件,再去setting中配置如下:
STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ]
#修改链接数据库,USER可能会写成os.getenv('user')(环境变量去进行添加操作)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME':'bbs',
'HOST':'127.0.0.1',
'POST':3306,
'USER':'root',
'PASSWORD':'123321',
}
}
__init__.py:
import pymysql pymysql.install_as_MySQLdb()
models.py:
from django.db import models # Create your models here. #用户上传的文件一般放到media文件夹中 from django.contrib.auth.models import AbstractUser class UserInfo(AbstractUser): phone=models.CharField(max_length=32) #upload_to文件上传以后的存放路径 #FileField本质是varchar类型 avatar=models.FileField(upload_to='avatar/',default='avatar/default.png') blog=models.OneToOneField(to='Blog',on_delete=models.CASCADE) class Blog(models.Model): site_title=models.CharField(max_length=32) site_name= models.CharField(max_length=32) #每个人样式不同(文件地址) site_style= models.CharField(max_length=32) class Tag(models.Model): name=models.CharField(max_length=32) blog=models.ForeignKey(to='Blog') class Category(models.Model): name = models.CharField(max_length=32) blog = models.ForeignKey(to='Blog') class TagToArticle(models.Model): tag=models.ForeignKey(to='Tag') article=models.ForeignKey(to='Article') class Article(models.Model): title = models.CharField(max_length=32) desc= models.CharField(max_length=128) #大文本 样式展现出来是一个大方框 content=models.TextField() cerate_time=models.DateTimeField(auto_now_add=True) #关联关系 blog=models.ForeignKey(to='Blog',on_delete=models.CASCADE) category=models.ForeignKey(to='Category',on_delete=models.CASCADE) #多对多关系 tag=models.ManyToOneRel(to='Tag',through='TagToArticle',through_fields=('article','tag')) class UpAndDown(models.Model): user=models.ForeignKey(to='UserInfo') article = models.ForeignKey(to='Article') # is_up=models.BooleanField() create_time=models.DateTimeField(auto_now_add=True) class Commit(models.Model): user = models.ForeignKey(to='UserInfo') article = models.ForeignKey(to='Article') content=models.CharField(max_length=256) create_time = models.DateTimeField(auto_now_add=True) #自关联 commit_id=models.ForeignKey(to='self',on_delete=models.CASCADE)
#级联删除不完整使用时根据需要自行添加
再去setting中配置:
#扩写auth_UserInfo表,是app名字+user表名 AUTH_USER_MODEL='blog.UserInfo'
去数据库新建数据库:
数据库名:bbs
字符集:utf8--UTF-8 Unicode
建立好新表之后再进行迁移
在blog文件夹中新建blog_form.py:
#校验
from django import forms
from django.forms import widgets
from blog import models
from django.forms import ValidationError
class RegisterForm(forms.Form):
username = forms.CharField(required=True, max_length=18, min_length=3,label='用户名',
error_messages={'required': '该字段必填',
'max_length': '做大长度为18',
'min_length': '最短为3'},
widgets=widgets.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(required=True, max_length=18, min_length=3,label='密码',
error_messages={'required': '该字段必填',
'max_length': '做大长度为18',
'min_length': '最短为3'},
widgets=widgets.PasswordInput(attrs={'class': 'form-control'}))
re_password = forms.CharField(required=True, max_length=18, min_length=3,label='确认密码',
error_messages={'required': '该字段必填',
'max_length': '做大长度为18',
'min_length': '最短为3'},
widgets=widgets.PasswordInput(attrs={'class': 'form-control'}))
email = forms.EmailField(required=True,label='邮箱',
error_messages={'required': '该字段必填'},
widgets=widgets.EmailInput(attrs={'class': 'form-control'}))
#用户名如果存在了 就不能注册
def clean_username(self):
username=self.cleaned_data.get('username')
#去数据库查询
user=models.UserInfo.objects.filter(username=username).count()
if user: #不合法
raise ValidationError('用户名已经存在')
else:
return username
#校验两次密码是否一致
def clean(self):
password=self.cleaned_data.get('password')
re_password=self.cleaned_data.get('re_password')
if re_password==password:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
urls.py:
from django.contrib import admin from django.urls import path from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('register/',views.register), ]
views.py:
from django.shortcuts import render
from django.http import JsonResponse
from blog import models
# Create your views here.
from blog.blog_form import RegisterForm
def register(request):
if request.method == 'GET':
#实例化 传到register.html中就可以使用
form=RegisterForm()
return render(request,'register.html',context={'form':form})
elif request.method=='POST':
#校验数据是否合法
res={'code':100,'msg':'注册成功'}
form=RegisterForm(data=request.POST)
if form.is_valid():
#保存到数据库
data=form.cleaned_data #{username:zs,password:123,avatar:文件对象}
data.pop('re_password')#在字典中 所以需要删除 得到上面这个字典
if not data.get('avatar'):
data.pop('avatar')
models.UserInfo.objects.create_user(**data)
#返回会被ajax接收到
return JsonResponse(res)
else:
#数据校验不通过
res['code']=101 #101标识注册失败
res['msg']='数据验证失败'
res['error']=form.errors
return JsonResponse(res)
//需要迁移数据库
register.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap-theme.min.css">
<script scr="/static/jquery-3.3.1/jquery-3.3.1.min.js"></script>
<title>注册</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<h1 class="text-center">注册功能</h1>
<div class="col-md=6 col-md-offset-3">
<form id=""form>
{% csrf_token %}
{% for foo in form %}
<div class="form-group">
<label for="{{ foo.auto_id }}">{{ foo.label }}</label>
{{ foo }}
</div>
{% endfor %}
<div class="form-group">
{# 焦点 实现点击图片和头像文字也可以上传头像#}
<label for="id_myfile">头像</label>
{# 默认头像图片路径以及图片高宽#}
<img src="/static/img/default.png" alt="" id="id_img" height="80" width="80" style="margin-left: 10px ">
{# 根据id实现label中焦点 将上传文件按键以及文字隐藏更加美观#}
<input type="file" name="myfile" id="id_myfile" style="display: none">
</div>
<div class="text-center">
<input type="button" value="注册" id="id_submit" class="btn btn-danger">
</div>
</form>>
</div>
</div>
</div>
</body>
<script>
//放文件的标签发生变化,我们把文件搞出来,放到img标签中
$("#id_myfile").change(function(){
//借助于文件阅读器
var filereader = new FileReader()
//把图片读到filereader对象中
//$('id_myfile')[0].files[0]
filereader.readAsDataURL($('#id_myfile')[0].files[0])
//$('#id_img').attr('src','https://account.cnblogs.com/images/registersideimg
//$('#id_img').attr('src',filereader.result)//这样不行,文件没读完
filereader.onload=function(){
//文件完全读到文件阅读器以后再执行
$('#id_img').attr('src',filereader.result)
}
})
$("#id_submit").click(function () {
var formdata=new FormData()
formdata.append('avatar',$('#id_myfile')[0].files[0])
var ser=$('#form').serializeArray()
$.each(ser,function(k,v){
formdata.append(v.name,v.value)
})
$.ajax({
url:'/register/',
method:'post',
processData:false,
contentType:false,
data:formdata,
success:function(data){
if (data.code==100){
console.log(data.msg)
//js控制的跳转 本地跳转
location.href=data.url
}else {
//有错误 需要渲染页面
}
}
})
})
</script>
</html>
标签:form,models,步骤,博客园,length,max,import,data From: https://www.cnblogs.com/97zs/p/17922175.html