Unable to Deploy Django in Heroku - python

I am unable to deploy django in Heroku. I think the problem lies with Ajax because all of the pages seems to render in heroku.
Error that I got is:
InvalidCursorName at /incidentReport/general
cursor "_django_curs_140297876031040_sync_1" does not exist
During handling of the above exception (relation "incidentreport_accidentcausation" does not exist LINE 1: ...cidentreport_accidentcausation"."updated_at" FROM "incidentr... ^ ), another exception occurred:
Thank you
HTML
<!-- Page Content -->
<div class="container-fluid">
<!-- Page Title -->
<div class="d-flex bd-highlight">
<div class="pg-title p-2 flex-grow-1 bd-highlight">
<h4>Incident Report</h4>
</div>
</div>
<!-- User Report Table -->
<div class="card shadow mb-5 d-flex ">
<!-- Top Pagination -->
<div class="card-header py-3">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" href="{% url 'incident_report_general' %}">General</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_people' %}">People</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_vehicle' %}">Vehicle</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_media' %}">Media</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'incident_report_remarks' %}">Remarks</a>
</li>
</ul>
</div>
<div class="card-body">
<div class="table-responsive">
<table>
<form id="form_incidentgeneral" action="{% url 'incident_report_general' %}" enctype="multipart/form-data" method="post" data-acc-url="{% url 'ajax_load_accident' %}">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Date</label>
{{user_report_form.date}}
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Time</label>
{{user_report_form.time}}
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputAddress">Street Address</label>
{{user_report_form.location}}
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputWeather">Weather</label>
{{inc_gen_form.weather}}
</div>
<div class="form-group col-md-6">
<label for="inputLight">Light</label>
{{inc_gen_form.light}}
</div>
</div>
<!-- ================================= -->
<hr>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputSeverity">Severity</label>
{{inc_gen_form.severity}}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAccident">Accident Factor</label>
{{inc_gen_form.accident_factor}}
</div>
<div class="form-group col-md-6">
<label for="inputAccident">Accident Factor Sub Category</label>
{{inc_gen_form.accident_subcategory}}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAccident">Collision Type</label>
{{inc_gen_form.collision_type}}
</div>
<div class="form-group col-md-6">
<label for="inputAccident">Collision Sub Category</label>
{{inc_gen_form.collision_subcategory}}
</div>
</div>
<!-- ================================= -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCrashType">Crash Type</label>
{{inc_gen_form.crash_type}}
</div>
<div class="form-group col-md-6">
<label for="inputMovement">Movement Code</label>
{{ inc_gen_form.movement_code }}
</div>
</div>
<!-- ================================= -->
<br>
<div class="modal-footer mb-3">
<input type="button" class="btn btn-secondary" data-dismiss="modal"
value="Clear">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</form>
</table>
</div>
</div>
</div>
<!-- End of User Report Table -->
</div>
<!-- End of Page Content -->
AJAX
<script>
$("#id_accident_factor").change(function () {
const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view
const accidentId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= /persons/ajax/load-cities/ )
data: {
'accident_factor_id': accidentId // add the country id to the GET parameters
},
success: function (data) {
//console.log(data) // `data` is the return of the `load_cities` view function
$("#id_accident_subcategory").html(data); // replace the contents of the city input with the data that came from the server
let html_data = '<option value="">---------</option>';
data.forEach(function (accident_subcategory) {
html_data += `<option value="${accident_subcategory.id}">${accident_subcategory.sub_category}</option>`
});
console.log(html_data);
$("#id_accident_subcategory").html(html_data);
}
});
});
$("#id_collision_type").change(function () {
const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view
const collisionId = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= /persons/ajax/load-cities/ )
data: {
'collision_type_id': collisionId // add the country id to the GET parameters
},
success: function (data) {
//console.log(data) // `data` is the return of the `load_cities` view function
$("#id_collision_subcategory").html(data); // replace the contents of the city input with the data that came from the server
let html_data = '<option value="">---------</option>';
data.forEach(function (collision_subcategory) {
html_data += `<option value="${collision_subcategory.id}">${collision_subcategory.sub_category}</option>`
});
console.log(html_data);
$("#id_collision_subcategory").html(html_data);
}
});
});
</script>
Dropdown HTML
<option value="">---------</option>
{% for accsubcategory in acc_subcat %}
<option value="{{ accsubcategory.pk }}">{{ accsubcategory.sub_category }}</option>
{% endfor %}
{% for colsubcategory in col_subcat %}
<option value="{{ colsubcategory.pk }}">{{ colsubcategory.sub_category }}</option>
{% endfor %}
Views
def incident_report_general(request):
if request.method == 'POST':
user_report_form = UserReportForm(request.POST, request.FILES)
inc_gen_form = IncidentGeneralForm(request.POST, request.FILES)
else:
user_report_form = UserReportForm()
inc_gen_form = IncidentGeneralForm()
context = {
'user_report_form': user_report_form,
'inc_gen_form': inc_gen_form,
}
return render(request, 'pages/incident_report.html', context)
def load_accident(request):
accident_factor_id = request.GET.get('accident_factor_id')
collision_type_id = request.GET.get('collision_type_id')
acc_subcat = AccidentCausationSub.objects.filter(accident_factor_id=accident_factor_id).all()
col_subcat = CollisionTypeSub.objects.filter(collision_type_id=collision_type_id).all()
context = {
'acc_subcat': acc_subcat,
'col_subcat': col_subcat
}
return render(request, 'incident/acc_sub_dropdown_list_options.html', context)
Form
class IncidentGeneralForm(forms.ModelForm):
class Meta:
model = IncidentGeneral
fields = '__all__'
def __init__(self, *args, **kwargs):
super(IncidentGeneralForm, self).__init__(*args, **kwargs)
self.fields['accident_factor'].widget.attrs['class'] = 'form-control'
self.fields['accident_subcategory'].widget.attrs['class'] = 'form-control'
self.fields['collision_type'].widget.attrs['class'] = 'form-control'
self.fields['collision_subcategory'].widget.attrs['class'] = 'form-control'
self.fields['weather'].widget.attrs['class'] = 'form-control'
self.fields['light'].widget.attrs['class'] = 'form-control'
self.fields['severity'].widget.attrs['class'] = 'form-control'
self.fields['crash_type'].widget.attrs['class'] = 'form-control'
self.fields['movement_code'].widget.attrs['class'] = 'form-control'
self.fields['accident_subcategory'].queryset = AccidentCausationSub.objects.none()
self.fields['collision_subcategory'].queryset = CollisionTypeSub.objects.none()
if 'accident_factor' in self.data:
try:
accident_factor_id = int(self.data.get('accident_factor'))
self.fields['accident_subcategory'].queryset = AccidentCausationSub.objects.filter(accident_factor_id=accident_factor_id).order_by('accident_factor')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['accident_subcategory'].queryset = self.instance.accident_factor.accident_subcategory_set.order_by('subcategory')
if 'collision_type' in self.data:
try:
collision_type_id = int(self.data.get('collision_type'))
self.fields['collision_subcategory'].queryset = CollisionTypeSub.objects.filter(collision_type_id=collision_type_id).order_by('collision_type')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['collision_subcategory'].queryset = self.instance.collision_type.collision_subcategory_set.order_by('subcategory')

