【问题标题】:how to name numerous dynamic input fields for post method - Django如何为 post 方法命名多个动态输入字段 - Django
【发布时间】:2021-04-01 23:09:47
【问题描述】:

在我的在线商店中,我从两个不同的应用程序中获取所有产品和服务,并将它们列出以供用户创建愿望清单。

每个产品或服务都显示在一个引导卡中,其中包含一个用于计算产品数量的输入字段。

#views.py
def my_products(request):
    
    ip_sensor = Ip_sensor.objects.all().order_by('title')
    control_valves = ControlValves.objects.all().order_by('title')

    context = {
        'ip_sensor': ip_sensor,
        'control_valves': control_valves,        
    }
    return render(request, 'users/basket/my_products.html', context)

然后在模板中,它们是这样显示的:

<form method="post" id="add_to_wishlist" data-url="{% url 'my_products' %}">
{% csrf_token %}

{% if ip_sensor %}
{% for item in ip_sensor %}

    <div class="card">

      <div class="card-body">

        <div class="row">

          <div class="col-12">
            <p class="card-text text-center text-capitalize">{{ item.title }}</p>
          </div>

          <div class="col-12">
            <div class="form-group">
              <input type="hidden" name="tag" value="{{ item.type }}">  <!-- what to put in name field of this line -->         
              <input type="hidden" name="item_id" value="{{ item.id }}">   <!-- what to put in name field of this line -->         
              <label for="count" class="control-label">count</label>     
              <input  type="text"    
                      id="count" 
                      name="count"             <!-- what to put in name field of this line -->         
                      placeholder="Count" 
                      class="form-control"
                      autofocus/> 
            </div>
          </div>

        </div>
        
      </div>
    </div>

{% endfor %}
{% endif %}

</form>

问题:

当我通过 POST 方法将每个产品或服务的计数返回到我的views.py 以保存到他的愿望清单时,我不知道如何区分返回的值??

由于项目正在 for 循环中显示,并且我想将每个选定的项目分别保存在 WishListItem 对象(模型)中,我需要分别命名每张卡的输入字段但我不知道如何去做吧。

我可以这样保存每个项目:

if request.method == 'POST':
    owner = request.user

    count = request.POST.get('count')
    tag = request.POST.get('tag') 
    object_id = request.POST.get('item_id')
    
    wishlist = WishListItem(owner=owner,
                            content_type=class_types[tag],
                            object_id=object_id,
                            tag=tag,
                            count=count)
    wishlist.save()
    
    return redirect('my_products')

【问题讨论】:

    标签: html post django-views django-templates http-post


    【解决方案1】:

    当有多个同名输入时,request.POST 具有所有这些输入元素值的列表。因此,您可以使用 request.POST.getlist('item_id') 获取所有项目 ID,它将返回包含所有 ID 的列表。在您的 html 中,您可以使用 id 将所有其他输入命名为 name 属性的一部分,如下所示:

    ...
    <input type="hidden" name="tag_{{ item.id }}" value="{{ item.type }}">  <!-- item id has become part of the input name -->         
    <input type="hidden" name="item_id" value="{{ item.id }}">   <!-- all item ids will be accessed as list in view -->         
    <label for="count" class="control-label">count</label>     
    <input  type="text"    
                          id="count" 
                          name="count_{{ item.id }}" <!-- item id has become part of the input name -->         
                          placeholder="Count" 
                          class="form-control"
                          autofocus/>
    ...
    

    在您看来,您可以像这样访问所有值:

    ...
    for object_id in request.POST.getlist('item_id'): #this will contain a list with all item ids in it
        count = request.POST.get('count_%s'%object_id) #as html inputs are named with ids as part of name you can access them
        tag = request.POST.get('tag_%s'%object_id) #as html inputs are named with ids as part of name you can access them
        wishlist = WishListItem(owner=owner,
                        content_type=class_types[tag],
                        object_id=object_id,
                        tag=tag,
                        count=count)
        wishlist.save()
    ...
    

    【讨论】:

    • 好主意,但有一个问题,因为产品是从多个表加载的,它们可能具有相同的ids。然后我得到相同的 WishListItem 在这个 for 循环之后创建的对象。另一个问题是即使值是0,也会为它们创建一个WishListItem,我尝试了if count != 0: wishlist = WishListItem(owner=owner...,但它没有用。
    【解决方案2】:

    我根据@datosula 的回答找到了答案。

    由于产品id可能是重复的,因为产品是从不同的表中加载的,所以需要一个唯一的标签来区分views.py中的返回值。我混合了产品的标题和产品类型来实现这一点:

    <div class="form-group">
    
        <input type="hidden" name="title_type" value="{{ item.title }}{{ item.type }}">
        <input type="hidden" name="item_id_{{ item.title }}{{ item.type }}" value="{{ item.id }}">
        <input type="hidden" name="tag_{{ item.title }}{{ item.type }}" value="{{ item.type }}">
        <input type="hidden" name="title_{{ item.title }}{{ item.type }}" value="{{ item.title }}">
                                      
        <div class="text-center">
            <input  type="number" 
                    id="count" 
                    name="count_{{ item.title }}{{ item.type }}" 
                    placeholder="count" 
                    class="form-control"
                    value="0"
                    min="0"
                    max="9999"
                    autofocus/>
        </div>
    
    </div>
    

    在views.py 中,我得到了值并创建了如下对象:

    ....
    for item in request.POST.getlist('title_type'):
                object_id = request.POST.get('item_id_%s'%item)
                tag = request.POST.get('tag_%s'%item)
                print('\ntag: ', tag )
                print('\nclass_types[tag]: ', class_types[tag])
                count = request.POST.get('count_%s'%item)
                title = request.POST.get('title_%s'%item)
                if count != '0':  # only save those products that their count is not 0
                    wishlist = WishListItem(owner=owner,
                                    content_type=class_types[tag],
                                    object_id=object_id,
                                    tag=tag,
                                    count=count,
                                    title=title)
                    wishlist.save()
    ....
    

    希望对某人有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多