Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

python - handling different forms post request on single page -Django

I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .

I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.

My code is as:

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

As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.

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

For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.

I want to do all the operations for all the attributes in single html page. Is it possible?

Means according to the atrribut type request the page data should


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.

Let's take an input line:

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

Let's use Django's tags and turn it into this:

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

The class will probably be the same but you could extend the same functionality to the class or type fields.

In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:

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'}  
    ],
]

Then you can do a for loop in the templates:

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

I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...