django 测试8之电脑

setting:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')

主urls:

from django.contrib import admin
from django.urls import path,include,re_path
from protwo.settings import UPLOAD_ROOT
from django.views.static import serve

urlpatterns = [
# path('admin/', admin.site.urls),
path('',include('web.urls')),
re_path('^upload/(?P<path>.*)$',serve,{'document_root':UPLOAD_ROOT}),
]

分urls:

from django.contrib import admin
from django.urls import path
from web import views

urlpatterns = [
# path('admin/', admin.site.urls),
path('add_cate/',views.AddCate.as_view()),
path('add_computer/',views.AddComputer.as_view()),
path('index/',views.Index.as_view()),
path('show_cate/',views.ShowCate.as_view()),
]

models:

from django.db import models

# Create your models here.

class ComCate(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)

class Meta:
db_table = 'comcate'

def to_dict(self):
return {
'id':self.id,
'name':self.name
}

class Computer(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=7,decimal_places=2)
image_url = models.CharField(max_length=255)
cpu = models.CharField(max_length=30)
xian = models.IntegerField()
cate = models.ForeignKey(ComCate,on_delete='CASCADE')

class Meta:
db_table = 'computer'

def to_dict(self):
return {
'id':self.id,
'name':self.name,
'price':float(self.price)
'image_url':self.image_url,
'cpu':self.cpu,
'xian':self.xian,
'cate':self.cate.to_dict()
}

views:

from django.shortcuts import render,redirect,HttpResponse
from django.views import View
from web.models import *
import os
from protwo import settings
import json
# Create your views here.

"""
1.添加电脑品牌
2.添加电脑
3.首页展示所有电脑,并用分页,每页3条数据
4.展示所有电脑分类,并提供按钮或跳转标签
5.用ajax异步加载该分类下的所有电脑
"""
def uploadfile(img):
f = open(os.path.join(settings.UPLOAD_ROOT, '', img.name), 'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()

class AddCate(View):
def get(self,request):
return render(request,'add_cate.html')
def post(self,request):
if request.method == 'POST':
name = request.POST.get('name')
if name:
comcate = ComCate(name=name)
comcate.save()
return redirect('/add_cate/')

class AddComputer(View):
def get(self,request):
cate = ComCate.objects.all()
return render(request,'add_computer.html',locals())
def post(self,request):
if request.method == 'POST':
data = request.POST
name = data.get('name')
price = data.get('price')
cpu = data.get('cpu')
image_url = request.FILES.get('image_url')
uploadfile(image_url)
xian = data.get('xian')
c_id = data.get('c_id')
cate = ComCate.objects.filter(id=c_id).first()
if all([name,price,cpu,image_url,xian,c_id]):
computer = Computer(
name=name,price=price,cpu=cpu,
image_url='/upload/'+image_url.name,
xian=xian,cate=cate
)
computer.save()
return redirect('/add_computer/')

from django.core.paginator import Paginator

class Index(View):
def get(self,request):
computer = Computer.objects.all()
page_count = 3 # 每页数据数
page = int(request.GET.get('p', 1)) # 当前显示页
g = Paginator(computer, page_count) # 获取所有产品
goodslist = g.get_page(page) # 第xx页显示的产品
total_page = g.num_pages
return render(request,'index.html',
{'computerlist':goodslist,'current_page':page,'total_page':total_page})

class ShowCate(View):
def get(self,request):
cate = ComCate.objects.all()
return render(request,'show_cate.html',locals())
def post(self,request):
mes = {}
if request.method == 'POST':
id_ = request.POST.get('id')
if id_:
computer = Computer.objects.filter(cate=id_).all()
computerlist = []
for i in computer:
computerlist.append(i.to_dict())

mes['code'] = 200
mes['computerlist'] = computerlist
return HttpResponse(json.dumps(mes))

html:

add_cate:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
添加电脑品牌:<input type="text" name="name"><br>
<button type="submit">添加</button>

</form>
<a href="/add_computer/">跳转到添加电脑页面</a>
</body>
</html>

add_computer:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
电脑名称:<input type="text" name="name"><br>
电脑价格:<input type="text" name="price"><br>
电脑CPU:<input type="text" name="cpu"><br>
电脑尺寸:<input type="text" name="xian"><br>
电脑图片:<input type="file" name="image_url"><br>
选择品牌:
<select name="c_id" id="">
{% for i in cate %}
<option value="{{ i.id }}">{{ i.name }}</option>
{% endfor %}
</select>
<button type="submit">添加</button>

</form>
<a href="/index/">跳转到首页</a>
</body>
</html>

index:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="/static/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="/static/jquery.pagination.min.js"></script>
<link rel="stylesheet" href="/static/jquery.pagination.css">
</head>
<body>
<ul>
{% for i in computerlist %}
<li>{{ i.name }}</li>
<li>{{ i.price }}</li>
<li>{{ i.xian }}</li>
<li>{{ i.cpu }}</li>
<li><img src="{{ i.image_url }}" alt="" width="100px" height="100px"></li>
{% endfor %}
</ul>
<div class="pagination"></div>
<a href="/show_cate/">展示所有品牌</a>
</body>
<script type="text/javascript">
$(".pagination").pagination({
currentPage: {{current_page}},
totalPage: {{total_page}},
callback: function(current) {
window.location.href="/index/?p="+current
}
});

</script>
</html>

show_cate:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript"src="/static/jquery-1.12.4.min.js"></script>
</head>
<body>
{% for i in cate %}
<button type="button"><a href="javascript:get_computer({{ i.id }})">{{ i.name }}</a></button>
{% endfor %}
<div class="computer"></div>
</body>
<script type="text/javascript">
function get_computer(id) {
$.ajax({
url:'/show_cate/',
type:'post',
dataType:'json',
data:{'id':id},
success:function (res) {
if(res.code == 200){
var mes = res.computerlist
var len = mes.length
var html = '<ul>'
for(var i=0;i<len;i++){
html += '<li>'+ mes[i]['name'] +'</li>'
}
html += '</ul>'
$('.computer').html(html)
}

}
})
}
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/lhrd/p/10911167.html