Home > Software engineering >  I'm not getting any option to select product list in order form
I'm not getting any option to select product list in order form

Time:07-17

I'm not getting any option to select product list in order formenter image description hereModels.py from django.db import models from re import I from django.utils import timezone from django.dispatch import receiver from more_itertools import quantify from django.db.models import Sum

# Create your models here.

CHOICES = (
    ("1", "Available"),
    ("2", "Not Available")
)

class Brand(models.Model):
    name = models.CharField(max_length=255)
    status = models.CharField(max_length=10, choices=CHOICES)

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=255)
    status = models.CharField(max_length=10, choices=CHOICES)

    def __str__(self):
        return self.name

class Product(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    name = models.CharField(max_length=255)
    code = models.CharField(max_length=10)
    #image = models.ImageField(upload_to="media/product/images/")
    quantity = models.IntegerField()
    rate = models.FloatField(max_length=100)
    status = models.CharField(max_length=10, choices=CHOICES)

    def __str__(self):
        return self.name

class Order(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    sub_total = models.FloatField(max_length=100)
    vat = models.FloatField(max_length=100)
    total_amount = models.FloatField(max_length=100)
    discount = models.FloatField(max_length=100)
    grand_total = models.FloatField(max_length=100)
    paid = models.FloatField(max_length=100)
    due = models.FloatField(max_length=100)
    payment_type = models.CharField(max_length=100)
    payment_status = models.IntegerField()
    status = models.IntegerField()

class OrderItem(models.Model):
    order_id = models.ForeignKey(Order, on_delete=models.CASCADE)
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)

    quantity = models.IntegerField()
    rate = models.FloatField(max_length=100)
    total = models.FloatField(max_length=100)
    status = models.IntegerField()

views.py

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Brand, Category, Product, Order, OrderItem


# Create your views here.

@login_required(login_url="/account/signin/")
def index(request):
    return render(request, "index.html", {})


def signup(request):
    if request.method == "POST":
        if request.POST.get("pwd1") == request.POST.get("pwd2"):
            print(request.POST.get("pwd1"))
            user = User.objects.create(
                username=request.POST.get("username")
            )
            user.set_password(request.POST.get("pwd1"))
            user.save()
            return redirect("/account/signin/")
        else:
            return redirect("/account/signup/")
    return render(request, "signup.html", {})


def signin(request):
    if request.method == "POST":
        pass
        user = authenticate(request, username=request.POST.get("username"), password=request.POST.get("password"))
        if user:
            login(request, user)
            return redirect("/dashboard/")
        else:
            messages.error(request, "Username or password error!")
            return redirect("/account/signin/")
    return render(request, "login.html", {})


def logout_view(request):
    logout(request)
    return redirect("/account/signin/")


@login_required(login_url="/account/signin/")
def dashboard(request):
    return render(request, "dashboard.html", {})

@csrf_exempt
@login_required(login_url="/account/signin/")
def products(request):
    return render(request, "product.html", {})

@login_required(login_url="/account/signin/")
def categories(request):
    return render(request, "categories.html", {})

def categories_list(request):
    categories_lists = Category.objects.all()
    html = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
    return JsonResponse({"message": "Ok", "html": html})

@csrf_exempt
def create_product(request):
    data = dict()
    if request.method == "GET":
        categories_lists = Category.objects.all()
        brands_lists = Brand.objects.all()
        data['html'] = render_to_string('modules/add_product.html', {"categories": categories_lists, "brands": brands_lists})
    else:
        print(request.FILES)
        Product.objects.create(
            name=request.POST["name"],
            brand=Brand.objects.get(id=request.POST["brand"]),
            category=Category.objects.get(id=request.POST["category"]),
            code=request.POST["code"],
            quantity=request.POST["quantity"],
            rate=request.POST["rate"],
            status=request.POST["status"],
        )
        products_lists = Product.objects.all()
        data['html'] = render_to_string('modules/tables_products.html', {"products": products_lists})
    return JsonResponse(data)

@csrf_exempt
def products_list(request):
    products_lists = Product.objects.all()
    html = render_to_string('modules/tables_products.html', {"products": products_lists})
    return JsonResponse({"message": "Ok", "html": html})

@login_required(login_url="/account/signin/")
def orders(request):
    return render(request, "orders.html", {})


@login_required(login_url="/account/signin/")
def report(request):
    return render(request, "report.html", {})

@csrf_exempt
def create_brand(request):
    data = dict()
    brand_name = request.POST.get("brandName")
    brand_status = request.POST.get("brandStatus")
    Brand.objects.create(name=brand_name, status=brand_status)
    brands_list = Brand.objects.all()
    data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})
    return JsonResponse(data)