Related

How to submit input type = range in flask

While trying to submit input type = range i'm getting "Bad request error".
HTML:
{% extends "base.html" %} {% block content %} <head>
<link rel="stylesheet" href="css/style.css" />
</head>
<div class="search-bar">
<div class="rt-container">
<form method="post" action="#">
<div class="col-rt-12">
<div class="Scriptcontent">
<!-- Range Slider HTML -->
<div slider id="slider-distance">
<div>
<div inverse-left style="width: 70%"></div>
<div inverse-right style="width: 70%"></div>
<div range style="left: 30%; right: 40%"></div>
<span thumb style="left: 30%"></span>
<span thumb style="left: 60%"></span>
<div sign style="left: 30%">
<span id="value">0</span>
</div>
<div sign style="left: 60%">
<span id="value">100</span>
</div>
</div>
<input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[1].style.width=value+'%';
children[5].style.left=value+'%';
children[7].style.left=value+'%';children[11].style.left=value+'%';
children[11].childNodes[1].innerHTML=this.value;" />
<input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[3].style.width=(100-value)+'%';
children[5].style.right=(100-value)+'%';
children[9].style.left=value+'%';children[13].style.left=value+'%';
children[13].childNodes[1].innerHTML=this.value;" />
<input id="search" type="submit" value="SEARCH" href="#"></input>
</div>
</form>
</div>
</div>
</div>
<form action="/lobbies" method="POST">
<input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
<input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
<input type="submit" value="CREATE" href="#"></input>
</form>
</div>
<div class="container"> {% for lobby in data%} <div class="lobby-item">
<div class="lobby-coins">
<img src="static/StashedCoins.png" alt="coin" width="32px" height="32px" /> {% print lobby['GameValue']%}
</div>
<div class="lobby-photo">
<a href="/Player/{{lobby['PlayerOneID']}}">
<img src=https://robohash.org/{{lobby['CreatorName']}} alt="coin" width="110px" height="110px" />
</a>
</div>
<div class="lobby-join">
Join
</div>
</div>
{%endfor%}
</div>
{% endblock %}
Flask:
#app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
if "username" in session:
coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
"balance"
]
ProfilePicture = "https://robohash.org/" + str(session["username"])
color = str(session["color"])
PlayerID = session["PlayerID"]
if request.method == "POST":
LobbyValue = request.form['LobbyValue']
if "IsVisible" in request.form:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
else:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
LobbyID = response['LobbyID']
return redirect(url_for('lobby',LobbyID=LobbyID))
data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
return render_template(
"lobbies.html",
coins=coins,
ProfilePicture=ProfilePicture,
color=color,
data=data.json(),
)
else:
return redirect(url_for("login"))
I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:
So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.

