1、上架时间小于或等于今天,并且按照降序排列
listproducts = Product.objects.filter(date_available__lt= datetime.datetime.now().date()).order_by("-date_available")
2、上架时间大于或等于今天
listproducts = Product.objects.filter(date_available__gt= datetime.datetime.now().date()).
3、分页
前台代码
{% if listproducts.has_previous %} <a href="?page={{ listproducts.previous_page_number }}">上一页</a> {% endif %} <span class="current"> 第 {{ listproducts.number }} 页 总共 {{ listproducts.paginator.num_pages }} 页 </span> {% if listproducts.has_next %} <a href="?page={{ listproducts.next_page_number }}">下一页</a> {% endif %}
后台代码
#购买首页 def storenew_view(request): #上架时间小于或等于今天,并且按照降序排列 listproducts = Product.objects.filter(date_available__lt= datetime.datetime.now().date()).order_by("-date_available") #从session获取购物车数据 cart = request.session.get("cart",None) #上架时间小于或等于今天,分页每页显示5个 paginator = Paginator(listproducts ,5) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: listproducts = paginator.page(page) except : listproducts = paginator.page(paginator.num_pages) t=get_template('depotapp/storenew.html') c=RequestContext(request,locals()) return HttpResponse(t.render(c))
4、session应用
cart = request.session.get("cart",None)//取值
if not cart: //判断cart是否不存在
#必须在setting.py中加上 SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
#否则会报错 <depotapp.cart.Cart object at 0x00000000036633C8> is not JSON serializable
request.session["cart"] = cart//赋值
#清空购物车 给一个初始值
def clean_cart(request):
request.session['cart']=Cart()
return view_cart(request)
5、表单
表单定义和验证
#/usr/bin/python #coding: utf8 from django import forms from models import * import itertools def anyTrue(predicate, sequence): return True in itertools.imap(predicate, sequence) def endsWith(s, *endings): return anyTrue(s.endswith, endings) class ProductForm(forms.ModelForm): class Meta: model = Product # exclude = [] # uncomment this line and specify any field to exclude it from the form def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) def clean_price(self): price = self.cleaned_data['price'] if price<=0: raise forms.ValidationError("价格必须大于零") return price def clean_image_url(self): url = self.cleaned_data['image_url'] if not endsWith(url, '.jpg', '.png', '.gif'): raise forms.ValidationError('图片格式必须为jpg、png或gif') return url
<table> <form action="" method="POST"> {% csrf_token %} {{form}} <tr> <td colspan="2" align="right"><input type="submit" value="Create"/></td> </tr> </form> </table> <p><a href="{% url 'depotapp.views.list_product'%}">返回首页</a></p>
#创建产品 def create_product(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() form = ProductForm() t = get_template('depotapp/create_product.html') c = RequestContext(request,locals()) return HttpResponse(t.render(c))
编辑表单
def edit_product(request, id): product_instance = Product.objects.get(id=id) form = ProductForm(request.POST or None, instance = product_instance) if form.is_valid(): form.save() t=get_template('depotapp/edit_product.html') c=RequestContext(request,locals()) return HttpResponse(t.render(c))
提交成功后跳转到**页面
@transaction.commit_on_success def create_order(request): form = OrderForm(request.POST or None) if form.is_valid(): order = form.save() for item in request.session['cart'].items: item.order = order item.save() clean_cart(request) return view_order(request,int(item.order.id)) t = get_template('depotapp/create_order.html') c = RequestContext(request,locals()) return HttpResponse(t.render(c))
6、一些查询语句
list_items = Product.objects.all()//查询所有
product_instance = Product.objects.get(id = id)//查询id为id的数据