@csrf_exempt
def create_categories(request):
    data = dict()
    category_name = request.POST.get("categoryName")
    category_status = request.POST.get("categoryStatus")
    Category.objects.create(name=category_name, status=category_status)
    categories_lists = Category.objects.all()
    data['html'] = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
    return JsonResponse(data)

@csrf_exempt
def remove_categories(request, id):
    data = dict()
    category = Category.objects.get(id=id)
    category.delete()
    categories_lists = Brand.objects.all()
    data['html'] = render_to_string('modules/tables_categories.html', {"categories": categories_lists})
    return JsonResponse(data)

@csrf_exempt
def edit_brand(request, id):
    data = dict()
    brand_name = Brand.objects.get(id=id)
    if request.method == "GET":
        data['html'] = render_to_string('modules/edit.html', {"brand": brand_name})
    else:
        brand_name.name = request.POST["brandName"]
        brand_name.status = request.POST["brandStatus"]
        brand_name.save()
        brands_list = Brand.objects.all()
        data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})
    return JsonResponse(data)

@csrf_exempt
def remove_brand(request, id):
    data = dict()
    brand = Brand.objects.get(id=id)
    brand.delete()
    brands_list = Brand.objects.all()
    data['html'] = render_to_string('modules/tables.html', {"brands": brands_list})

    return JsonResponse(data)

@login_required(login_url="/account/signin/")
def brand_list(request):
    brands_list = Brand.objects.all()
    html = render_to_string('modules/tables.html', {"brands": brands_list})
    return JsonResponse({"message": "Ok", "html": html})

@csrf_exempt
@login_required(login_url="/account/signin/")
def brands(request):
    return render(request, "brand.html", {})

@csrf_exempt
@login_required
def invoices(request):
    invoice = Order.objects.all()
    

    return render(request, 'report.html', {})

@login_required
def delete_invoice(request):
    resp = {'status':'failed', 'msg':''}

    if request.method == 'POST':
        try:
            invoice = Order.objects.get(id = request.POST['id'])
            invoice.delete()
            messages.success(request, 'Invoice has been deleted successfully')
            resp['status'] = 'success'
        except Exception as err:
            resp['msg'] = 'Invoice has failed to delete'
            print(err)

    else:
        resp['msg'] = 'Invoice has failed to delete'
    
    return HttpResponse(json.dumps(resp), content_type="application/json")

order.html If I select the product in this order form, the product list should appear. But the list does not appear. {% extends 'modules/base.html' %} {% load static %}