display images in select option for selection -Django Python

I am working on a PRoject and I am stuck on order page.
Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working.
I want to show images to user so that user can select one of them.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
class ImageTemplate(models.Model):
temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True)
temp_img = models.ImageField("Template Image", null=False)
class ImageTemplateProductMapping(models.Model):
imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True)
temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE,
verbose_name="Image Template ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form>
<div class="card mx-2 my-2 border border-secondary">
<div class="my-2">
<div class="form-group">
<div class="form-group row mx-2">
<label for="quantity"
class="form-control-label font-weight-bold card-header col-4 ml-4 my-auto"
style="background-color:#e3e4e6"><h5>Quantity : </h5></label>
<input id="quantity" class="form-control col-5 mx-2 my-auto" type="number">
</div>
</div>
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection" value="Upload"/> Upload an
Image
<input type="file" name="file" class='btn btn-outline-secondary type my-2'>
<br>
<input id="Select" type="radio" name="ImageSelection" value="Select"/> Select
From Templates
<!-- Button trigger modal -->
<input type="button" name="url" style='display: none;'
class='btn btn-outline-secondary type my-2'
value="Choose Template" data-toggle="modal"
data-target="#exampleModalLong">
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Select
Template</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="d-flex-row justify-content-center modal-body"
style="background:red;">
<div>
<!-- Here I want to display images in select tag to make selection of one from all images but not able to achieve it. -->
<select id="ImageTemplateProductsList1">
{% for IT in ImageTemplateProductsList %}
<option value="{{IT}}"
><img src="{{IT.url}}" height="250" width="400"
class="border border-secondary rounded my-2 mx-3">
</option>
<br>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger"
data-dismiss="modal">Close
</button>
<button type="button" class="btn btn-outline-secondary">
Select
</button>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-success my-2">Place Order</button>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").change(function() {
$(".type").hide();
$(this).next("input").show();
});
});
{% endblock %}
urls.py
path('order/<int:id>', views.order, name="user-order"),
I have slightly modified my html template with jquery and changed views a little bit and now it is working for me.
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
.t {
display: none;
}
img:hover {
opacity:0.8;
cursor: pointer;
}
img:active {
opacity:0.5;
cursor: pointer;
}
input[type=radio]:checked + label > img {
border: 20px solid rgb(228, 207, 94);
}
#dropdown{
height: 50px;
width: 50%;
font-size: 20px;
margin-left: 10px;
margin-top: 3px;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" id="templateValue" name="templateValue" value=""/>
{% csrf_token %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection"
class="templateSelection"/> Upload an
Image
<div class="type">
<input type="file" name="image"
class='btn btn-outline-secondary my-2 SelectedImage'>
</div>
<br>
<input type="radio" id="Select" name="ImageSelection" class="templateSelection"
/> Select
From Templates
<div class="type">
{% for IT in ImageTemplateProductsList %}
<input type="radio" name="image2" id="{{IT}}"
value="{{IT}}" class="SelectedImage t"/>
<label for="{{IT}}">
<img src="{{IT.url}}" style="width: 20vw;
height: 20vw;
padding: 2vw;"/>
</label>
<br>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button type="submit" class="btn btn-success my-2">Place Order</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").on('change', function() {
$(".type").hide();
$(this).next("div").show();
});
$("#templateValue").val('');
$(".templateSelection").on('change', function(){
$("#templateValue").val('');
$("#templateValue").val($(this).attr('id'));
console.log($("#templateValue").val());
});
});
{% endblock %}
I have used hidden field to check whether user is trying to upload the image or select tha image and according to that I am taking the decision that what should I do:
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
if request.method == 'POST':
try:
if request.POST['templateValue'] == 'Upload':
if 'image' in request.FILES:
Template_Value1 = request.FILES['image']
fs = FileSystemStorage()
fs.save(Template_Value1.name, Template_Value1)
TemplateValue = Template_Value1.name
elif request.POST['templateValue'] == 'Select':
TemplateValue = request.POST['image2']
else:
pass
except MultiValueDictKeyError:
pass
order_store = Order(product_img=TemplateValue)
order_store.save()
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)

