Django form is not submitted to the database - python

I am writing a Django website for dentists, the dentist can register patients with form easily not an issue, however when registering visits for a patient it is not saved, in the admin panel both models works just fine, on the website the visits form dose not save to database.
models.py
from django.db import models
class Paitent(models.Model):
pname = models.CharField(max_length=50)
age = models.IntegerField()
gender = models.CharField(max_length=50)
address = models.CharField(max_length=50)
telephone = models.IntegerField()
mHistory = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.pname
class Visit(models.Model):
paitent = models.ForeignKey(Paitent,null=True ,on_delete=models.CASCADE, blank=True)
toothNumber = models.CharField('involved tooth', max_length=120)
cComplaint = models.CharField('chief complaint',max_length=120)
sASymptoms = models.CharField('signs and symptoms',max_length=120)
diagnosis = models.CharField(max_length=120)
procedure = models.CharField(max_length=120)
notes = models.TextField(blank=True)
currentVisit = models.DateTimeField(
'time and date of current visit', null=True)
nextAppointment = models.DateTimeField()
def __str__(self):
return self.toothNumber
forms.py
from django import forms
from .models import Paitent
from .models import Visit
class PaitentForm(forms.ModelForm):
class Meta:
model = Paitent
fields = ['pname', 'age', 'gender', 'address', 'telephone']
class VisitForm(forms.ModelForm):
class Meta:
model = Visit
fields = ['paitent', 'toothNumber', 'cComplaint',
'sASymptoms', 'diagnosis', 'procedure',
'notes', 'currentVisit', 'nextAppointment']
views.py
from django.shortcuts import render
from .models import Paitent
from .models import Visit
from .forms import PaitentForm
from .forms import VisitForm
import calendar
from calendar import HTMLCalendar
def homePage(request):
all_paitents = Paitent.objects.all
return render (request, 'homePage.html',{'all':all_paitents})
def newpaitent(request):
if request.method == 'POST':
form = PaitentForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'newpaitent.html', {})
else:
return render(request, 'newpaitent.html', {})
def addVisit(request):
if request.method == 'POST':
form = VisitForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'addVisit.html', {})
else:
return render(request, 'addVisit.html', {})
template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="../static/css/addVisit.css">
<link href="//db.onlinewebfonts.com/c/e662339992c4abf5b43f537391bd3169?
family=Candara" rel="stylesheet"
type="text/css" />
<title>Add Visit</title>
</head>
<body>
<!-- Title navbar -->
<div class="titleContainer">
<h1> Clinic Name </h1>
<h2> Dental Clinic. </h2>
</div>
<!-- Drop down menu -->
<div class="drop_down_menu hidden buttons_container">
<p id="add_appointment"> Home </p>
<hr id="hr_line">
<p id="calender"> Calender </p>
</div>
<!-- Form -->
<h4 class="h4_text"> Add Current Visit : </h4>
<form class="form_container" method="POST" action="{% url 'addVisit'
%}">
{% csrf_token %}
{{form.as_p}}
<div class="form-group">
<input class="form-control" name="paitent">
</div>
<label> Involved Tooth :</label>
<div class="chart_container form-group">
<div class="chart_item upper_right_quardent">
<option onclick="toothNumber('UR8')">8</option>
<option onclick="toothNumber('UR7')">7</option>
<option onclick="toothNumber('UR6')">6</option>
<option onclick="toothNumber('UR5')">5</option>
<option onclick="toothNumber('UR4')">4</option>
<option onclick="toothNumber('UR3')">3</option>
<option onclick="toothNumber('UR2')">2</option>
<option onclick="toothNumber('UR1')">1</option>
</div>
<div class="chart_item upper_left_quardent">
<option onclick="toothNumber('UL1')">1</option>
<option onclick="toothNumber('UL2')">2</option>
<option onclick="toothNumber('UL3')">3</option>
<option onclick="toothNumber('UL4')">4</option>
<option onclick="toothNumber('UL5')">5</option>
<option onclick="toothNumber('UL6')">6</option>
<option onclick="toothNumber('UL7')">7</option>
<option onclick="toothNumber('UL8')">8</option>
</div>
</div>
<div class="chart_line hidden"> </div>
<div class="chart_line vertical_line hidden"> </div>
<div class="chart_container">
<div class="chart_item lower_right_quardent">
<option onclick="toothNumber('LR8')">8</option>
<option onclick="toothNumber('LR7')">7</option>
<option onclick="toothNumber('LR6')">6</option>
<option onclick="toothNumber('LR5')">5</option>
<option onclick="toothNumber('LR4')">4</option>
<option onclick="toothNumber('LR3')">3</option>
<option onclick="toothNumber('LR2')">2</option>
<option onclick="toothNumber('LR1')">1</option>
</div>
<div class="chart_item lower_left_quardent">
<option onclick="toothNumber('LL1')">1</option>
<option onclick="toothNumber('LL2')">2</option>
<option onclick="toothNumber('LL3')">3</option>
<option onclick="toothNumber('LL4')">4</option>
<option onclick="toothNumber('LL5')">5</option>
<option onclick="toothNumber('LL6')">6</option>
<option onclick="toothNumber('LL7')">7</option>
<option onclick="toothNumber('LL8')">8</option>
</div>
<div class="form-group">
<input type="text" class="form-control" id="toothNumber" name="toothNumber" placeholder="Tooth Number">
</div>
</div>
<div class="non-chart">
<div class="form-group">
<input type="text" class="form-control" id="ccomplain" name="cComplaint" placeholder="Chief Complaint">
</div>
<div class="form-group">
<input type="dropdown" class="form-control" id="sasymptoms" name="sASymptoms" placeholder="Signs and Symptoms">
</div>
<div class="form-group">
<input class="form-control" list="diagnosis" name="diagnosis" placeholder="Diagnosis" />
<datalist id="diagnosis">
<option value="Bad Oral Hygien"></option>
<option value="Gingivitis"></option>
<option value="Periodentits"></option>
<option value="dental Stain"></option>
<option value="dental and Gingival Stain"></option>
<option value="Mobility"></option>
<option value="Superficial Caires"></option>
<option value="Deep Caires"></option>
<option value="Reversible Pulpitis"></option>
<option value="Irreversible Pulpitis"></option>
<option value="Necrotic"></option>
<option value="Retained Root"></option>
</datalist>
</div>
<div class="form-group">
<input class="form-control" list="procedure" name="procedure" placeholder="Procedure" required />
<datalist id="procedure">
<option value="Treatment"></option>
<option value="Scalling and Polishing"></option>
<option value="Deep Scalling and polishing"></option>
<option value="Whitening"></option>
<option value="Direct Pulp Capping"></option>
<option value="Indirect Pulp Capping"></option>
<option value="Amlgam Filling"></option>
<option value="Composite Filling"></option>
<option value="Build Up"></option>
<option value="RCT"></option>
<option value="Crown Preparation"></option>
<option value="Extraction"></option>
</datalist>
</div>
<div class="form-group">
<input class="form-control notes" name="notes" placeholder="Notes"/>
</div>
</div>
<label class="appointment_label"> Current Visit Date :</label>
<div class="form-group appointment">
<input type="datetime-local" class="form-control" id="current_visit" name="currentVisit" required>
</div>
<label class="appointment_label"> Next Appointment :</label>
<div class="form-group appointment">
<input type="datetime-local" class="form-control"
id="appointment"
name="nextAppointment">
</div>
<div class="bottom_button_cotainer">
<a href="javascript:history.back() " class="btn btn-danger button">
cancel </a>
<button type="submit" class="btn btn-primary form-group button">
Submit </button>
</div>
</form>
<script>
function toothNumber(string) {
document.getElementById("toothNumber").value = string;
}
</script>
</body>
</html>
urls:
from django.urls import path
from . import views
urlpatterns = [
path('', views.homePage, name='homePage'),
path('newpaitent', views.newpaitent, name='newpaitent'),
path('calendar', views.calendar, name='calendar'),
path('paitentInfo', views.paitentInfo, name='paitentInfo'),
path('addVisit', views.addVisit, name='addVisit'),
path('paitentInfoSearched', views.paitentInfoSearched,
name='paitentInfoSearched'),
path('visits', views.visits, name='visits')
thank you in advance

If the form is not valid, it wont be committed to database.
Print the form errors, this should help you understand why the form is not getting saved
if form.is_valid():
form.save()
else:
print(form.errors)

I think you didn't provide context in view:
Instead of this:
def addVisit(request):
if request.method == 'POST':
form = VisitForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'addVisit.html', {})
else:
return render(request, 'addVisit.html', {})
try this:
def addvisit(request):
if request.method == 'POST':
form = VisitForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect("/") #Add your project route here where you want to go after adding visitors
except:
pass
else:
form = VisitForm()
return render(request, 'addvisit.html', {'form':form})

