开发者

How do I get get a custom template form to display a model with choices?

I'm a Django newbie and am making a simple grocery store app that has three columns: Item, Amount, and Category (e.g. Dairy, Bread, etc.). Here is my Item model:

CATEGORY_CHOICES = (
('B', 'Bread'),
('D', 'Dairy'),
)

class Item(models.Model):
     name = models.CharField(max_length=200)
     quantity = models.IntegerField()
     category = models.CharField(max_length=1, choices=CATEGORY_CHOICES)

What should I write in my html form to let the user pick the one of the categories? Here's what I have so far:

<table>
{% for each_item in total_items %}
<tr>
<td><label for="id_item{{each_item}}" id="tbb">Item</label></th>
<td><label for="id_amount{{each_item}}" id="tbb">Amount</label></th>
<td><label for="id_category{{each_item}}" id="tbb">Category</label></th>
</tr>
<tr>
<td><input id="id_item{{each_item}}" type="text" name="item{{each_item}}" size="64"/></td> 
<td><input id="id_amount{{each_item}}"开发者_JAVA技巧 type="text" name="amount{{each_item}}" size="24"/></td> 

What should come next, to let the user select within the category list?

Haven't found much help in the Django documentation.


I may be misunderstanding what you're looking for but it sounds like you just want a select menu with each catagory option. When the user selects the category the items can be refined on the server side. Alternatively you could use check boxes so that multiple categories are selected.

<select name="category">
    {% for category in categories %}
    <option>{{ category }}</option>
    {% endfor %}
</select>

or

{% for category in categories %}
    {{ category }}<input type="checkbox" name="{{ category }}" class="categories"/>
{% endfor %}

when the select is submitted you can refine the items shown with something like:

items = Item.objects.filter(category=request.GET['category'])

or

items = Item.objects.filter(category__in=request.GET['categories'])

is this what you're looking for?


I don't understand what all that logic is for. You just do this:

{{ form.category }}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