【发布时间】:2016-06-01 05:16:40
【问题描述】:
我创建了带有四个选项值(1、2、3、4)的选择标签。当我选择 4 并按提交时,它会变回 1。选择选项包含用户所需的产品数量。那么如何按提交按钮后保留选项值。我试过这样,按提交按钮后值变回1。有什么办法可以克服这个问题吗?
我的模板文件,
<label for="quantity">Quantity</label>
<select id="quantity" name="quantity">
<option value="1" {% if quantity == '1' %}selected{% endif %}>1</option>
<option value="2" {% if quantity == '2' %}selected{% endif %}>2</option>
<option value="3" {% if quantity == '3' %}selected{% endif %}>3</option>
<option value="4" {% if quantity == '4' %}selected{% endif %}>4</option>
</select>
<input type="submit" value="Buy"/>
更新: 表格.py,
class SortForm(forms.Form):
RELEVANCE_CHOICES = (
(1,'1'),(2, '2'),(3,'3'), (4,'4'),(5,'5'),
)
sort = forms.ChoiceField(choices = RELEVANCE_CHOICES,label='Quantity')
views.py,
from .forms import SortForm
@csrf_protect
def buy_book(request,pk):
form = SortForm(request.POST or None)
my_products = Add_prod.objects.filter(pk=pk)
#Add_prod is the model class name
context = {"products":my_products}
if request.POST.get('quantity'):
for i in my_products:
rate= i.price
#price is the column name in the model class
u_quantity = request.POST.get('quantity')
Quantity=int(u_quantity)
total = rate*Quantity
context = {
"products":my_products,
"Total":total,
"form": form
}
return render(request,"buy_book.html",context)
我在模板文件中添加了这一行,
{{form.as_p}}
现在我得到空白输出。我认为该表单无法在模板中识别。
【问题讨论】:
-
为什么要手动渲染
select而不是使用Forms API。它会为你做那种事情。 -
除上述之外,您应该展示您的视图(或至少是上下文数据)
-
@solarissmoke 我使用表单 api 更新了我的代码。你能指出我的错误吗?