我想使用Django表单编辑SizeProductMapping模型,但该表单未呈现-Django [英] I want to edit SizeProductMapping model using Django forms but The form is not rendering - Django

查看:51
本文介绍了我想使用Django表单编辑SizeProductMapping模型,但该表单未呈现-Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个编辑表单以使用Django模型表单更新数据库,但问题是在编辑表单时 sizeProductMap.html 页面的编辑表单部分未呈现(sizeProductMap_edit ).

I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.

我的模型如下所示.

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

这是我用来添加和编辑模型的表格.

This is the form I used to add and edit the model.

forms.py

from django import forms

from user.models import SizeProductMapping


class SizeProductMapForm(forms.ModelForm):

    class Meta:
        model = SizeProductMapping
        fields = ['size_id', 'prod_id']

这是我创建的用于添加,更新和删除记录的视图.

Here is the view I created to add ,update and delete the record.

views.py

def sizeProductMap(request):
    form = SizeProductMapForm(request.POST, request.FILES)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
        return redirect("/admin1/sizeProductMap/")
    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:
            sizeProductMap_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, 'form': form})


def sizeProductMap_delete(request, id):
    sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
    sizeProductMap_delete.delete()
    return redirect('/admin1/productSizeMap')


def sizeProductMap_edit(request, id):
    instance = SizeProductMapping.objects.get(size_p_map_id=id)
    form = SizeProductMapForm(instance=instance)
    if request.method == 'POST':
        form = SizeProductMapForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            return redirect('/admin1/sizeProductMap')

    return render(request, 'admin1/sizeProductMap.html', {'form': form})

这是我的网址.

urls.py

from django.urls import path

from admin1 import views

urlpatterns = [

    path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
    path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
    path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]

这是HTML页面,我要根据页面请求在其中显示表单.

This is the Html page where I want to display the form according to the page request.

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">
            {% if sizeProductMap_show %}
            <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 %}
                                <table border="1" class="table table-bordered border border-info">
                                    <tr>
                                        <th>
                                            {{form.size_id.label_tag}}
                                        </th>
                                        <td>{{form.size_id}}</td>
                                    </tr>
                                    <tr>
                                        <th>
                                            {{form.prod_id.label_tag}}
                                        </th>
                                        <td>
                                            {{form.prod_id}}
                                        </td>
                                    </tr>
                                </table>
                                <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 -->

            <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>
                                    <td>{{x.size_p_map_id}}</td>
                                    <td>{{x.prod_id}}</td>
                                    <td>{{x.size_id}}</td>
                                    <td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
                                           class="btn btn-outline-primary mt-2"><i
                                            class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
                                        <a href="{% url 'admin-size-product-map-delete' x.size_p_map_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 sizeProductMap_show.has_previous %}
                                <li class="page-item"><a class="page-link"
                                                         href="?page={{sizeProductMap_show.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.next_page_number}}">
                                    Next </a>
                                </li>
                                {% endif %}
                            </ul>
                        </div>
                    </div>
                    <!-- /.card -->
                </div>
            </div>
            {% endif %}
            {% if sizeProductMap_edit %}
            <form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
                {% csrf_token %}
                {{form.size_id}}
                {{form.prod_id}}
            </form>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

如果有可能减少代码行数,请也提供帮助.预先感谢.

And if it is possible to reduce the number of line of code please also help. Thanks in advance.

推荐答案

我找到了答案.我确实犯了一个愚蠢的错误.

I've found out the answer. There was a really a silly mistake by me.

sizeProductMap.html 中有一个错误让我指出:

In the sizeProductMap.html there is a mistake let me point out that:

sizeProductMap.html

 {% if sizeProductMap_edit %}
            <form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
                {% csrf_token %}
                {{form.size_id}}
                {{form.prod_id}}
            </form>
            {% endif %}

在这里,我正在检查实例 {%,如果sizeProductMap_edit%} ,这是错误的事情.我必须根据我的 views.py 检查 {%,如果实例为%} .

Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing. I have to check {% if instance %} according to my views.py.

这篇关于我想使用Django表单编辑SizeProductMapping模型,但该表单未呈现-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