django update function based view of multiple models

I have a parent model and two children models and I made a view to add multiple children to one parent
but I'm getting confused about making an update view for the parent with all children
this is the form to create multiple children
views.py
def create_day_view(request,pk):
mydate = get_object_or_404(MyDate,pk=pk)
if request.method == 'POST':
length = request.POST.get('length')
sof_zman_1 = request.POST.get('sof_zman_1')
sof_zman_2 = request.POST.get('sof_zman_2')
sof_zman_tefila = request.POST.get('sof_zman_tefila')
ad_image = request.POST.get('ad_image')
day_details = MyDateDetails.objects.create(
date = mydate,
sof_zman_1 = sof_zman_1,
sof_zman_2 = sof_zman_2,
sof_zman_tefila = sof_zman_tefila,
ad_image = ad_image,
)
for file_num in range(0, int(length)):
Image.objects.create(
date = mydate,
image = request.FILES.get(f'images{file_num}')
)
context = {'mydate': mydate}
return render(request, 'luach/create_day.html',context=context)
I'm sharing the template so you will understand how the form works
create_day.html
{% extends 'luach/base.html' %}
{% block content %}
<div class='container'>
<div class="jumbotron myjumbotron">
<div class="p-3 mb-2 bg-light text-center " style="border-radius: 10px;">
<h1 class='title-date text'>{{mydate.hebrew_date}}</h1>
<h4 class='english-date'>{{mydate.english_date}}</h4>
</div>
<label>sof zman 1</label>
<div class="row">
<div class="col">
<input type="time" id="sof_zman_1" class="form-control">
</div>
<div class="col">
</div>
</div>
<label>sof zman 2</label>
<div class="row">
<div class="col">
<input type="time" id="sof_zman_2" class="form-control">
</div>
<div class="col">
</div>
</div>
<label>sof zman tefila</label>
<div class="row">
<div class="col">
<input type="time" id="sof_zman_tefila" class="form-control">
</div>
<div class="col">
</div>
</div>
<br>
<!--<label>ad image</label>
<input type="file" id="ad_image">-->
<br>
<label>Images</label>
<br>
<div class="row">
<div class="col">
<input type="file" multiple>
</div>
<div class="col">
</div>
</div>
<button type="submit" id="saveBtn" class="btn btn-primary mt-4">Save</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var files = []
FilePond.registerPlugin(FilePondPluginFileValidateSize);
FilePond.registerPlugin(FilePondPluginFileValidateType);
FilePond.setOptions({
allowMultiple:true,
maxFiles:10,
maxFileSize: '10MB'
})
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create( inputElement, {
acceptedFileTypes:['image/png', 'image/jpeg','image/jpg'],
onaddfile: (err, fileItem) => {
if (!err) {
files.push(fileItem.file)
}
console.log(files)
},
onremovefile: (err, fileItem) => {
const index = files.indexOf(fileItem.file)
if (index > -1) {
files.splice(index, 1)
}
console.log(files)
}
} );
var formData = new FormData();
$(document).on('click', '#saveBtn', function(e) {
formData.append('length', files.length)
formData.append('sof_zman_1', $('#sof_zman_1').val())
formData.append('sof_zman_2', $('#sof_zman_2').val())
formData.append('sof_zman_tefila', $('#sof_zman_tefila').val())
formData.append('ad_image', $('#ad_image').val())
for (var i = 0; i < files.length; i++) {
formData.append('images' + i, files[i])
}
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')
$.ajax({
type: 'POST',
url: '{% url "day_new" pk=mydate.pk %}',
data: formData,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
success: function (){
//alert('The post has been created!')
window.location.href = "{% url 'date_detail' pk=mydate.pk %}";
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ":" + xhr.responseText)
}
})
})
})
</script>
{% endblock %}