Related

Why can't I filter the data by one known in django&

I have a painted filter in view.py which works wonderfully. When I use a common abbreviation in html code, like {{form.as_p}} or {{form|crispy}}, then I can find the data I need, according to one known one. In my case, this is by course, by semester, by type of subject, by institute, and so on, and when I start writing my html code, in order for the search to give the correct answer, all fields must be filled in, although in forms and models I determined that all fields are not required, it turns out that an error in the html code, but I do not know where(
veiws.py:
def buy_files(request):
bdfiles = FeedFile.objects.all()
# bdfiles = UploadFile.objects.all()
form = FileFilterForm(request.GET)
if form.is_valid():
if form.cleaned_data["number_course"]:
bdfiles = bdfiles.filter(feed__number_course = form.cleaned_data["number_course"])
if form.cleaned_data["number_semestr"]:
bdfiles = bdfiles.filter(feed__number_semestr = form.cleaned_data["number_semestr"])
if form.cleaned_data["subjectt"]:
bdfiles = bdfiles.filter(feed__subjectt = form.cleaned_data["subjectt"])
if form.cleaned_data["type_materials"]:
bdfiles = bdfiles.filter(feed__type_materials = form.cleaned_data["type_materials"])
if form.cleaned_data["institute"]:
bdfiles = bdfiles.filter(feed__institute = form.cleaned_data["institute"])
return render(request, 'chat/files/buyfile.html', {'bdfiles': bdfiles, 'form':form})
html code:
<div style="float: right; margin-bottom: 10%; margin-top: 10%;" class="form-group row" data-aos="fade-up">
<form action="" method="get" style="width:90%">
{% csrf_token %}
<!-- {{form|crispy}}-->
<p><label class="form-label">Курс: </label> {{ form.number_course }}</p>
<div class="form-error">{{ form.number_course.errors }}</div>
<p><label class="form-label">Семестр: </label> {{ form.number_semestr }}</p>
<div class="form-error">{{ form.number_semestr.errors }}</div>
<p><label class="form-label">Дисциплина </label> {{ form.subjectt }}</p>
<div class="form-error">{{ form.subjectt.errors }}</div>
<p><select name = "type_materials" class="form-select" aria-label="Тип материала">
<option selected>Тип материала</option>
<option value="Практические работы">Практические работы</option>
<option value="Лабораторные работы">Лабораторные работы</option>
<option value="Курсовые">Курсовые</option>
<option value="Дипломная работа">Дипломная работа</option>
<option value="Лекции">Лекции</option>
<option value="Диск с работами">Диск с работами</option>
<option value="Другое">Другое</option>
</select></p>
<p><select name = "institute" class="form-select" aria-label="Институт">
<option selected>Институт</option>
<option value="ИВТИ">ИВТИ</option>
<option value="ГПИ">ГПИ</option>
<option value="ИЭЭ">ИЭЭ</option>
<option value="ИГВИЭ">ИГВИЭ</option>
<option value="ИнЭИ">ИнЭИ</option>
<option value="ИРЭ">ИРЭ</option>
<option value="ИЭТЭ">ИЭТЭ</option>
<option value="ИТАЭ">ИТАЭ</option>
<option value="ИЭВТ">ИЭВТ</option>
<option value="ЭнМИ">ЭнМИ</option>
<option value="Другой">Другой</option>
</select></p>
<div class="form-error">{{ form.institute.errors }}</div>
<button type="submit" class="btn btn-primary">Найти</button>
</form>
forms.py
class FileFilterForm(forms.Form):
number_course = forms.IntegerField(label='Курс',required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}))
number_semestr = forms.IntegerField(label='Семестр',required=False, widget=forms.NumberInput(attrs={'class': 'form-control'}))
subjectt = forms.CharField(label='Дисциплина',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))
type_materials = forms.CharField(label='Тип материала',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))
institute = forms.CharField(label='Институт',required=False,widget=forms.TextInput(attrs={'class': 'form-control'}))
When you generate a form by something like {{form.as_p}}, all the fields are generated and submitted, even if some of the values associated with them are empty because no choice is made by the user.
When you write out only a few fields, the missing fields aren't submitted at all.
That means, in your views.py, when you refer to them by
form.cleaned_data["number_course"]
you might get an invalid key error, as no data by that name was submitted.
To fix, you can use
form.cleaned_data.get('number_course')
...which should return None if there is no such key, rather than erroring out

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

