0

首先让我说我是 Django 和一般编程的新手。花时间学习 python 并在一个多月前开始使用 django。我可以尝试在具有下拉菜单的电子商务应用程序上创建浏览点击,您可以在其中选择一个类别并对其进行排序。我认为我需要做的工作是在视图中,但不确定要编写的代码。

Views: 
    def browse(request):
        if request.method == 'POST':
           form = CategoryChoicesForm(request.POST)
           if form.is_valid():
               return HttpResponseRedirect('/')

model:
    CATEGORY_CHOICES = (
    ('Accessories', 'Accessories'),
    ('Bags', 'Bags'),
    ('Basic Tees', 'Basic Tees'),
    ('Belts', 'Belts'),
    ('Blazers', 'Blazers'),
    ('Boots', 'Boots'),
    ('Button Downs', 'Button Downs'),
    ('Cardigans', 'Cardigans'),
    ('Denim', 'Denim'),
    ('Footwear', 'Footwear'),
    ('Gloves', 'Gloves'),
    ('Hats', 'Hats'),
    ('Headphones', 'Headphones'),
    ('Henleys', 'Henleys'),
    ('Home', 'Home'),
    ('Jackets', 'Jackets'),
    ('Jewelry', 'Jewelry'),
    ('Outerwear', 'Outerwear'),
    ('Other', 'Other'),
    ('Pants', 'Pants'),
    ('Polos', 'Polos'),
    ('Scarves', 'Scarves'),
    ('Shirts', 'Shirts'),
    ('Shoes','Shoes'),
    ('Sneakers', 'Sneakers'),
    ('socks', 'Socks'),
    ('Sunglasses', 'Sunglasses'),
    ('Sweaters', 'Sweaters'),
    ('Sweatshirts', 'Sweatshirts'),
    ('Tank Tops', 'Tank Tops'),
    ('Tech', 'Tech'),
    ('T-Shirts', 'T-Shirts'),
    ('Undergarments', 'Undergarments'),
    ('Wallets', 'Wallets'),
    ('Watches', 'Watches'),
    )
    class Item(models.Model):
    item_name = models.CharField(max_length=120)
    item_picture = models.ImageField(upload_to="images/")
    item_description = models.CharField(max_length=999, blank=True)
    size = models.CharField(max_length=8, choices=SIZE_CHOICES, blank=True)
        item_brand = models.ForeignKey('Brand')
        category = models.CharField(max_length=25, choices=CATEGORY_CHOICES)

    def __unicode__(self):
        return self.item_name

Form:
    class CategoryChoicesForm(forms.Form):
        items = Item.get_category_display
        categoryoption = forms.ModelChoiceField(queryset=items, empty_label=None)
4

1 回答 1

1

使用基于类的通用视图 (ListView)。好好阅读文档。特别是关于查看对象子集动态过滤的部分。

就个人而言,我认为您应该将表单全部放在一起并将您自己的<a>标签添加到模板中。因此,也许也可以阅读URL 调度程序。我认为您需要该reverse()功能(可能在模板中)。

作为基本大纲 -

from django.views.generic import ListView
from books.models import Item

class CategoryListView(ListView):

    template_name = "item_list.html"

    def get_queryset(self):
        category = name__iexact=self.args[0])
        return Item.objects.filter(publisher=publisher)

self.args[0]您需要在 URLconf 中输入一个条目来获取"item_list.html"

于 2012-11-19T07:56:43.003 回答