views.py
import os, random
from django.contrib import messages
import django.utils.timezone as timezone
from django.shortcuts import render, HttpResponse
from mall.forms import *
from mall.models import *
# Create your views here.
def test(request):
#return HttpResponse('test page of mall app')
goodsimg_form = forms.GoodsImgForm()
return render(request, 'goodsimg.html', locals())
def list(request):
goods = Goods.objects.get(id=1)
goodsimg = goods.goodsimg_set.all()
gi = goodsimg[1]
return render(request, 'list.html', locals())
def makepath(path):
if not os.path.exists(path):
os.mkdir(path)
def datepath():
year = timezone.now().year
month = timezone.now().month
day = timezone.now().day
pathstr = 'images/' + str(year)
makepath(pathstr)
pathstr = pathstr + '/' + str(month)
makepath(pathstr)
pathstr = pathstr + '/' + str(day)
makepath(pathstr)
return pathstr
def randname(datepath, oldname):
ext = oldname[oldname.rfind('.'):]
filename = random.randint(1, 1000)
filename = str(filename) + ext
while os.path.exists(filename):
filename = random.randint(1, 1000)
filename = str(filename) + ext
return filename
def single_upload(f):
datepathstr = datepath()
filename = randname(datepath, f.name)
file_path = os.path.join(os.path.abspath('.'), datepathstr, filename) # 拼装目录名称+文件名称
with open(file_path, 'wb+') as destination: # 写文件word
for chunk in f.chunks():
destination.write(chunk)
destination.close()
return datepathstr + '/' + filename
def upload(request):
if request.method == 'POST':
goods_form = GoodsForm(request.POST, request.FILES)
files = request.FILES.getlist('file_field') # 获得多个文件上传进来的文件列表。
if goods_form.is_valid(): # 表单数据如果合法
title = goods_form.cleaned_data['title']
brief = goods_form.cleaned_data['brief']
unit = goods_form.cleaned_data['unit']
quantity = goods_form.cleaned_data['quantity']
ondesk = goods_form.cleaned_data['ondesk']
price = goods_form.cleaned_data['price']
goods = Goods(title=title, brief=brief, unit=unit, quantity=quantity, ondesk=ondesk)
goods.save()
Price.objects.create(gid=goods, price=price)
for f in files:
filename = single_upload(f) # 处理上传来的文件
GoodsImg.objects.create(gid=goods, path=filename)
messages.add_message(request, messages.INFO, '添加成功')
else:
goods_form = GoodsForm()
return render(request, 'goods.html', locals())
models.py
# -*- encoding: utf-8 -*-
from django.db import models
# Create your models here.
class User(models.Model):
nickname = models.CharField(max_length = 32)
mobile = models.CharField(max_length = 16)
email = models.EmailField(max_length = 254, blank = True)
address = models.CharField(max_length = 254, blank = True)
createtime = models.DateTimeField(auto_now_add = True)
updatetime = models.DateTimeField(auto_now = True)
def __str__(self):
return self.mobile
class ExtraMobile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mobile = models.CharField(max_length = 16)
def __str__(self):
return self.mobile
forms.py
from django.forms import ModelForm
from django import forms
from mall import models
from captcha.fields import CaptchaField
class GoodsForm(forms.Form):
title = forms.CharField()
brief = forms.CharField(widget=forms.Textarea)
unit = forms.ChoiceField(choices = (
('斤', '斤'),
('盒', '盒'),
('袋', '袋'),
('箱', '箱'),
('瓶', '瓶'),
('件', '件'),
('只', '只'),
('双', '双'),
('包', '包'),
))
quantity = forms.IntegerField()
ondesk = forms.BooleanField()
price = forms.DecimalField()
file_field = forms.FileField(label='选择多个文件', widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': "bg-info"}))
class PriceForm(forms.ModelForm):
class Meta:
model = models.Price
fields = ('gid', 'price', 'pov')
class GoodsImgForm(forms.ModelForm):
class Meta:
model = models.GoodsImg
fields = ('gid', 'path')
class ExtraMobileForm(ModelForm):
class meta:
model = models.ExtraMobile
fields = "__all__"
base.html
<!--base.html-->
{% load static %}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test website</title>
<link rel="stylesheet" href="{% static "bootstrap.min.css" %}">
<link rel="stylesheet" href="{% static "glyphicon.css" %}" />
<link rel="stylesheet" href="{% static "animate.css" %}" />
<link rel="stylesheet" href="{% static "swiper.min.css" %}" />
{% block css %} {% endblock %}
<script src="{% static "jquery-3.3.1.min.js" %}"></script>
<script src="{% static "swiper.min.js" %}"></script>
<script src="{% static "bootstrap.min.js" %}"></script>
<script src="{% static "popper.min.js" %}"></script>
<script src="{% static "animate.js" %}"></script>
{% block jsheader %} {% endblock %}
</head>
<body>
{% include 'header.html' %}
{% block content %} {% endblock %}
{% include 'footer.html' %}
{% block jsfooter %} {% endblock %}
</body>
</html>
main.html
{% extends 'base.html' %}
{% load static %}
{% block css %}<link rel="stylesheet" href="{% static "css/about.css" %}" />{% endblock %}
{% block content %}
{% if message %}
<div class="alert alert-warning">{{ message }}</div>
{% endif %}
<form name="myform" method="post">
{% csrf_token %}
<table>
{{ user_form.as_table }}
</table>
<input type="submit" value="submit">
</form>
{% endblock %}