let say these are the inputs of user, in my view it's well validated form.is_valid().
item code | description | unit | quantity
---------------------------------------------------------------
#itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1
#itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2
#itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3
reqeust.POST.getlist('description')
return a list -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3']
How can i save all the cells that the user enter to my MaterialIndent model??
just like in myview i could only save the last item only !!
# models
class MaterialIndent(models.Model):
material_indent_id = models.AutoField(primary_key=True)
date_request = models.DateTimeField(auto_now_add=True)
local_code = models.CharField(max_length=10, default='Local')
quotation = models.FileField(upload_to='files/', null=True, blank=True)
description = models.CharField(max_length=200)
unit = models.CharField(max_length=100)
quantity_requested = models.DecimalField(max_digits=12, decimal_places=2)
quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True)
request_for = models.CharField(max_length=50)
requester = models.ForeignKey(User, on_delete=models.CASCADE)
priority = models.CharField(max_length=100)
status = models.CharField(max_length=50, default='Store Checking')
def __str__(self):
return str(self.material_indent_id)
# form
class MaterialIndentForm(ModelForm):
class Meta:
model = MaterialIndent
fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation']
# views
def test(request):
available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True)
if request.method == 'POST':
form = MaterialIndentForm(request.POST, request.FILES)
if form.is_valid():
length = len(request.POST.getlist('local_code'))
post = form.save(commit=False)
for r in range(length):
local_code = request.POST.getlist('local_code')[r]
description = request.POST.getlist('description')[r]
unit = request.POST.getlist('unit')[r]
quantity_requested = request.POST.getlist('quantity_requested')[r]
post.local_code = local_code
post.description = description
post.unit = unit
post.quantity_requested = quantity_requested
post.requester = request.user
post.quantity_remained = post.quantity_requested
post.status = 'Store Checking'
post.save()
print('form is valid')
else:
print(form.errors)
else:
sparestock = SparePartsStock.objects.all()
form = MaterialIndentForm()
context = {'form': form, 'stock':available_stock, 'table': sparestock}
return render(request, 'copy.html', {})
# template
{% extends 'inventory.html' %}
{% load static %}
{% load crispy_forms_filters %}
{% block title %}
SG
{% endblock %}
{% block head %}
<style>
.container{
padding: 100px;
}
#priority_label{
margin-left: 15px;
}
#submit_button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
background-color: #555555;/* Black */
}
.btn {
background-color: DodgerBlue;
border: none;
color: white;
padding: 12px 16px;
font-size: 16px;
cursor: pointer;
}
/* Darker background on mouse-over */
.btn:hover {
background-color: RoyalBlue;
}
#rowAdder{
margin-left: 15px;
right: 10px;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
<script src="{% static 'js/jQuery.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
{% endblock %}
{% block content %}
<div class="container">
<h2 style="">Material Indent</h2>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="card">
<div class="card-header">
<label id="priority_label" for="rate">Priority</label><br>
<div class="rate">
<input type="radio" id="star5" name="priority" value="High" required/>
<label for="star5" title="High">High</label>
<input type="radio" id="star4" name="priority" value="Medium" required/>
<label for="star4" title="Medium">Medium</label>
<input type="radio" id="star3" name="priority" value="Low" required/>
<label for="star3" title="Low">Low</label>
</div>
<input name="request_for" type="text" class="form-control m-input" placeholder="Requested For" required><br>
<label for="quotation">Quotation: </label>
<input type="file" name="quotation" placeholder="Quotation">
</div>
<div class="card-body">
<div class="">
<div class="col-lg-12">
<div id="row">
<div class="input-group m-3">
<div class="input-group-prepend">
<button class="btn btn-danger"
id="DeleteRow" type="button">
<i class="bi bi-trash"></i>
-
</button>
</div>
<input id="local_code0" name="local_code0" type="text" class="form-control m-input" placeholder="Local Code" required list="localList">
<datalist id="localList">
{% for item in stock %}
<option value={{ item }}>
{% endfor %}
</datalist>
<input name="description0" type="text" class="form-control m-input" placeholder="Description">
<input name="unit0" type="text" class="form-control m-input" placeholder="Unit">
<input name="quantity0" type="text" class="form-control m-input" placeholder="Quantity">
</div>
</div>
<div id="newinput"></div>
<button id="rowAdder" type="button"
class="btn btn-dark">
<span class="bi bi-plus-square-dotted" id="plus_sign">
</span> +
</button>
<input type="hidden" name="length" id="length">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="button button5" id="submit_button">Submit</button>
</div>
</form>
</div>
<script type="text/javascript" >
let count = Number(1)
document.getElementById('length').value = 0
console.log(document.getElementById('length').value)
$("#rowAdder").click(function () {
document.getElementById('length').value = count
newRowAdd =
'<div id="row"> <div class="input-group m-3">' +
'<div class="input-group-prepend">' +
'<button class="btn btn-danger" id="DeleteRow" type="button">' +
'<i class="bi bi-trash"></i> - </button> </div>' +
'<input name=local_code' + count +' type="text" class="form-control m-input" placeholder="Local Code" list="localList" required>'+
'<input name=description'+count+ ' type="text" class="form-control m-input" placeholder="Description" required>'+
'<input name=unit'+count+ ' type="text" class="form-control m-input" placeholder="Unit" required>'+
'<input name=quantity'+count+ ' type="text" class="form-control m-input" placeholder="Quantity" required> </div> </div>'
;
$('#newinput').append(newRowAdd);
count ++
});
$("body").on("click", "#DeleteRow", function () {
$(this).parents("#row").remove();
count --
})
</script>
<script src="{% static 'js/material_indent_autofill.js' %}"></script>
{% include 'spare_parts_table.html' %}
{% endblock %}
Related
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.
I am working on a Django app where the user will be able to take any survey they pick from a list of surveys. For one of the surveys, they are supposed to select an image that best represents their mood. For their answer I do not need to record the image they selected, just the name of the mood it represents (for example, "cheerful"). Therefore, I have not yet added an "image" field to the model. However, the user should be able to see the image and select it. At the moment I am not able to display the images, only getting the names. I have checked my code and still unable to find the mistake. By the way, not getting any technical error messages. Any recommendations you have are appreciated. Below are my models, views, and HTML. I apologize for the lengthy files.
Thank you!
Models
User = settings.AUTH_USER_MODEL
class Questionnaire(models.Model):
name = models.CharField(max_length=255)
text = models.CharField(max_length=200)
def __str__(self):
return self.name
class Question(models.Model):
text = models.CharField(max_length=200)
questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions')
def __str__(self):
return self.text
class Answer(models.Model):
questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='answers', default='')
text = models.CharField(max_length=200)
def __str__(self):
return self.text
class Response(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
question = models.ForeignKey(Question, on_delete = models.CASCADE)
answer = models.ForeignKey(Answer, on_delete = models.CASCADE)
def __str__(self):
return '%s - %s - %s - %s' % (self.user, self.question, self.answer, self.date)
Views
from django.forms import ModelForm
class ResponseForm(ModelForm):
class Meta:
model = Response
fields = ['question', 'answer']
# widgets= {'answer': RadioSelect}
def __init__(self, *args, user=None, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def save(self, commit=True):
response = super().save(commit=False)
response.user = self.user
return response.save()
def take_questionnaire_fs(request, questionnaire_id):
ResponseFormSet = modelformset_factory(Response, form=ResponseForm, extra=0)
if request.method == 'POST':
formset = ResponseFormSet(request.POST or None, request.FILES, form_kwargs={'user': request.user})
if formset.is_valid():
print("Formset is valid")
formset.save()
return HttpResponseRedirect(reverse ('questionnaires:questionnaire_index'))
else:
print("Formset is NOT valid")
print(formset.errors)
print(formset.non_form_errors())
questions = Question.objects.filter(questionnaire_id=questionnaire_id)
answers = Answer.objects.filter(questionnaire_id=questionnaire_id)
return render(request, 'questionnaires/take_questionnaire_fs.html', {
'questions': questions,
'answers': answers,
})
HTML
{% extends "base.html" %}
{% block page_content %}
{% if questionnaire.name == 'Pick-a-Mood' %}
<form action="{{ request.url }}" method="post">
{% csrf_token %}
<style>
.circle-container {
position: relative;
width: 24em;
height: 24em;
padding: 2.8em;
/*2.8em = 2em*1.4 (2em = half the width of a link with img, 1.4 = sqrt(2))*/
/* border: dashed 1px; */
border-radius: 50%;
margin: 1.75em auto 0;
}
.circle-container label {
display: block;
position: absolute;
top: 50%; left: 50%;
width: 8em; height: 8em;
margin: -2em;
}
.circle-container img { display: block; width: 100%; }
.deg22_5 { transform: rotate(22.5deg) translate(12em) rotate(-22.5deg); }
.deg67_5 { transform: rotate(67.5deg) translate(12em) rotate(-67.5deg); }
.deg112_5 { transform: rotate(112.5deg) translate(12em) rotate(-112.5deg); }
.deg157_5 { transform: rotate(157.5deg) translate(12em) rotate(-157.5deg); }
.deg202_5 { transform: rotate(202.5deg) translate(12em) rotate(-202.5deg); }
.deg247_5 { transform: rotate(247.5deg) translate(12em) rotate(-247.5deg); }
.deg292_5 { transform: rotate(292.5deg) translate(12em) rotate(-292.5deg); }
.deg337_5 { transform: rotate(337.5deg) translate(12em) rotate(-337.5deg); }
/* HIDE RADIO */
[type=radio] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
/* IMAGE STYLES */
[type=radio] + img {
cursor: pointer;
}
/* CHECKED STYLES */
[type=radio]:checked + img {
border: 2px solid #f00;
}
[type=radio]:not(:checked) + img {
border: none;
}
</style>
<div class="circle-container">
<label class='center'>
<input type="radio" name="pickamood" value="Neutral">
<img src="/static/mysurveys/female_neutral.png">
</label>
<label class='deg22_5'>
<input type="radio" name="pickamood" value="Relaxed">
<img src="/static/mysurveys/female_relaxed.png">
</label>
<label class='deg67_5'>
<input type="radio" name="pickamood" value="Calm">
<img src="/static/mysurveys/female_calm.png">
</label>
<label class='deg112_5'>
<input type="radio" name="pickamood" value="Bored">
<img src="/static/mysurveys/female_bored.png">
</label>
<label class='deg157_5'>
<input type="radio" name="pickamood" value="Sad">
<img src="/static/mysurveys/female_sad.png">
</label>
<label class='deg202_5'>
<input type="radio" name="pickamood" value="Irritated">
<img src="/static/mysurveys/female_irritated.png">
</label>
<label class='deg247_5'>
<input type="radio" name="pickamood" value="Tense">
<img src="/static/mysurveys/female_tense.png">
</label>
<label class='deg292_5'>
<input type="radio" name="pickamood" value="Excited">
<img src="/static/mysurveys/female_excited.png">
</label>
<label class='deg337_5'>
<input type="radio" name="pickamood" value="Cheerful">
<img src="/static/mysurveys/female_cheerful.png">
</label>
</div>
<a>
<input type="submit" value="Submit" >
</a>
</form>
{% else %}
<form method="post" action="{{ request.url }}">
{% csrf_token %}
{% for question in questions %}
<h1>{{question.text}}</h1>
<label hidden="" for="id_form-{{ forloop.counter0 }}-question">Question:</label>
<select hidden="" name="form-{{ forloop.counter0 }}-question" id="id_form-{{ forloop.counter0 }}-question">
<option value="{{question.id}}" selected="">{{question.text}}</option>
</select>
<label for="id_form-{{ forloop.counter0 }}-answer">Answer:</label>
<select required="" name="form-{{ forloop.counter0 }}-answer" id="id_form-{{ forloop.counter0 }}-answer">
<option value="" selected="">---------</option>
{% for answer in answers %}
<option value="{{answer.id}}">{{answer.text}}</option>
{% endfor %}
</select>
<input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id">
<input type="hidden" name="form-TOTAL_FORMS" value="{{questions|length}}" id="id_form-TOTAL_FORMS" />
<input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" />
<input type="hidden" name="form-MAX_NUM_FORMS" value="{{questions|length}}" id="id_form-MAX_NUM_FORMS" />
{% endfor %}
<br />
<br />
<input type="submit" value="Submit">
</form>
{% endif %}
{% endblock %}
You need to use static files.
Make sure it’s set up in your settings.py and then in the html load static and use it to get your files.
Eg. Assuming your files are in a static folder and that is set up in settings.py
<img src="{% static 'mysurveys/female_irritated.png' %}">
Try these steps in order:
Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.
In your settings file, define STATIC_URL:
STATIC_URL = '/static/'
In your template file
{% load static %}
<img src="{% static 'mysurveys/female_irritated.png' %}" alt="image alt">
Store your static files in a folder called static in your app. For example my_app/static/mysurveys/female_bored.png. As you done already
More informations in Django doc.
thank you for the suggestions! The static files were set up correctly, the error was that I needed to add the field 'questionnaire' to my views. The syntax is now:
def take_questionnaire_fs(request, questionnaire_id):
ResponseFormSet = modelformset_factory(Response, form=ResponseForm, extra=0)
if request.method == 'POST':
formset = ResponseFormSet(request.POST or None, request.FILES, form_kwargs={'user': request.user})
if formset.is_valid():
# do something with the formset.cleaned_data
print("Formset is valid")
formset.save()
return HttpResponseRedirect(reverse ('questionnaires:questionnaire_index'))
else:
print("Formset is NOT valid")
print(formset.errors)
print(formset.non_form_errors())
questionnaire = Questionnaire.objects.get(id=questionnaire_id)
questions = Question.objects.filter(questionnaire_id=questionnaire_id)
answers = Answer.objects.filter(questionnaire_id=questionnaire_id)
return render(request, 'questionnaires/questionnaire_lec.html', {
'questions': questions,
'answers': answers,
'questionnaire': questionnaire,
})
I think i have successfully created relation between user model and another table called shop_details but the data is not been inserted. i don't know what is going wrong.
the code is here.
models.py
from django.db import models
from django.contrib.auth.models import User
class Shop_Details(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
shop_name = models.CharField(max_length=50)
shop_street = models.TextField()
shop_area = models.TextField()
city = models.CharField(max_length=50)
state = models.CharField(max_length=50)
pin_code = models.TextField()
my views.py is here
views.py
def shop_detils(request):
if request.method == "POST":
shop_name = request.POST['shop_name']
shop_street = request.POST['shop_street']
shop_area = request.POST['shop_area']
city = request.POST['city']
state = request.POST['state']
pin_code = request.POST['pin_code']
if(len(str(pin_code))!=6):
messages.info(request,"please provide a valid address pin-code")
print("niceee...........................")
return render(request,'shop_details.html')
else:
if(is_number(int(pin_code))):
shop = Shop_Details(shop_name=shop_name,shop_street=shop_street,shop_area=shop_area,city=city,state=state,pin_code=pin_code,user=request.user)
shop.save()
messages.info(request,"Shop Details Updated")
shop_data = Shop_Details.objects.filter(user = request.user)
print(shop_data[1])
print("congrats...........................")
return redirect('home',{'data':shop_data})
else:
messages.info(request,"please provide a valid address")
print("nice2222222222222222222222222")
return render(request,'shop_details.html')
else:
return render(request,'shop_details.html')
my shop_details.html is here
shop_detsils.html
enter code here
{% extends 'layout.html' %}
{% csrf_token %}
{% if user.is_authenticated %}
{% csrf_token %}
{% load static %}
{% csrf_token %}
<meta name="viewport" content="width=device-width, initial-scale=1">
{% csrf_token %}
<body align="center">
{% csrf_token %}
{% csrf_token %}
{% csrf_token %}
{% block content %}
<form action="shop_detils" method="POST">
{% csrf_token %}
<div align="center" class='resp_code frms'>
{% csrf_token %}
<p align='center'<h5><font style='font: 1em/1.3em Tahoma,Geneva,sans-serif;'>
<b>Shop Details</b></font></h5></p>
<div id="selection">
{% csrf_token %}
<table>
{% csrf_token %}
<tr><td>Shop Name: </td><td><input required style="width:200%;" name="shop_name" type="text"></td></tr>
<tr><td>Shop Street: </td><td><input required style="width:200%;" name="shop_street" type="text"></td></tr>
<tr><td>Shop Area: </td><td><input required style="width:200%;" name="shop_area" type="text"></td></tr>
<tr><td>City: </td><td><input required style="width:200%;" name="city" type="text"></td></tr>
<tr><td>State: </td><td><input required style="width:200%" list="state" name="state" type="text"></td></tr>
<datalist id="state">
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
<option value="Arunachal Pradesh">Arunachal Pradesh</option>
<option value="Assam">Assam</option>
<option value="Bihar">Bihar</option>
<option value="Chandigarh">Chandigarh</option>
<option value="Chhattisgarh">Chhattisgarh</option>
<option value="Dadar and Nagar Haveli">Dadar and Nagar Haveli</option>
<option value="Daman and Diu">Daman and Diu</option>
<option value="Delhi">Delhi</option>
<option value="Lakshadweep">Lakshadweep</option>
<option value="Puducherry">Puducherry</option>
<option value="Goa">Goa</option>
<option value="Gujarat">Gujarat</option>
<option value="Haryana">Haryana</option>
<option value="Himachal Pradesh">Himachal Pradesh</option>
<option value="Jammu and Kashmir">Jammu and Kashmir</option>
<option value="Jharkhand">Jharkhand</option>
<option value="Karnataka">Karnataka</option>
<option value="Kerala">Kerala</option>
<option value="Madhya Pradesh">Madhya Pradesh</option>
<option value="Maharashtra">Maharashtra</option>
<option value="Manipur">Manipur</option>
<option value="Meghalaya">Meghalaya</option>
<option value="Mizoram">Mizoram</option>
<option value="Nagaland">Nagaland</option>
<option value="Odisha">Odisha</option>
<option value="Punjab">Punjab</option>
<option value="Rajasthan">Rajasthan</option>
<option value="Sikkim">Sikkim</option>
<option value="Tamil Nadu">Tamil Nadu</option>
<option value="Telangana">Telangana</option>
<option value="Tripura">Tripura</option>
<option value="Uttar Pradesh">Uttar Pradesh</option>
<option value="Uttarakhand">Uttarakhand</option>
<option value="West Bengal">West Bengal</option>
</datalist>
<tr><td>Pin-code: </td><td><input required name="pin_code" type="text"></td></tr>
</table>
<input style="border-radius: 0.5em; background-color:rgba(2, 2, 253, 0.753);
width:2.5cm;height:0.8cm; font-family: sans-serif;" type="submit" value="Submit">
</div>
</div>
</form>
{% endblock %}
</body>
{% endif %}
my layout.html is here. basically Iam extending layout.html in all html files.
layout.html
<!DOCTYPE html>
{% load static %}
{% csrf_token %}
<html>
<title>GrocSale</title>
<head>
<script language="Javascript" href="{% static 'js/jquery.js' %}"></script>
<script type="text/JavaScript" href="{% static 'js/state.js'%}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'style.css'%}">
</head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
{% csrf_token %}
<style>
* {box-sizing: border-box}
body{
background:url("{% static 'groc.jpeg' %}") no-repeat;
background-size:cover ;
background-attachment:fixed;
}
body:after {
content: "";
position: fixed;
top: 0; bottom: 0; left: 0; right: 0;
background: hsla(180,0%,50%,0.25);
pointer-events: none;
}
.tab {
float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 20%;
height: 1000px;
}
/* Style the buttons that are used to open the tab content */
.tab button {
display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current "tab button" class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
}
.divs{
width: 300px;
height: 300px;
border: 1px solid green;
padding: 50px;
float: left;
border-radius: 1em;
box-shadow: 10px 10px;
margin-right: 15px;
margin-left: 15px;
margin-top: 15px;
}
.divs:hover:not(.active) {
background-color: gold;
cursor: grab;
}
</style>
<body>
{% csrf_token %}
<header align="center" style="height: 150px;background-color:orange">
{% csrf_token %}
<strong>
{% csrf_token %}
{% for detail in data%}
<h1>{{detail.shop_name}}</h1>
<h4>Arokya,Hatsun,Arun All Products Available Here</h4>
<h6>{{detail.shop_street}}{{detail.shop_area}}, {{detail.city}}, {{detail.state}} - {{detail.pin_code}}</h6>
{% endfor %}
</strong>
</header>
<div style="background-color:orange;" class="tab" >
{% csrf_token %}
<button class="w3-bar-item w3-button" >Home</button>
<button class="w3-bar-item w3-button" >Add/Update Product</button>
<button class="w3-bar-item w3-button" >Add Stock/Update Stock</button>
<button class="w3-bar-item w3-button" >Add Sale</button>
<button class="w3-bar-item w3-button" >Total Sale</button>
<button class="w3-bar-item w3-button" >Daily Collection Customers</button>
<button class="w3-bar-item w3-button" >Today's Collection Status</button>
<button class="w3-bar-item w3-button" >Show Products</button>
<button class="w3-bar-item w3-button" >All Stock Orders</button>
<button class="w3-bar-item w3-button" >Settings</button>
<a href="{% url 'shop_detils' %}" ><button class="w3-bar-item w3-button" >Shop Details</button></a>
<button class="w3-bar-item w3-button" >Contact Us</button>
<button class="w3-bar-item w3-button" >Logout</button>
</div>
{% block content %}
{% endblock %}
</body>
</html>
Iam still a learner in Django.
Thanks in advance.
my error is shown in image
enter image description here
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)
HTML file (+Flask+Bootstrap)
{% extends "bootstrap/base.html" %}
{% block content %}
<html>
<head>
<style>
table, th, td {
background: #f5f5f5;
border-collapse: separate;
box-shadow: inset 0 1px 0 #fff;
font-size: 12px;
line-height: 24px;
margin: 30px auto;
text-align: left;
width: 800px;
}
.center {
text-align: center;
margin: auto;
width: 80%;
border: 3px solid rgba(0, 0, 0, 0);
padding: 20px;
}
.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
background-color: #efefef00;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<ul class="nav navbar-nav">
<a class="navbar-brand"> TMS </a>
<li>Routing</li>
</ul>
</div>
</nav>
<table style="width:auto" align="center">
<tr>
<th>
<p>Select the route sheet:</p>
<div class='center'>
<form ip="upload-form" action="{{ url_for('routing') }}" method="POST"
enctype="multipart/form-data">
<input type="file" name="file" accept="/" multiple>
<input type="submit" action="submit" value="send">
</div>
</th>
</tr>
</table>
{% if ifHTMLConditional %}
<form method='POST' action="{{ url_for('routing') }}">
<table>
<tr>
<th>Name</th>
<th>Meters</th>
</tr>
{% for i in returnFromObjectClassRoute %}
<tr>
<td>
<input type="checkbox" name="vehicle" value= {{ i[1] }}>
{{ i[1] }}
</input>
</td>
<td>
{{ i[2] }}
</td>
</tr>
{% endfor %}
</table>
<input type="submit" value = {{ test.test }}>
{% endif %}
</form>
</body>
</html>
{% endblock %}
How could I use this for loop to create the number of checkboxes but with returns for using them in next functionalities.
The goal of the program is to create a Short Route. With the checkbox I want to let the user to select where is the startPoint for the algorithm
Python Code
#app.route('/routing', methods=['GET', 'POST'])
def routing():
test = Reference()
print(test.test.data)
if test == True:
return redirect('/home')
else:
if request.method == 'POST':
directory = os.path.join(APP_ROOT)
ifHTMLConditional = False
if not os.path.isdir(directory):
os.mkdir(directory)
for file in request.files.getlist("file"):
filename = file.filename
destination = "/".join([directory, filename])
if file.filename != '':
file.save(destination)
objectFromClassRoute = Route(filename, 'totalDistances_AB_BA_12012018.csv')
returnFromObjectClassRoute = objectFromClassRoute.routing1()
ifHTMLConditional = True
else:
returnFromObjectClassRoute = []
ifHTMLConditional = False
return redirect ('/home')
return render_template('routing.html', test=test, returnFromObjectClassRoute=returnFromObjectClassRoute, ifHTMLConditional=ifHTMLConditional)
return render_template('routing.html')
returnFromObjectClassRoute returns a list as a value.
Python code
An example for what I was looking for:
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SECRET_KEY'] = 'ThisIsSecret'
class Reference():
def testList(self):
testList = ['ABC', 'DEF', 'GHI']
return testList
#app.route('/home', methods=['GET', 'POST'])
def home():
test1 = Reference()
test = test1.testList()
print(test1.testList())
if request.method == "POST":
selected_contacts = request.form.getlist("test")
return render_template('checkBoxTest.html', test=test)
if __name__ == '__main__':
app.run(debug=True)
Html + Jinja2 code
<html>
<head>
</head>
<body>
<form method='POST' action="{{ url_for('home') }}">
{{ test.csrf_token }}
{% for i in test %}
<input type="checkbox" name="test" value="{{i}}">
<label>{{i}}</label>
{% endfor %}
<input type="submit" action="submit">
</form>
</body>
</html>
It returns all the check list you had activate before submitting and return a list of the values where you can used them as you want