【问题标题】:How to retain select option value after submit in django?在 django 中提交后如何保留选择选项值?
【发布时间】: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 更新了我的代码。你能指出我的错误吗?

标签: django django-templates


【解决方案1】:

这里的问题是您的模板只是显示数据,它对状态一无所知。因此,如果您想实现这种行为,您需要从后端提供所有必需的数据。同样正如@solarissmoke 提到的,您应该使用django forms

例如(下面的伪代码)

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.data)
        if form.is_valid():
            form.save()
            redirect(reverse('myview'))
    else:
        form = MyForm(instance) # <- instance is object with previously saved data
    return render(request, 'my_template.html' , {'form': form})

第二部分

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        # <- here is problem 
        }    
    return render(request,"buy_book.html",context)

您正在将表单添加到 if request.method == 'POST' 内的上下文中。应该是这样的

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, 'form': form} # <- here

    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,
        }    
    return render(request,"buy_book.html",context)

【讨论】:

  • 我使用表单 API 更新了我的代码。你能告诉我错误在哪里吗?我的模板文件中没有加载表格。所以我得到空白输出
  • @Bhanukiran 我也建议使用form.is_valid() 就像在下面的帖子中显示的@Sayse 一样,如果你在form.is_valid() 之后实例化这样的form = SortForm(request.POST or None) 形式,你可以做u_quantity = form.cleaned_data('quantity') 这是首选的访问方式来自request.POST的数据
【解决方案2】:

在您看来,只有在发布数据中有数量时才将表单添加到上下文数据中,您应该将其添加到上下文中,因为它是您的视图所必需的。

您还应该真正使用表单,因此不要检查发布数据,而是检查表单的有效性,然后使用其清理后的数据。

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,
               'form': form}

    if form.is_valid():
        for i in my_products:
            rate= i.price
        #price is the column name in the model class
        u_quantity = form.cleaned_data.get('sort', 0)
        Quantity=int(u_quantity)
        total = rate*Quantity
        context['total'] = total
    return render(request,"buy_book.html",context)

'int' 对象不可迭代

可能是因为您的排序字段不是元组列表

choices = [(i, i) for i in range(1,6)]

【讨论】:

  • 我复制了你的代码,现在我收到错误,因为 'int' 对象不可迭代并且 django 回溯指向这一行,{{form.as_p}}
  • form.is_valid() 方法没有被执行
  • @Bhanukiran - 我已经更新,但这是一个与您的实际问题无关的单独问题
  • 我删除了 is_valid 方法,因为如果包含该方法,则不会进行计算
猜你喜欢
  • 2016-05-11
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2014-04-15
  • 2016-12-15
  • 2013-05-03
  • 2015-02-25
相关资源
最近更新 更多