已完成
大体模板
用户登入注册明天加商品订单商品进去
完成效果图
注册
登入
settings.py
"""Django settings for drf_test project.Generated by 'django-admin startproject' using Django 1.11.22.For more information on this file,seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full List of settings and their values,seehttps://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checkList/# Security WARNING: keep the secret key used in production secret!SECRET_KEY = 'ppa5l3jvxr4k^ow*4o+0_^7@&sa3x+!hb_$artwraa%60iq@g7'# Security WARNING: don't run with deBUG turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application deFinitionINSTALLED_APPS = [ 'django.contrib.admin','django.contrib.auth','django.contrib.ContentTypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','drf_API',]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 = 'drf_test.urls'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',],},]Wsgi_APPliCATION = 'drf_test.wsgi.application'# Database# https://docs.djangoproject.com/en/1.11/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3','name': os.path.join(BASE_DIR,'db.sqlite3'),}}# Password valIDation# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-valIDatorsAUTH_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/1.11/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS,JavaScript,Images)# https://docs.djangoproject.com/en/1.11/howto/static-files/STATIC_URL = '/static/'STATICfileS_Dirs=(os.path.join(BASE_DIR,'static'),)AUTH_USER_MODEL = "drf_API.UserInfo"MEDIA_URL = "/img/"MEDIA_ROOT = os.path.join(BASE_DIR,"img")
@H_404_42@2.创建模型以及form组件models.py
from django.db import modelsfrom django.contrib.auth.models import AbstractUser# Create your models here.class UserInfo(AbstractUser): avatar = models.fileFIEld(upload_to='avatar/',default='avatar/default.png') class Meta: verbose_name='用户表' verbose_name_plural = verbose_name
userinfo_form.py
from django import formsfrom django.forms import Widgetsfrom django.core.exceptions import ValIDationErrorfrom drf_API import modelsclass Register(forms.Form): username=forms.CharFIEld(max_length=18,min_length=3,label="用户名",error_messages={'max_length':'太长了','min_length':'太短了','required':'不能为空'},Widget=Widgets.Textinput(attrs={'class':'form-control'}),) password=forms.CharFIEld(max_length=18,label="密码",Widget=Widgets.Passwordinput(attrs={'class':'form-control'}),) re_pwd=forms.CharFIEld(max_length=18,label="确认密码",) email=forms.EmailFIEld(max_length=18,label="邮箱",Widget=Widgets.Emailinput(attrs={'class':'form-control'}),) def clean_username(self): name=self.cleaned_data.get('username') user=models.UserInfo.objects.filter(username=name).first() if user: raise ValIDationError('用户已经存在') else: return name def clean(self): pwd=self.cleaned_data.get('password') r_pwd=self.cleaned_data.get('re_pwd') if pwd==r_pwd: return self.cleaned_data else: raise ValIDationError('两次密码不一致')
3.页面母版
template.HTML
<!DOCTYPE HTML><HTML lang="zh"><head> <Meta charset="UTF-8"> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/CSS/bootstrap.min.CSS"> <script src="/static/jquery-3.4.1.min.Js"></script> <script src="/static/bootstrap-3.3.7-dist/Js/bootstrap.min.Js"></script> <Title>{% block Title_text %}{% endblock %}</Title></head><style> .header { position: fixed; top: 0; left: 0; height: 100px; wIDth: 100%; background: red; } .header_left{ position: absolute; line-height: 100px; Font-size: 50px; wIDth:20% ; text-align: center; background: black; color: white; } .header_right{ float: right; line-height: 100px; } .body { position: fixed; top: 100px; left: 0; bottom: 20px; wIDth: 100%; } .body_left { position: fixed; top: 100px; left: 0; bottom: 20px; wIDth: 20%; background: white; } .body_right { overflow: auto; position: fixed; top: 100px; left: 20%; bottom: 20px; wIDth: 80%; background: #2aabd2; } .footer { position: fixed; left: 0; bottom: 0; height: 20px; wIDth: 100%; background: black; }</style>{% block new_CSS %}{% endblock %}<body><div > <div >管理系统</div> <div > <a href="http://127.0.0.1:8000/login/">登入</a> <a href="http://127.0.0.1:8000/register/">注册</a> </div></div><div > <div > <ul > <li role="presentation" ><a>库存管理</a></li> <li role="presentation"><a href="#">查看商品</a></li> <li role="presentation"><a href="#">添加商品</a></li> <li role="presentation"><a href="#">删除商品</a></li> </ul> <ul > <li role="presentation" ><a>订单管理</a></li> <li role="presentation"><a href="#">查看订单</a></li> <li role="presentation"><a href="#">添加订单</a></li> <li role="presentation"><a href="#">删除订单</a></li> <li role="presentation"><a href="#">订单号快速查询</a></li> </ul> </div> <div > {% block data %} {% endblock %} </div></div><div ></div></body></HTML>{% block new_Js %}{% endblock %}
登入
login.HTML
{% extends 'template.HTML' %}{% block Title_text %} 登入{% endblock %}{% block new_CSS %}{% endblock %}{% block data %} <div > <div > <div > {% csrf_token %} <h1>登陆</h1> <form action=""> <div > <label for="ID_name">用户名</label> <input type="text" name="name" ID="ID_name" > </div> <div > <label for="pwd">密码</label> <input type="password" name="pwd" ID="pwd" > </div> <div > <label for="ID_code">验证码</label> <div > <div > <input type="text" name="code" ID="ID_code" > </div> <div ID="img"> <img src="/get_code/" height="40" wIDth="240" > </div> </div> </div> <input type="button" value="提交" ID="up_data"> <span ID="msg"></span> </form> </div> </div> </div>{% endblock %}{% block new_Js %} <script> $('.img-code').click(function () { var img_code_src = $(this).attr('src'); img_code_src += '1'; console.log(img_code_src); $(this).attr('src',img_code_src) }) </script> <script> $('#up_data').click(function () { $.AJAX({ type: 'post',url: '/login/',data: { 'name': $('#ID_name').val(),'pwd': $('#pwd').val(),'code': $('#ID_code').val(),'csrfmIDdlewaretoken': '{{csrf_token}}' },success: function (msg) { console.log(msg); $('#msg').text(msg); if (msg == '登入成功') { console.log('sb'); window.location.replace('http://www.baIDu.com'); } } }) }) </script>{% endblock %}
登入
register.HTML
{% extends 'template.HTML' %}{% block Title_text %} 注册{% endblock %}{% block new_CSS %}{% endblock %}{% block data %} <div > <div > <div > <h1>注册</h1> <form ID="my_form"> {% for foo in form %} <div > <label for="{{ foo.auto_ID }}">{{ foo.label }}</label> {{ foo }} <span ></span> </div> {% endfor %} <div > <label for="ID_file">头像 <img src="/img/avatar/default.png" wIDth="80" height="80" ID="ID_img"> </label> <input type="file" name="file" ID="ID_file" > </div> <input type="button" value="提交" ID="ID_submit"> </form> </div> </div> </div>{% endblock %}{% block new_Js %} <script> $("#ID_file").change(function () { var file = $("#ID_file")[0].files[0] var filereader = new fileReader() filereader.readAsDataURL(file) filereader.onload = function () { $("#ID_img").attr('src',filereader.result) } }) $("#ID_submit").click(function () { var formdata = new FormData() var my_form_data = $("#my_form").serializeArray() $.each(my_form_data,function (k,v) { {#console.log(k)#} {#console.log(v)#} formdata.append(v.name,v.value) }) formdata.append('avatar',$("#ID_file")[0].files[0]) $.AJAX({ url: '/register/',type: 'post',processData: false,ContentType: false,data: formdata,success: function (data) { //console.log(data) if (data.code == 100) { location.href = '/login/' } else if (data.code == 101) { $.each(data.msg,v) { console.log(k) console.log(v) $("#ID_" + k).next().HTML(v[0]) if (k == '__all__') { $("#ID_re_pwd").next().HTML(v[0]) } }) } //定时器 setTimeout(function () { $(".error").HTML("") },3000) } }) }) </script>{% endblock %}
4.路由urls.py
from django.conf.urls import urlfrom django.contrib import adminfrom drf_API import vIEwsfrom django.vIEws.static import servefrom .settings import MEDIA_ROOTurlpatterns = [ url(r'^admin/',admin.site.urls),url(r'^register/',vIEws.register),url(r'^login/',vIEws.login),url(r'^get_code/',vIEws.get_code),url(r'^img/(?P<path>.*)',serve,{'document_root': MEDIA_ROOT}),]
5.视图from django.shortcuts import render,httpResponse,redirectfrom django.http import JsonResponsefrom PIL import Image,ImageDraw,ImageFontimport randomfrom io import BytesIOfrom django.contrib import authfrom drf_API.userinfo_form import Registerfrom drf_API import modelsdef register(request): if request.method=='GET': form=Register() return render(request,'register.HTML',{'form':form}) elif request.is_AJAX(): response={'code':100,'msg':None} form = Register(request.POST) if form.is_valID(): #校验通过的数据 clean_data=form.cleaned_data #把re_pwd剔除 clean_data.pop('re_pwd') #取出头像 avatar=request.fileS.get('avatar') if avatar: clean_data['avatar']=avatar user=models.UserInfo.objects.create_user(**clean_data) if user: response['msg'] = '创建成功' else: response['code'] = 103 response['msg'] = '创建失败' else: response['code']=101 #把校验不通过的数据返回 response['msg']=form.errors print(type(form.errors)) return JsonResponse(response,safe=False)def login(request): if request.method=='GET': return render(request,'login.HTML') else: print(request.POST) user_name=request.POST.get('name') pwd=request.POST.get('pwd') code=request.POST.get('code') user=auth.authenticate(username=user_name,password=pwd) print(user) if request.session.get('code').upper() !=code.upper(): #忽略大小写 return httpResponse('验证码错误') elif not user: return httpResponse('账号密码错误') else: auth.login(request,user) return httpResponse('登入成功')def get_code(request): if request.method == 'GET': img = Image.new('RGB',(350,40),(random.randint(0,255),random.randint(0,255))) # 写文字 # 生成一个字体对象 Font = ImageFont.truetype('/static/Gabriola.ttf',34) # 调用方法,返回一个画板对象 draw = ImageDraw.Draw(img) new_text ='' # 生成随机8位数字 for x_index in range(1,8): num = chr(random.randint(48,57)) word = chr(random.randint(65,90)) word_1 = chr(random.randint(97,122)) text =random.choice((num,word,word_1)) draw.text((x_index * 32,0),text,Font=Font) new_text +=text # 加点线 wIDth = 320 height = 35 for i in range(5): x1 = random.randint(0,wIDth) x2 = random.randint(0,wIDth) y1 = random.randint(0,height) y2 = random.randint(0,height) # 在图片上画线 draw.line((x1,y1,x2,y2),fill=(random.randint(0,255))) for i in range(33): # 画点 draw.point([random.randint(0,wIDth),height)],255))) x = random.randint(0,wIDth) y = random.randint(0,height) # 画弧形 draw.arc((x,y,x + 4,y + 4),90,255))) print(new_text) #存在session中 request.session['code']=new_text #存内存 f = BytesIO() img.save(f,'png') return httpResponse(f.getvalue())
大家周末娱乐
以上是内存溢出为你收集整理的周末手撸管理系统(一)全部内容,希望文章能够帮你解决周末手撸管理系统(一)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)