在单页上处理不同形式的 post 请求 -Django

handling different forms post request on single page -Django

我是新手,正在做网站。在这个网站上,我创建了管理面板来管理不同的产品和属性。

我有一个名为 size.html 的页面,我应该更改它的名称并使其成为 productAtributes.html 并且在这个页面上,我想对不同的产品属性执行所有 添加、更新、删除 操作。

我的代码如下:

models.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 Color(models.Model):
    color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
    prod_color = models.CharField("Product Color", max_length=50, null=False)

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


class PaperChoice(models.Model):
    paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
    paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)

    def __str__(self):
        return "{}-->{}".format(self.paper_id,
                                self.paper_choices_name)

views.py

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect

from user.models import *

def size(request):
    if request.method == 'POST':
        size_store = request.POST['prod_size']
        size_update = Size(prod_size=size_store)
        size_update.save()
        return redirect('/admin1/productSize')
    else:
        size_show = Size.objects.all()
        # start paginator logic
        paginator = Paginator(size_show, 3)
        page = request.GET.get('page')
        try:
            size_show = paginator.page(page)
        except PageNotAnInteger:
            size_show = paginator.page(1)
        except EmptyPage:
            size_show = paginator.page(paginator.num_pages)
        # end paginator logic
        return render(request, 'admin1/size.html', {'size_show': size_show})


def size_edit(request, id):
    size_edit = Size.objects.filter(size_id=id)
    return render(request, 'admin1/size.html', {'size_edit': size_edit})


def size_edit_update(request, id):
    if request.method == 'POST':
        size_store = request.POST['prod_size']
        size_update = Size(size_id=id, prod_size=size_store)
        size_update.save()
        return redirect('/admin1/productSize')


def size_delete(request, id):
    size_deletee = Size.objects.filter(size_id=id)
    size_deletee.delete()
    return redirect('/admin1/productSize')

当我为 Size 创建 添加、更新、删除 功能时,我将对 color 做同样的事情 纸张选择

size.html

{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
    <center>Size</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
            </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 Product Size</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-product-size'%}" method="POST" enctype="multipart/form-data">
                                {% csrf_token %}
                                <label>Product Size:</label>
                                <input type="text" name="prod_size" class="form-control w-50"><br>
                                <br>
                                <input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>

                                <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 -->

            <br>
            {% if size_show %}
            <div class="container-fluid ">
                <div class="row">
                    <div class="card mt-2 border border-secondary">
                        <div class="card-header">
                            <h3 class="card-title ">Product Table</h3>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">

                            <table class="table table-bordered border border-info">
                                <thead>
                                <tr>
                                    <th>Product Id</th>
                                    <th>Product Size</th>
                                </tr>
                                </thead>
                                <tbody class="justify-content-center">
                                {% for x in size_show %}

                                <tr>
                                    <td>{{x.size_id}}</td>
                                    <td>{{x.prod_size}}</td>
                                    <td><a href="/admin1/size_edit/{{x.size_id}} "
                                           class="btn btn-outline-primary mt-2"><i
                                            class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
                                        <a href="/admin1/size_delete/{{x.size_id}}"
                                           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 size_show.has_previous %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{size_show.has_previous_page_number}}">
                                    Previous </a>
                                </li>
                                {% endif%}
                                {% for x in size_show.paginator.page_range %}

                                {% if size_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 size_show.has_next %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{size_show.has_next_page_number}}"> Next </a>
                                </li>
                                {% endif %}
                            </ul>
                        </div>
                    </div>
                    <!-- /.card -->
                </div>
            </div>
            {% endif %}
            {% if size_edit %}
            {% for x in size_edit %}
            <form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
                {% csrf_token %}
                <label>Size Name:</label>
                <input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>

                <input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
            </form>
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

为了执行 views.py 的操作,我创建了 size.html .Nut 1012 产品属性,对于这些属性我不想创建单独的 html 页面.

我想对单个 html 页面中的所有属性进行所有操作。可能吗?

意味着根据属性类型请求页面数据应该动态变化,我不必为每个属性创建单独的模板页面。

您需要在您的视图中制作表单,而不是模板,我不确定这是否是最佳做法,但这是我认为您可以做到这一点的唯一方法,(使用 Class-Based Views 会简化这个过程很多)但是如果你想坚持功能,这就是你要做的。

让我们输入一行:

<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>

让我们使用 Django 的标签并将其变成这样:

<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">

class 可能相同,但您可以将相同的功能扩展到 class 或类型字段。

在后端,您想列出所有要显示的元素,并带有嵌套字典:

forms = [  # Each form
    [  # Each field within the form, this way, you can have a different amount each time
        {'display_name': 'Product Size',  # label Display name
         'name': 'prod_size'},  # name tag value
        {'display_name': "it's value", # This is a different field
         'name': 'just an example'}  
    ],
]

然后你可以在模板中做一个for循环:

{% for form in forms %}
    {$ for field in form %}
       <label>{{field.display_name}}:</label>
       <input type="text" name="{{field.name}}" class="form-control w-50">

我不太确定你想在你的代码中做什么,所以我没有让这个例子太具体,但希望它能给你灵感,让你走上正确的轨道,如果您需要更多帮助,只需询问