Django 2, How to create an instance of Form in FormView with POST request?

I have a form made with HTML and I'm using a formview to take advantage of the POST method. The form has information on several HTML related select (interactive with Javascript), so the best option for me was to create an HTML form.
In summary, I want to instance a form. A form with the POST information, process the form, return the error messages or save (save is not the problem).
Code
Form View
class ServiceOrderForm(forms.Form):
TYPE = (
('preventivo', 'Preventivo'),
('correctivo', 'Correctivo'),
)
STATUS = (
('abierta','Abierta'), #amarillo
('aprobada','Aprobada'), #verde
('modificada','Modificada'), #rojo
('realizada','Realizada'), #azul
('rechazada','Rechazada'), #naranja
('Cerrada','Cerrada'), #Azul con check
)
id_orden_servicio = forms.IntegerField()
id_establecimiento = forms.IntegerField()
id_equipo_establecimiento = forms.IntegerField()
hora_entrada = forms.DateField()
hora_salida = forms.DateField()
tipo = forms.ChoiceField(choices=TYPE)
id_tecnico = forms.IntegerField()
fecha_panificada= forms.DateField()
hora_planificada = forms.DateField()
fecha = forms.DateField()
estado = forms.ChoiceField(choices=STATUS)
observaciones = forms.TextInput()
View
class ServiceOrderTemplateView(FormView):
''' Presenta el formulario del evento y sus detalles '''
template_name = 'serviceorders/service-order.html'
form_class = ServiceOrderForm
def get(self, request, **kwargs):
context = super(ServiceOrderTemplateView, self).get_context_data \
(**kwargs)
if request.user.is_authenticated and self.request.user.is_active:
customer_group = CustomerGroupData(request.user.id).get()
context_data_event = ContextDataEvent(customer_group)
event_service = ServiceEvent(kwargs['id_order_service'])
event_data = event_service.getEvent()
estado_equipo = {
'garantia': {
'label': 'danger',
'icon': 'fa-ban',
},
'vida_util' : {
'label': 'success',
'icon': 'fa-check',
}
}
data = {
'customer_group': customer_group,
'establishments' : context_data_event.getEstablishments(),
'equipments' : context_data_event.getEquipments(),
'create': False,
'technicals' : context_data_event.getTechnicals(),
'current_equipment' : event_data['equipment'],
'current_technical' : event_data['technical'],
'current_establishment': event_data['establishment'],
'current_year': 2018,
'equipment_standard' : event_data['equipment_standard'],
'historic_orders' : event_service.getHistoricEvent(),
'current_order_detail' : event_service.getDetailService(),
'images_service_order' : event_service.getImageItem(),
'items_mantenimiento' : event_service.getDetailService(),
'equipment_estatus' : estado_equipo,
'order_service' : event_data['order_service'],
'id_order' : kwargs['id_order_service'],
}
context.update({'data': data})
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
context = super(ServiceOrderTemplateView, self).get_context_data \
(**kwargs)
form = ServiceOrderForm(request.POST)
#the form always is empty
#if form is valid this method return
if form.is_valid():
print('El formulario es valido')
#more code
HttpResponseRedirect('/mostrar/orden/servicio/')
else:
print('El formulario en invalido')
#return this error ti html template
print(form.errors)
data = {
'form': form,
'errors' : form.errors
}
context.update({ 'data' : data })
print('recibiendo data por post')
return self.render_to_response(context)
html
<form action="" method="post" role="form">
{% csrf_token %}
<input type="hidden" name="id_orden_servicio" value="{{ data.order_service.id_orden_servicio }}">
<div class="col-md-1"></div>
<div class="col-md-5">
<div class="row">
<div class="col-sm-4 text-right">
<label>Nro Orden:</label>
</div>
<div class="col-sm-4">
<input
type="text"
readonly = ""
name="id_orden_servicio"
value="OS-{{ data.current_year }}-{{ data.order_service.id_orden_servicio }}"
>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Establecimiento:</label>
</div>
<div class="col-sm-4">
<select class="btn btn-sm btn-default" name="id_establecimiento" id="id_establecimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for establishment in data.establishment %}
<option value="{{ establishment.id_establecimiento }}">{{ establishment }}</option>
{% endfor %}
{% else %}
<option value="{{ data.current_establishment.id_establecimiento }}" disabled selected>{{ data.current_establishment }}</option>
{% endif %}
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Equipos:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="id_equipo_establecimiento" id="id_equipo_establecimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for equipment in data.equipments %}
<option value="{{equipment.id_equipo_establecimiento}}">{{ equipment }}</option>
{% endfor %}
{% else %}
<option value="{{data.current_equipment.id_equipo_establecimiento}}" disabled selected>{{ data.current_equipment }}</option>
{% endif %}
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Mantenimiento.:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="tipo_mantenimiento" id="tipo_mantenimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
<option value="preventivo">Preventivo</option>
<option value="correctivo">Correctivo</option>
{% else %}
<option selected disabled value="{{data.order_service.tipo}}">{{ data.order_service.tipo | upper}}</option>
{% endif %}
</option>
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Técnico:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="id_tecnico" id="id_tecnico">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for technical in data.technicals %}
<option value="{{technical.id_tecnico}}">{{ technicals.apellidos }} {{ technicals.nombres }} </option>
{% endfor %}
{% else %}
<option value="{{ data.order_service.id_tecnico_id }}">{{ data.order_service.id_tecnico }}</option>
{% endif %}
</option>
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Fecha Mant.:</label>
</div>
<div class="col-sm-5">
<input type="text" name="fecha" style="width: 100%" value = "{{ data.order_service.fecha | date:"d/m/Y" }}">
</div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Observaciones:</label>
</div>
<div class="col-sm-5">
<textarea rows="5" cols="31" name="observaciones">{{ data.order_service.observaciones }}</textarea>
</div>
</div>
</div>
<div class="col-md-5">
<div class="row">
<div class="col-sm-4 text-right">
<label>Imagen de equipo:</label>
</div>
<div class="col-sm-6">
<img src="{{BASE_URL}}media/{{ data.current_equipment.url_imagen }}" style="width: 60%;height: auto">
</div>
<div class="col-sm-2 text-left">
<span class="label label-{{data.equipment_estatus.garantia.label}}">
<i class="fas {{ data.equipment_estatus.garantia.icon }}"></i> Garantía
</span>
<span class="label label-{{data.equipment_estatus.vida_util.label}}">
<i class="fas {{ data.equipment_estatus.vida_util.icon }}"></i> Vida Útil
</span>
</div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Plano ubicación:</label>
</div>
<div class="col-sm-6">
<a href="{{BASE_URL}}media/{{ data.current_equipment.url_ubicacion}}" class="btn btn-sm btn-default" target="_blank">
<i class="fa fa-eye"></i> Ver Ubicación
</a>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Lugar:</label>
</div>
<div class="col-sm-6">
<input type="text" value="{{ data.current_equipment.ubicacion }}" readonly="">
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Nro Serie:</label>
</div>
<div class="col-sm-6">
<input type="text" value="{{ data.current_equipment.nro_serie }}" readonly="">
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Estado Orden:</label>
</div>
<div class="col-sm-6">
{% if data.create == True %}
<a href="#" class="btn btn-sm {{data.order_service.estado}}">
<i class="fas fa-info-circle"></i>
ABIERTA
</a>
{% else %}
<a href="#" class="btn btn-sm {{data.order_service.estado}}">
<i class="fas fa-info-circle"></i>
{{ data.order_service.estado | upper }}
</a>
{% endif %}
</div>
<div class="col-sm-2"></div>
</div>
<br>
<div class="row">
<div class="col-sm-8 text-right">
</div>
<div class="col-sm-4 text-right">
<button class="btn btn-sm btn-primary" type="submit">
{% if data.create == True %}
<span class="fas fa-plus"></span>
Agergar Orden Mantenimiento
{% else %}
<span class="fas fa-save"></span>
Guardar Cambios
{% endif %}
</button>
</div>
</div>
</div>
<div class="col-md-1"></div>
</form>
thanks!.
I solved it
the form was always empty because the forms.py did not have the same fields as the html
i cant use createview because need add information in the form.

