I need to make it so that the select from the form is displayed in the database, None appears in its place in the database
everything is added except categories and stocks
I was told that I need to add value to option, but nothing happened
what's wrong
Here is my views.py :
def create_product(request):
user = request.user
category = user.category_set.all()
stock = user.stock_set.all()
if request.method == 'POST':
product = Product()
product.title = request.POST.get('title')
product.categories = user.category_set.get(id=request.POST.get('categories'))
product.price = request.POST.get('price')
product.user = request.POST.get('user')
product.amount = request.POST.get('amount')
product.stock = Stock.objects.get(id=request.POST.get('stock'))
product.user = request.user
product.save()
return redirect('index')
return render(request, 'main/create.html', {'category':category,'stocks':stock})
Here is my models.py :
class Product(models.Model):
title = models.CharField(verbose_name="Название товара", max_length=250)
categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
price = models.IntegerField(verbose_name="Цена")
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products')
amount = models.CharField(max_length=250,verbose_name='Количество')
user = models.ForeignKey(User, on_delete=models.PROTECT)
stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
def __str__(self):
return self.title
My create template :
<div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);">
<h1 class="display-6">Создайте товар</h1>
<form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;">
{% csrf_token %}
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Название</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Цена</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Цена товара" name="price">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Количество товара</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Кол-во" name="amount">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Категория</label>
<select class="form-select" aria-label="Default select example" name="category">
{% for categories in categories %}
<option value="">{{ categories.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Склад</label>
<select class="form-select" aria-label="Default select example" name="stock">
{% for stocks in stocks %}
<option value="{{ stocks.pk }}" >{{ stocks.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<button class="btn btn-success">Создать</button>
Выйти
</div>
</form>
</div>
Related
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 class="container">
<div class="row vertical">
<div class="col-sm-12">
<div class="breadcrumb">
<p>Home / Orders </p>
</div>
<div class="card card-outline-secondary">
<div class="card-header">
<h3 class="mb-0 text-center">Manage Orders</h3>
</div>
<div class="card-block">
<form class="form form-horizontal" method="post" action="" id="createOrderForm">
<div class="form-group">
<label for="orderDate" class="col-sm-2 control-label">Order Date</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="orderDate" name="orderDate"
autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientName" class="col-sm-2 control-label">Client Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="clientName" name="clientName"
placeholder="Client Name" autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientContact" class="col-sm-2 control-label">Client Contact</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="clientContact" name="clientContact"
placeholder="Contact Number" autocomplete="off"/>
</div>
</div>
<table class="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="" class="">
<td>
<div class="form-group">
<select class="form-control" 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" class="form-control"/>
<input type="hidden" name="rateValue[]" id="rateValue<?php echo $x; ?>"
autocomplete="off" class="form-control"/>
</td>
<td>
<div class="form-group">
<input type="number" name="quantity[]" id="quantity<?php echo $x; ?>"
onkeyup="" autocomplete="off"
class="form-control" min="1"/>
</div>
</td>
<td>
<input type="text" name="total[]" id="total<?php echo $x; ?>"
autocomplete="off"
class="form-control" disabled="true"/>
<input type="hidden" name="totalValue[]" id="totalValue<?php echo $x; ?>"
autocomplete="off" class="form-control"/>
</td>
<td>
<button class="btn btn-default removeProductRowBtn" type="button"
id="removeProductRowBtn" onclick="">
<i class="fa fa-trash" aria-hidden="true"></i></button>
</td>
</tr>
</tbody>
</table>
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="subTotal" class="col-sm-6 control-label">Sub Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="subTotal" name="subTotal"
disabled="true"/>
<input type="hidden" class="form-control" id="subTotalValue"
name="subTotalValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="vat" class="col-sm-6 control-label">VAT 13%</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="vat" name="vat"
disabled="true"/>
<input type="hidden" class="form-control" id="vatValue"
name="vatValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="totalAmount" class="col-sm-6 control-label">Total Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="totalAmount"
name="totalAmount" disabled="true"/>
<input type="hidden" class="form-control" id="totalAmountValue"
name="totalAmountValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="discount" class="col-sm-6 control-label">Discount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="discount" name="discount"
onkeyup="discountFunc()" autocomplete="off"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="grandTotal" class="col-sm-6 control-label">Grand Total</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="grandTotal"
name="grandTotal" disabled="true"/>
<input type="hidden" class="form-control" id="grandTotalValue"
name="grandTotalValue"/>
</div>
</div> <!--/form-group-->
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="paid" class="col-sm-6 control-label">Paid Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="paid" name="paid"
autocomplete="off" onkeyup="paidAmount()"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="due" class="col-sm-6 control-label">Due Amount</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="due" name="due"
disabled="true"/>
<input type="hidden" class="form-control" id="dueValue"
name="dueValue"/>
</div>
</div> <!--/form-group-->
<div class="form-group">
<label for="clientContact" class="col-sm-6 control-label">Payment
Type</label>
<div class="col-sm-9">
<select class="form-control" 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 class="form-group">
<label for="clientContact" class="col-sm-6 control-label">Payment
Status</label>
<div class="col-sm-9">
<select class="form-control" 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 class="form-group submitButtonFooter" style="margin-top: 50px">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" onclick="addRow()"
id="addRowBtn" data-loading-text="Loading..."><i
class="glyphicon glyphicon-plus-sign"></i> Add Row
</button>
<button type="submit" id="createOrderBtn" data-loading-text="Loading..."
class="btn btn-success"><i
class="glyphicon glyphicon-ok-sign"></i> Save Changes
</button>
<button type="reset" class="btn btn-default" onclick="resetOrderForm()">
<i class="glyphicon glyphicon-erase"></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 %}
Not getting your quetion perfectly But you will get Idea By below code:
<select id="" class="" 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).
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="" class="" name="">
{% for product in products %}
<option value="{{ product.name }}">
{{product.name }}
</option>
{% endfor %}
</select>
i'm new trying to learn Django by building my e-commerce website.
In my terminal i'm getting GET and POST, although i specified action to POST
image result in my terminal
this code works great before i add translation to my website, but after adding Internationalization to my project, the form is no longer working(the form is not translated because it is comment section)
models.py:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py:
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
html code:
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
urlpatterns:
path('addcomment/int:id', views.addcomment, name='addcomment'),
admin.py:
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['subject', 'comment', 'status', 'create_at']
list_filter = ['status']
readonly_fields = ('subject', 'comment', 'user', 'product', 'rate', )
thanks
Here is the code in one codeblocks
models.py
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
urlpatterns
urlpatterns = [
path('addcomment/<int:id>', views.addcomment, name='addcomment')]
html
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
Create Forms.py file and add the form fields below with proper indentation like this:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
I have one Boolean model field payment_received which as default value set to False. From the frontend dropdown it as coming as 0 or 1 form.No matter what value from the dropdown I select it is always saved as 1(True) in the table.
I am trying to debug it & I can verify that proper value is coming from the HTML form but after cleaning is done by Django form it is always results in True value.
My Model
class InvoiceHeader(models.Model):
class Meta:
db_table = 'invoice_hdr'
invoice_no = models.CharField(max_length=50)
client = models.ForeignKey(Client, on_delete=models.DO_NOTHING)
campaign = models.ForeignKey(CampaignHeader, on_delete=models.DO_NOTHING, null=True)
invoice_date = models.DateField()
invoice_amount = models.DecimalField(max_digits=11, decimal_places=2)
cgst = models.DecimalField(max_digits=11, decimal_places=2)
sgst = models.DecimalField(max_digits=11, decimal_places=2)
igst = models.DecimalField(max_digits=11, decimal_places=2)
total_amount = models.DecimalField(max_digits=11, decimal_places=2)
payment_received = models.BooleanField(default=False)
def __str__(self):
return self.invoice_no
My Form
class InvoiceHeaderForm(forms.ModelForm):
class Meta:
fields = ('invoice_no','invoice_date','campaign','client', 'invoice_amount','cgst','sgst','igst','total_amount','payment_received')
model = InvoiceHeader
invoice_no = forms.CharField(max_length=50)
invoice_date = forms.DateField()
client = forms.ModelChoiceField(queryset=Client.objects.all())
campaign = forms.ModelChoiceField(queryset=CampaignHeader.objects.all())
invoice_amount = forms.DecimalField(max_digits=11, decimal_places=2)
cgst = forms.DecimalField(max_digits=11, decimal_places=2)
igst = forms.DecimalField(max_digits=11, decimal_places=2)
sgst = forms.DecimalField(max_digits=11, decimal_places=2)
total_amount = forms.DecimalField(max_digits=11, decimal_places=2)
payment_received = forms.BooleanField()
def clean_payment_received(self):
val = self.cleaned_data['payment_received']
print('TEST1', val) #<---- always True
return val
def clean_invoice_no(self):
invoice_no = self.cleaned_data.get('invoice_no')
if InvoiceHeader.objects.filter(invoice_no=invoice_no).exists() and not str(self.instance):
raise forms.ValidationError('Invoice no. already exist!')
return invoice_no
Template
<form action="{{ url }}" method="POST" id="invoice_form">
<input type="hidden" name="edit_mode" value="{% if invoice %}{{'1'}}{% else %}{{'0'}}{% endif %}">
{% csrf_token %}
<div class="card shadow py-2">
<div class="card-body">
<div class="row ">
<div class="col-md-6">
<div class="form-group">
<label for="invoice_no">Invoice No.<sup class="text-danger">*</sup></label>
<input type="text" tabindex="1" class="form-control" id="invoice_no"
name="invoice_no" placeholder="Enter campaign name"
value="{% if invoice %}{{invoice.invoice_no}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="client">Client<sup class="text-danger">*</sup></label>
<select tabindex="3" class="form-control selectpicker" data-live-search="true"
id="client" name="client">
{% for client in clients %}
<option data-state="{{client.state}}" id="client" value="{{ client.id }}"
{% if invoice and invoice.client_id == client.id %}{{'selected'}}{% endif %}>
{{ client }}</option>
{% endfor %}
</select>
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="invoice_amount">Invoice Amount<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="5" class="form-control" id="invoice_amount"
name="invoice_amount" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.invoice_amount}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="igst">IGST<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="7" class="form-control" id="igst"
name="igst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.igst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="payment_received">Payment Received?<sup class="text-danger">*</sup></label>
<select tabindex="9" class="form-control selectpicker" data-live-search="true"
id="payment_received" name="payment_received">
<option value="0" {% if invoice and not invoice.payment_received %}{{'selected'}}{% endif %}>NO</option>
<option value="1" {% if invoice and invoice.payment_received %}{{'selected'}}{% endif %}>YES</option>
</select>
<small class="error-msg form-text text-danger"></small>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="invoice_date">Invoice Date<sup class="text-danger">*</sup></label>
<input type="text" tabindex="2" class="form-control datepicker" id="invoice_date"
name="invoice_date" placeholder="Enter invoice date"
value="{% if invoice %}{{invoice.invoice_date|date:'d/m/Y'}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="campaign">Campaign<sup class="text-danger">*</sup></label>
<select tabindex="4" class="form-control selectpicker" data-live-search="true"
id="campaign" name="campaign">
{% if invoice %}
{% for campaign in campaigns %}
<option value="{{campaign.id}}" {% if campaign == invoice.campaign %}{{'selected'}}{% endif %}>{{campaign}}</option>
{% endfor %}
{% endif %}
</select>
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="cgst">CSGT<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="6" class="form-control" id="cgst"
name="cgst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.cgst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="sgst">SGST<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="8" class="form-control" id="sgst"
name="sgst" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.sgst}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
<div class="form-group">
<label for="total_amount">Total Amount<sup class="text-danger">*</sup></label>
<input type="text" data-type='currency' tabindex="10" class="form-control" id="total_amount" readonly
name="total_amount" placeholder="Enter invoice amount"
value="{% if invoice %}{{invoice.total_amount}}{% endif %}">
<small class="error-msg form-text text-danger"></small>
</div>
</div>
</div>
</div>
</div>
<br>
</form>
Any help would be appreciated....
This might work (in forms.py). Also can you tell which django version you are using?
[...]
payment_received = forms.BooleanField(widget=CheckboxInput(default=False), required=False)
[...]
the 'selected' value of the html template will render the booleanfield to True.
Because usually a booleanfield on html-side is a checkbox, which is True if it is selected.
Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.
See my code below:
models.py
from django.db import models
from accounts.models import User
from datetime import datetime, date
#// ------------ FUNCTIONS -------------//
# Generate Organisation IDs for each organisation
def org_id_generate():
last_org = Organization.objects.all().order_by('org_id').last()
if not last_org:
return 'ORG_001'
else:
last_org_id = last_org.org_id
number_in_id = int(last_org_id[4:7])
new_number_in_id = number_in_id + 1
new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
return new_org_id
#// ------------ MODELS -------------//
class Organization(models.Model):
org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
organization_code = models.CharField(max_length=20)
company_name = models.CharField(verbose_name="Company Name", max_length=60)
legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
industry_education = models.BooleanField(verbose_name="Education", default=False)
industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
industry_retail = models.BooleanField(verbose_name="Retail", default=False)
industry_services = models.BooleanField(verbose_name="Services", default=False)
business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
created_date = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
effective_start_date = models.DateField(auto_now_add=False)
effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
update_date = models.DateTimeField(default=datetime.now)
last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")
def __str__(self):
return self.company_name
forms.py
from django import forms
from organizations.models import Organization
class OrganizationAddForm(forms.ModelForm):
class Meta:
model = Organization
exclude = ['created_date', 'update_date', ]
views.py
from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required
#login_required()
def settings(request):
return render(request, 'settings/settings.html')
#login_required()
def organizations_settings(request):
orgs = Organization.objects.all()
context = {
'orgs': orgs,
}
return render(request, 'settings/settings_organizations.html', context)
#login_required
def organization_add(request):
if request.method == 'POST':
user_email = request.user.email
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['brn']
form.vat_registration_no = form.cleaned_data['vat']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = forms.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
form.created_by = form.cleaned_data[user_email]
form.last_updated_by = form.cleaned_data[user_email]
form.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.settings, name="settings"),
path('organizations/', views.organizations_settings, name='organizations_settings'),
path('organization_create', views.organization_create, name="organization_create"),
path('organizations/add/', views.organization_add, name="organization_add"),
]
Page Source Code
<!-- Add Organization Form -->
<div class="container form-style">
<i class="fas fa-arrow-left"></i> Back
<div class="form-header">
<h3>Add Organization</h3>
</div>
<form action="{% url 'organization_add' %}" method="POST">
{% csrf_token %}
<div class="container">
<!-- Row 1 -->
<div class="row">
<div class="col-md-4">
<label for="organization_code">Organization Code<span class="star-red">*</span></label>
<input type="text" name="organization_code" class="form-control" required>
</div>
<div class="col-md-4">
<label for="company_name">Organization Name<span class="star-red">*</span></label>
<input type="text" name="company_name" class="form-control" required>
</div>
<div class="col-md-4">
<label for="legal_name">Legal Name<span class="star-red">*</span></label>
<input type="text" name="legal_name" class="form-control" required>
</div>
</div>
<!-- Row 2 -->
<div class="row mt-4">
<!-- <div class="col-md-4">
<label for="industry">Industry<span class="star-red">*</span></label>
<select name="industry" class="selectpicker">
<option value="distribution">Distribution</option>
<option value="education">Education</option>
<option value="healthcare">Healthcare</option>
<option value="manufacturing">Manufacturing</option>
<option value="retail">Retail</option>
<option value="services">Services</option>
</select>
</div> -->
<div class="col-md-6">
<label for="brn">Business Registration No.</label>
<input type="text" name="brn" class="form-control">
</div>
<div class="col-md-6">
<label for="vat">VAT Registration No.</label>
<input type="text" name="vat" class="form-control">
</div>
</div>
<!-- Row 3 -->
<h5 class="mt-4">Industry</h5>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_distribution" class="form-check-input">
<label for="industry_distribution" class="form-check-label">Distribution</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_education" class="form-check-input">
<label for="industry_education" class="form-check-label">Education</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_healthcare" class="form-check-input">
<label for="industry_healthcare" class="form-check-label">Healthcare</label>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_manufacturing" class="form-check-input">
<label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_retail" class="form-check-input">
<label for="industry_retail" class="form-check-label">Retail</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_services" class="form-check-input">
<label for="industry_services" class="form-check-label">Services</label>
</div>
</div>
</div>
<!-- Row 4 -->
<div class="row mt-4">
<div class="col-md-6">
<label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
<input type="date" name="effective_start_date" class="form-control" required>
</div>
<div class="col-md-6">
<label for="effective_end_date">Effective End Date:</label>
<input type="date" name="effective_end_date" class="form-control">
</div>
</div>
<!-- Hidden Input - User -->
<input type="hidden" name="user_email" />
<div class="float-right mt-3">
<button type="submit" class="btn btn-custom save">Save and Close</button>
</div>
</div>
</form>
</div>
Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.
I did not find any code to show the errors in html.
According to the function in views, if the form is not valid, then it renders the page with the form.
Try to add {{form.errors}} to you the html file to see if it has errors?
I managed to solve it.
views.py
#login_required
def organization_add(request):
if request.method == 'POST':
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['business_registration_no']
form.vat_registration_no = form.cleaned_data['vat_registration_no']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = form.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
org.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.
This is resolved by using:
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
Note that the following two posts helped me:
Using request.user with Django ModelForm
Cannot assign "42": "Event.user_id" must be a "User" instance
I'm working on a project using Python(3.7) and Django(2) in which I need to create a multi-select field inside one of my form.
Here's what I have tried:
from models.py:
class ExperimentModel(models.Model):
user = models.ForeignKey(User, related_name='experiments',
on_delete=models.CASCADE)
name = models.CharField(max_length=255)
start_date = models.DateField()
change_date = models.DateField()
end_date = models.DateField()
assets = models.CharField(max_length=450, choices=choices)
goals = models.CharField(max_length=255, blank=True)
comments = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now=True)
From forms.py:
class ExperimentForm(forms.ModelForm):
choices = (
('CO2 SCRUBBER', 'CO2 SCRUBBER'),
('CORN OIL', 'CORN OIL'),
('DRYERS', 'DRYERS'),
('ENVIRONMENTAL', 'ENVIRONMENTAL'),
('UTILITIES', 'UTILITIES'),
('LAB', 'LAB'),
('SIEVES', 'SIEVES'),
('GRAINS & MILLING', 'GRAINS & MILLING'),
('SEPARATION', 'SEPARATION'),
('AIR & GAS', 'AIR & GAS'),
('COOK', 'COOK'),
('EVAPORATION', 'EVAPORATION'),
('WATER', 'WATER'),
('STORAGE', 'STORAGE'),
('BOILER', 'BOILER'),
('FERMENTATION', 'FERMENTATION'),
('DISTILLATION', 'DISTILLATION'),
('BUILDING AND FACILITIES', 'BUILDING AND FACILITIES'),
('CHEMICAL', 'CHEMICAL'),
)
assets = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=choices)
class Meta:
model = ExperimentModel
fields = ('user', 'name', 'start_date', 'change_date', 'end_date', 'assets',
'goals', 'comments')
From template.html:
<form method="POST" action="{% url 'new-experiment' %}">
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
{% csrf_token %}
<h2> Create new Experiment:</h2>
{# {{ form|crispy }}#}
<div class="form-group">
<input type="text" name="name" id="name" class="form-control input-lg"
placeholder="experiment name" tabindex="3" required>
</div>
<div class="form-group">
<label for="start_date"> Start Date </label>
<input type="date" name="start_date" id="start_date" class="form-control input-lg"
placeholder="start_date" tabindex="4" required>
</div>
<div class="form-group">
<label for="change_date"> Change Date </label>
<input type="date" name="change_date" id="change_date" class="form-control input-lg"
placeholder="change date" tabindex="4" required>
</div>
<div class="form-group">
<label for="end_date"> End Date </label>
<input type="date" name="end_date" id="end_date" class="form-control input-lg"
placeholder="end date" tabindex="4" required>
</div>
<div class="form-group">
<label for="assets"> Assets </label>
{# <input type="text" name="assets" id="assets" class="form-control input-lg"#}
{# placeholder="Assets" tabindex="3" required>#}
<select name="assets" class="form-control" id="assets" multiple>
<option value="CO2 SCRUBBER">CO2 SCRUBBER</option>
<option value="CORN OIL">CORN OIL</option>
<option value="DRYERS">DRYERS</option>
<option value="ENVIRONMENTAL">ENVIRONMENTAL</option>
<option value="UTILITIES">UTILITIES</option>
<option value="LAB">LAB</option>
<option value="SIEVES">SIEVES</option>
<option value="GRAINS & MILLING">GRAINS & MILLING</option>
<option value="SEPARATION">SEPARATION</option>
<option value="AIR & GAS">AIR & GAS</option>
<option value="COOK">COOK</option>
<option value="EVAPORATION">EVAPORATION</option>
<option value="WATER">WATER</option>
<option value="STORAGE">STORAGE</option>
<option value="BOILER">BOILER</option>
<option value="FERMENTATION">FERMENTATION</option>
<option value="BUILDING AND FACILITIES">BUILDING AND FACILITIES</option>
<option value="CHEMICAL">CHEMICAL</option>
</select>
</div>
<div class="form-group">
<label for="assets"> Goals </label>
<input type="text" name="goals" id="goals" class="form-control input-lg"
placeholder="Goals" tabindex="3" required>
</div>
<div class="form-group">
<label for="comments"> Comments </label>
<textarea name="comments" id="comments" class="form-control input-lg"
rows="5" required>
</textarea>
</div>
<hr class="colorgraph">
<div class="row">
<div class="col-md-12 float-right">
<input type="submit" value="Create" class="btn btn-primary btn-block btn-lg float-right"
tabindex="7" style="background-color: #7386D5; color: white">
</div>
{# <div class="col-xs-12 col-md-6"><a href="{% url 'register' %}"#}
{# class="btn btn-success btn-block btn-lg">Create New Account</a>#}
{# </div>#}
</div>
</form>
And here's the views.py:
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = ExperimentForm(post_data)
print('req submitted')
if form.is_valid():
print('form valid')
form.save(commit=False)
form.user = request.user
form.save()
return HttpResponseRedirect(reverse_lazy('all-experiments'))
else:
return HttpResponseRedirect(reverse_lazy('new-experiment'))
When I select the only one option from multiple assets, the experiment has been created but when select multiple options the request failed, what's can wrong here?
How can I achieve the multi-select functionality for assets for experiment Model?
Also, no error is displaying in the template, even though I have printed the errors in the template, but doesn't any error is displaying on the template.
Thanks in advance!