How to use 3 seperate filters on 1 page?

I have a page on which are 3 separate forms.
With form 1 I can filter on name (typed in by user) with form method Post
With form 2 I can filter on level (from list) with form method Get
With form 3 I want to filter on school (from list) also with form method Get
<!-- ### Filters ### -->
<form method="POST" action="{% url 'spells' %}">
{% csrf_token %}
<h1>Filter Options</h1>
<div class="container ftable">
<div class="row">
<div class="input-group ml-5 col-md-4">
<label for="filter-search-name" class="form-labelz"><strong>Spell Name: </strong></label>
<input class="form-control py-2 border-right-0 border" type="search" name="filter-search-name" id="filter-search-name" value autocomplete="off"
placeholder="Give Spell Name or leave blank for all spells" spellcheck="false">
</div>
<div class="col-12">
<button type="submit" class="btn btn-secondary">Filter</button>
</div>
</div>
</div>
</form>
<form method="GET" action="{% url 'spells' %}">
<div class="container ftable">
<div class="input-group ml-5 mt-5 col-md-4">
<label for="filter-search-level" class="form-label"><strong>Spell Level: </strong></label>
<select id="filter-search-level" name="filter-search-level" class="form-select">
<option selected value='Cantrip'>Cantrip</option>
<option value='1st'>1st</option>
<option value='2nd'>2nd</option>
<option value='3rd'>3rd</option>
<option value='4th'>4th</option>
<option value='5th'>5th</option>
<option value='6th'>6th</option>
<option value='7th'>7th</option>
<option value='8th'>8th</option>
<option value='9th'>9th</option>
</select>
<div class="col-12">
<button type="submit" class="btn btn-secondary">Filter</button>
</div>
</div>
</div>
</form>
<form method="GET" action="{% url 'spells' %}">
<div class="container ftable">
<div class=" input-group ml-5 mt-5 col-md-4">
<label for="filter-search-school" class="form-label"><strong>Spell School: </strong></label>
<select id="filter-search-school" name="filter-search-school" class="form-select">
<option selected value='Abjuration'>Abjuration</option>
<option value= 'Conjuration'>Conjuration</option>
<option value= 'Divination'>Divination</option>
<option value= 'Enchantment'>Enchantment</option>
<option value= 'Evocation'>Evocation</option>
<option value= 'Illusion'>Illusion</option>
<option value= 'Necromancy'>Necromancy</option>
<option value= 'Transmutation'>Transmutation</option>
</select>
<div class="col-12">
<button type="submit" class="btn btn-secondary">Filter</button>
</div>
</div>
</div>
</form>
<!-- ### END Filters ### -->
Currently form 1 and 2 work, giving a filtered list a little lower on the same page.
form 3 is working too (the right choice is visible behind the URL) but the filtered list stays empty.
part of views.py:
def spells(request):
if request.method == "POST":
spellz = request.POST.get('filter-search-name')
spells = Underdark_Spells.objects.filter(Q(spell_name__icontains=spellz)).order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
elif request.method == "GET":
level = request.GET.get('filter-search-level')
spells = Underdark_Spells.objects.filter(Q(spell_level=level)).order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
elif request.method == "GET":
school = request.GET.get('filter-search-school')
spells = Underdark_Spells.objects.filter(Q(spell_school=school)).order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
else:
spells = Underdark_Spells.objects.all().order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
def __str__(self):
return self.name
I think the problem is with the way I set it up with if and elif
It looks like this way I can not use request method twice in the same if statement.
If I comment out form 2 code in views.py then form 3 works like a charm.
Is there a way to make it work like this or do i have to create a seperate def for each GET?
You can not have identical conditions in two different if/elif blocks.
Instead you can do this as below:
...
elif request.method == "GET":
if request.GET.get('filter-search-level'):
level = request.GET.get('filter-search-level')
spells = Underdark_Spells.objects.filter(Q(spell_level=level)).order_by('spell_name')
elif request.GET.get('filter-search-school'):
school = request.GET.get('filter-search-school')
spells = Underdark_Spells.objects.filter(Q(spell_school=school)).order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
You should add a check to see if the item is in the querystring, so:
def spells(request):
if request.method == 'POST' and 'filter-search-name' in request.POST:
spellz = request.POST.get('filter-search-name')
spells = Underdark_Spells.objects.filter(Q(spell_name__icontains=spellz))
elif request.method == 'GET' and 'filter-search-level' in request.POST:
level = request.GET.get('filter-search-level')
spells = Underdark_Spells.objects.filter(Q(spell_level=level))
elif request.method == 'GET' and 'filter-search-school' in request.POST:
school = request.GET.get('filter-search-school')
spells = Underdark_Spells.objects.filter(Q(spell_school=school))
else:
spells = Underdark_Spells.objects.all()
spells = spells.order_by('spell_name')
return render(request, 'spells.html', {'spells': spells})
That being said, the code looks quite "ugly" with a lot of duplicated code. It is also strange to make use of a GET or POST request to search for data. Typically a GET request is used to filter data, a POST request is used to update entities. By using three different forms, you also make it impossible to simply select a level and a school for example to apply two filters.
I would advise to make use of one form where you have multiple items, and make use of django-filter [GitHub] or at least of Django forms [Django-doc] to remove boilerplate code.

Django Forms posting not working - Django simply renders the page again

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

MultiSelect field in Django 2 is not working

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!

Categories