{% block content %}
    <div >
        <div >
            <div >
                <div >
                    <p><a href="{% url 'index' %}">Home</a> / Orders </p>
                </div>
                <div >
                    <div >
                        <h3 >Manage Orders</h3>
                    </div>
                    <div >
                        <form  method="post" action="" id="createOrderForm">

                            <div >
                                <label for="orderDate" >Order Date</label>
                                <div >
                                    <input type="text"  id="orderDate" name="orderDate"
                                           autocomplete="off"/>
                                </div>
                            </div> <!--/form-group-->


                            <div >
                                <label for="clientName" >Client Name</label>
                                <div >
                                    <input type="text"  id="clientName" name="clientName"
                                           placeholder="Client Name" autocomplete="off"/>
                                </div>
                            </div> <!--/form-group-->
                            <div >
                                <label for="clientContact" >Client Contact</label>
                                <div >
                                    <input type="text"  id="clientContact" name="clientContact"
                                           placeholder="Contact Number" autocomplete="off"/>
                                </div>
                            </div>

                            <table  id="productTable">
                                <thead>
                                    <tr>
                                        <th width="30%">Product</th>
                                        <th width>Rate</th>
                                        <th width="15%">Quantity</th>
                                        <th width="20%">Total</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr id="" >
                                        <td>
                                            <div >

                                                <select  name="productName[]"
                                                        id="productName<?php echo $x; ?>"
                                                        onchange="">
                                                    <option value="">SELECT</option>
                                                </select>
                                            </div>
                                        </td>
                                        <td>
                                            <input type="text" name="rate[]" id="rate<?php echo $x; ?>"
                                                   autocomplete="off"
                                                   disabled="true" />
                                            <input type="hidden" name="rateValue[]" id="rateValue<?php echo $x; ?>"
                                                   autocomplete="off" />
                                        </td>
                                        <td>
                                            <div >
                                                <input type="number" name="quantity[]" id="quantity<?php echo $x; ?>"
                                                       onkeyup="" autocomplete="off"
                                                        min="1"/>
                                            </div>
                                        </td>
                                        <td>
                                            <input type="text" name="total[]" id="total<?php echo $x; ?>"
                                                   autocomplete="off"
                                                    disabled="true"/>
                                            <input type="hidden" name="totalValue[]" id="totalValue<?php echo $x; ?>"
                                                   autocomplete="off" />
                                        </td>
                                        <td>

                                            <button  type="button"
                                                    id="removeProductRowBtn" onclick="">
                                                <i  aria-hidden="true"></i></button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>


                            <div >
                                <div >
                                    <div >
                                        <div >
                                            <label for="subTotal" >Sub Amount</label>
                                            <div >
                                                <input type="text"  id="subTotal" name="subTotal"
                                                       disabled="true"/>
                                                <input type="hidden"  id="subTotalValue"
                                                       name="subTotalValue"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="vat" >VAT 13%</label>
                                            <div >
                                                <input type="text"  id="vat" name="vat"
                                                       disabled="true"/>
                                                <input type="hidden"  id="vatValue"
                                                       name="vatValue"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="totalAmount" >Total Amount</label>
                                            <div >
                                                <input type="text"  id="totalAmount"
                                                       name="totalAmount" disabled="true"/>
                                                <input type="hidden"  id="totalAmountValue"
                                                       name="totalAmountValue"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="discount" >Discount</label>
                                            <div >
                                                <input type="text"  id="discount" name="discount"
                                                       onkeyup="discountFunc()" autocomplete="off"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="grandTotal" >Grand Total</label>
                                            <div >
                                                <input type="text"  id="grandTotal"
                                                       name="grandTotal" disabled="true"/>
                                                <input type="hidden"  id="grandTotalValue"
                                                       name="grandTotalValue"/>
                                            </div>
                                        </div> <!--/form-group-->
                                    </div>
                                    <div >
                                        <div >
                                            <label for="paid" >Paid Amount</label>
                                            <div >
                                                <input type="text"  id="paid" name="paid"
                                                       autocomplete="off" onkeyup="paidAmount()"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="due" >Due Amount</label>
                                            <div >
                                                <input type="text"  id="due" name="due"
                                                       disabled="true"/>
                                                <input type="hidden"  id="dueValue"
                                                       name="dueValue"/>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="clientContact" >Payment
                                                                                                      Type</label>
                                            <div >
                                                <select  name="paymentType" id="paymentType">
                                                    <option value="">SELECT</option>
                                                    <option value="1">Cheque</option>
                                                    <option value="2">Cash</option>
                                                    <option value="3">Credit Card</option>
                                                </select>
                                            </div>
                                        </div> <!--/form-group-->
                                        <div >
                                            <label for="clientContact" >Payment
                                                                                                      Status</label>
                                            <div >
                                                <select  name="paymentStatus" id="paymentStatus">
                                                    <option value="">SELECT</option>
                                                    <option value="1">Full Payment</option>
                                                    <option value="2">Advance Payment</option>
                                                    <option value="3">No Payment</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div  style="margin-top: 50px">
                                            <div >
                                                <button type="button"  onclick="addRow()"
                                                        id="addRowBtn" data-loading-text="Loading..."><i
                                                        ></i> Add Row
                                                </button>

                                                <button type="submit" id="createOrderBtn" data-loading-text="Loading..."
                                                        ><i
                                                        ></i> Save Changes
                                                </button>

                                                <button type="reset"  onclick="resetOrderForm()">
                                                    <i ></i> Reset
                                                </button>
                                            </div>
                                        </div>

                                    </div>
                                </div>
                            </div>

                        </form>

                    </div>
                    <!--/card-block-->
                </div>
            </div>
        </div>


    </div>
{% endblock %}

{% block script %}
    <script src="{% static 'js/order.js' %}"></script>
{% endblock %}

CodePudding user response:

Not getting your quetion perfectly But you will get Idea By below code:

<select id=""  name="">
    {% for i in Product %}
    <option value="{{ i.name }}">
        {{i.name }}
    </option>
    {% endfor %}
</select>

Basically you need to use jinja html and loop with the data/model(here Product) which is given from view.py(function) and then you can access each column of model(here name).

CodePudding user response:

To do this you should create a serialiser and pass that as part of the context to the frontend and loop through that.

visit this link to see how t make a serializer docs

After you have created your serializer and lets say you named it ProductSerializer, you then add the below line to the place that passes data to that order page screen in the frontend. The below line serializes your raw queryset and passes it to your frontend to be consumable.

products = Product.objects.all()
products = ProductSerializer(cart, many=True)
context = {"products": products}

Then in your frontend you can access this and loop through like so:

<select id=""  name="">
  {% for product in products %}
  <option value="{{ product.name }}">
      {{product.name }}
  </option>
  {% endfor %}
</select>
  • Related