I want to edit SizeProductMapping model using Django forms but The form is not rendering - Django

断了今生、忘了曾经 提交于 2021-01-29 19:51:06

问题


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.

My models are as shown below.

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

This is my urls.

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"),
]

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.


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/65839565/i-want-to-edit-sizeproductmapping-model-using-django-forms-but-the-form-is-not-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!