django 王中王15之淘宝

seetting:

STATIC_URL = '/static/'

STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'static')
]

 

urls:

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

urlpatterns = [
path('add_goods/', views.add_goods),
path('', views.index),
]

 

models:

from django.db import models

# Create your models here.


class Goods(models.Model):
name = models.CharField(max_length=50)
price = models.CharField(max_length=50)
cate = models.CharField(max_length=50)
img = models.CharField(max_length=255)

 

 

 

views:

from django.shortcuts import render
from web import models
from Django_15 import settings
import os
from django.core.paginator import PageNotAnInteger, EmptyPage, Paginator


# Create your views here.
def add_goods(request):
if request.method == 'GET':
return render(request, 'add_goods.html')
if request.method == 'POST':
name = request.POST.get('name')
price = request.POST.get('price')
cate = request.POST.get('cate')
file = request.FILES.get('img')
if file:
base_path = settings.STATICFILES_DIRS[0]
file_path = os.path.join(base_path, 'img/' + file.name)
with open(file_path, 'wb') as fp:
if file.multiple_chunks:
for buf in file.chunks():
fp.write(buf)
else:
fp.write(file.read())

models.Goods.objects.create(
name=name,
price=price,
cate=cate,
img='img/' + file.name,
)
return render(request, 'add_goods.html',locals())


def index(request):
all = models.Goods.objects.all()
p = Paginator(all, 3)
page_id = request.GET.get('page_id')
if page_id:
try:
all = p.page(page_id)
except PageNotAnInteger:
all = p.page(1)
except EmptyPage:
all = p.page(1)
else:
all = p.page(1)
return render(request, 'index.html', locals())

 

 

html:

add_goods:





添加产品



{% csrf_token %}
请输入产品名称:

请输入产品价格:

请输入产品分类:

请上传产品图片:




 

 

 

index:






首页展示

{% load static %}

{% for a in all %}
{#

#}



{{ a.name }}

{{ a.cate }}

价格:¥{{ a.price }}

{{ a.name }}

{#
#}
{% endfor %}


{% if all.has_previous %}
上一页
{% else %}
上一页
{% endif %}
{% for num_ in p.page_range %}
{% if all.number == num_ %}
{{ num_ }}
{% else %}
{{ num_ }}
{% endif %}
{% endfor %}

{% if all.has_next %}
下一页
{% else %}
下一页
{% endif %}

{# 跳转 #}




 

转载于:https://www.cnblogs.com/lhrd/p/10914427.html

你可能感兴趣的:(python,javascript,人工智能,ViewUI)