首页 > 解决方案 > 在 Django Template For Selection 中同时迭代两个表 - Python Django

问题描述

在这里,我想遍历两个表数据并使其在SELECT标记中可供选择,这是一个映射表,所以我想同时迭代两个表。

我想将此映射存储在映射表中。让我展示我的代码,以便您更好地理解它。

模型.py

class Product(models.Model):
    prod_ID = models.AutoField("Product ID", primary_key=True)
    prod_Name = models.CharField("Product Name", max_length=30, null=False)
    prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
    prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
    prod_img = models.ImageField("Product Image", null=True)

    def __str__(self):
        return "{}-->{}".format(self.prod_ID,
                                self.prod_Name)


class Size(models.Model):
    size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
    prod_size = models.CharField("Product Size", max_length=20, null=False)

    def __str__(self):
        return "{size_id}-->{prod_size}".format(size_id=self.size_id,
                                                prod_size=self.prod_size)


class SizeProductMapping(models.Model):
    size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
    size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
    prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")

    def __str__(self):
        return ".`.  {}_____{}".format(self.size_id,
                                       self.prod_id)

在上述模型中,我想将尺寸产品映射存储在SizeProductMap表中。

视图.py

def sizeProductMap(request):
    
    # Here I am fetching products and size ID to give option while add new records 
    productSize_show = Size.objects.all()
    print(productSize_show)
    product_show = Product.objects.all()
    print(product_show)
    attribute_values = zip(productSize_show, product_show)
    print(attribute_values)

    if request.method == 'POST':
        size_id = request.POST['size_id']
        product_id = request.POST['prod_id']
        sizeProductMap_update = SizeProductMapping(size_id=size_id, prod_id=product_id)
        
        # saving record to table
        sizeProductMap_update.save()
        return redirect('/admin1/productSize', {'attribute_values': attribute_values})
    else:
        sizeProductMap_show = SizeProductMapping.objects.all()
        # start paginator logic
        paginator = Paginator(sizeProductMap_show, 3)
        page = request.GET.get('page')
        try:
            sizeProductMap_show = paginator.page(page)
        except PageNotAnInteger:
            size_show = paginator.page(1)
        except EmptyPage:
            sizeProductMap_show = paginator.page(paginator.num_pages)
        # end paginator logic
        return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show})

views.py中,我正在尝试更新数据库。

现在看看我的 html 模板,请检查它并告诉我我做错了什么,并请提供解决方案。

SizeProductMap.html

{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
    <center>Size Product Map</center>
</h1>
<div class="container">
    <div class="row">
        <div class="col-lg-2"></div>
        <div class="col-lg-10">

            <button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
                Size Product Mapping
            </button>
            <div class="modal fade" id="modal-primary">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">Add Size Product Mapping</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="modal-body mt-2">
                            <form action="{% url 'admin-size-product-map'%}" method="POST"
                                  enctype="multipart/form-data">
                                {% csrf_token %}

                                <!-- Here I am trying to fetch the *product_id* and *size_id* but not getting it-->

                                {% for x in attribute_values %}
                                <div class="form-group">
                                    <label for="sel1">Select Size ID : </label>
                                    <select class="form-control w-50" id="sel1">
                                        <option name="size_id">{{x.0.size_id}}</option>
                                    </select>
                                </div>
                                <br>
                                <div class="form-group">
                                    <label for="sel2">Select Product ID : </label>
                                    <select class="form-control w-50" id="sel2">
                                        <option name="product_id">{{x.1.prod_ID}}</option>
                                    </select>
                                </div>
                                <br>
                                <input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
                                {% endfor %}
                                <div class="modal-footer justify-content-between">
                                    <button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
            <div class="container-fluid ">
                <div class="row">
                    <div class="card mt-2 border border-secondary">
                        <div class="card-header">
                            <h3 class="card-title ">Size Product Map Table</h3>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">

                            <table class="table table-bordered border border-info">
                                <thead>
                                <tr>
                                    <th>Size Product Mapping Id</th>
                                    <th>Product ID</th>
                                    <th>Size ID</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody class="justify-content-center">
                                {% for x in sizeProductMap_show %}
                                <tr>
                                    <th>{{x.size_p_map_id}}
                                    <td>{{x.prod_id}}</td>
                                    <td>{{x.size_id}}</td>
                                    <td><a href="#"
                                           class="btn btn-outline-primary mt-2"><i
                                            class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
                                        <a href="#"
                                           class="btn btn-outline-danger mt-2"><i
                                                class="fa fa-trash" aria-hidden="true"></i></a>
                                    </td>
                                </tr>

                                {% endfor %}

                                </tbody>
                            </table>

                        </div>
                        <!-- /.card-body -->
                        <div class="card-footer clearfix ">
                            <ul class="pagination pagination-sm m-0 justify-content-center">
                                {% if sizeProductMap_show.has_previous %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{sizeProductMap_show.has_previous_page_number}}">
                                    Previous </a>
                                </li>
                                {% endif%}
                                {% for x in sizeProductMap_show.paginator.page_range %}

                                {% if sizeProductMap_show.number == x %}
                                <li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
                                {% else%}
                                <li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
                                {% endif %}
                                {% endfor %}

                                {% if sizeProductMap_show.has_next %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{sizeProductMap_show.has_next_page_number}}">
                                    Next </a>
                                </li>
                                {% endif %}
                            </ul>
                        </div>
                    </div>
                    <!-- /.card -->
                </div>
            </div>

        </div>
    </div>
</div>
{% endblock %}

标签: pythonhtmlmysqldjangodatabase

解决方案


我已经修改了我的视图并稍微更改了 html,现在我可以遍历这些字段。

订单.html

{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
<div class="container">
    <div>
        <div class="row rounded mx-auto d-block d-flex justify-content-center">
            <button class="btn btn-secondary my-2 mr-1">Custom</button>
            <button class="btn btn-secondary my-2 ml-1">Package</button>
        </div>
        <div class="row">
            <div class="col-4">
                <div class="card border border-secondary">
                    <div class="card body mx-2 mt-4 mb-2">
                        {% for product in products %}
                        <a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
                           href="{% url 'user-order' product.prod_ID  %}">
                            <h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
                        <div class="dropdown-divider"></div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            <div class="col-8">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" id="templateValue" name="templateValue" value=""/>
                    {% csrf_token %}
<div class="card mx-2 my-2 border border-secondary">
                        <div class="my-2">
{% if sizesList %}
                            <div class="form-group">
                                <div class="form-group row mx-2">
                                    <label for="sizeList"
                                           class="form-control-label font-weight-bold card-header col-4 ml-4"
                                           style="background-color:#e3e4e6"><h5>Sizes : </h5></label>
                                    <div id="sizeList">
                                        {% for s in sizesList %}
                                        <input id="{{s}}" class="mx-2 my-auto" type="radio" name="size" value="{{s}}"
                                               required="required">
                                        <label for="{{s}}">{{s}}</label><br>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    <div class="row rounded mx-auto d-block d-flex justify-content-center">
                        <button type="submit" class="btn btn-success my-2">Place Order</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

视图.py

def order(request, id):
    products = Product.objects.all()
    sizesList = []
    try:
        sizesMap = SizeProductMapping.objects.filter(prod_id=id)
        sizesList = [data.size_id.prod_size for data in sizesMap]
    except AttributeError:
        pass
    if request.method == 'POST':
        try:
            size = request.POST['size']
            print(size)
        except MultiValueDictKeyError:
    context = {'products': products,
               'sizesList': sizesList,
               }

    return render(request, 'user/order.html', context)

推荐阅读