How to add more than item to the session in Flask

I've created a add-to-cart in my website and it works just great.
Am using Jquery.getJSON to make the request to get the value of the chosen product, here is the code:
$(function() {
$('a#process_menu').bind('click', function() {
/*var amount = document.getElementById('kale').value;*/
$.getJSON('{{url_for("get_the_order")}}', {
menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
}, function(data) {
location.reload();
});
return false;
});
});
and here is the function that receiving the request:
#app.route('/get_the_order')
def get_the_order():
global the_order_list
try:
the_order_list = []
sum_list = []
get_order = request.args.get('menu_order', 0, type=str)
get_price = request.args.get('price_order', 0, type=str)
the_order_list.append(get_order)
sum_list.append(get_price)
session['theOrder'] = ' '.join(the_order_list)
session['price'] = ' '.join(sum_list)
return jsonify(result=the_order_list + sum_list)
except Exception as e:
return redirect("menu")
and here i have the template that shows all the products:
{% if entries_menu %}
{% for menu_ent in entries_menu %}
<div class="col-sm-6 col-md-3 col-lg-3 {{menu_ent.categorie}}">
<div class="portfolio-item">
<div class="hover-bg">
<a id="process_menu">
<div class="hover-text">
<h4 id="title">{{menu_ent.title}}</h4>
<small id="price">{{menu_ent.price}}</small>
<div class="clearfix"></div>
<i class="fa fa-plus add_basket"></i>
<div class="counter-order">
<div class="row">
<div class="col-md-3">
<form>
<fieldset>
<div class="form-group">
<input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<img src="../../static/{{menu_ent.path}}" class="img-responsive" alt="..." id="image-menu">
</a>
</div>
<h4 class="brand bold">{{menu_ent.title}}</h4>
<span class="price pull-right">{{menu_ent.price}} </span><span class="amount pull-right"> {{menu_ent.amount}}</span>
<p id="descr">{{menu_ent.descr}}</p>
</div>
</div>
{% endfor %}
{% endif %}
here i made this function to put all the products within array and showing them above where the cart exist beside the header, this is the file where all the logic happens also where it should show what i want:
{% if session.logged_in %}
{% if session.theOrder %}
<div class="confirm-cancel">
<i class="fa fa-close fa-3x btn-danger"></i>
<i class="fa fa-check fa-3x btn-success"></i>
</div>
{% endif %}
<li class='main'><a href='/#main'><span>Main</span></a></li>
<li class="comfort"><a href='/#ckidki' ><span>Chief</span></a></li>
<li class="menu"><a href='/menu/' ><span>Menu</span></a></li>
<li class="order"><a href="/order/" ><span>Make an order</span></a></li>
<li class="contact"><a href='/#contact' ><span>Contact us</span></a></li>
<li class="last orders"><a href='/admin/' ><span>Admin</span></a></li>
{% if session.theOrder %}
<li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">{{session.get('theOrder')}} &nbspx{{session.get('price')}}</p></i></li>
{% else %}
<li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">0$ &nbsp&nbsp</p></i></li>
{% endif %}
{% endif %}
The problem is i can't get all the products that i've been chosen inside the session, so if i checked the products list i see only one, in fact , am getting only the clicked item every time.
Please, any suggestion how to make that work, anyway please, any help would be tons appreciated .
I modified your code like this:
the_order_list = session['theOrder']
sum_list = session['price']
the_order_list.append(get_order)
sum_list.append(get_price)
session['theOrder'] = the_order_list
session['price'] = sum_list
I was facing the same issue and finally got this answer!
#app.route('/addtocart/') #加入购物车选项
def addtocart():
id = request.args.get('id')
if 'cart' not in session:
session['cart'] = [] #
cart_list = session['cart']
cart_list.append(id)
session['cart'] = cart_list #
print(session)
cart_list = session['cart'] will return an empty list. Then, after cart_list.append(id), you've got a list with length 1. The key sentence is session['cart'] = cart_list, if you don't do this, your list's maximum length is 2.

Categories

Resources