I have a drop down and it is populated through my models. I am able to select one and then push submit. But the data that I am getting is being broke by spaces in the name. So if I have an option in my drop down menu such as:
Please Pick Me
I will only get
Please
template.html
<form action="{% url 'parsed' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sel1">Select Test:</label>
<select class="form-control" name="selectedtest" id="sel1">
{% for test in test %}
<option value={{ test.name }}>{{ test.name }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label>Paste Event JSON</label>
<textarea class="form-control" name="jsontextarea" rows="20"></textarea>
<div style="text-align:center">
</br>
<input class="btn btn-primary" type="submit" value="Parse">
</div>
</div>
</form>
views.py
def parsed(request):
data = request.POST.get('jsontextarea')
testname = request.POST.get('selectedtest')
print(testname)
context = {
"json" : data,
"test" : Test.objects.all(),
"event" : Event.objects.all(),
"platform" : Platform.objects.all(),
"device" : Device.objects.all(),
"property" : Property.objects.all(),
"testname" : testname
}
return render(request, 'jsonparser/parsed.html', context)
Try replacing
<option value={{ test.name }}>{{ test.name }}</option>
with
<option value="{{ test.name }}">{{ test.name }}</option> (Notice the double quotes)
My guess is that your HTML becomes - <option value=Please Pick Me>Please pick me</option> and in this case the value of the option is "Please". If you use double quotes however, it would become <option value="Please Pick Me">Please pick me</option> which is what you want
Related
I want to fetch the data from database. I am using Ajax and then I want to define it in views.py to extract the data and display it in view(webpage) using Django. How may I approach in order to bring "be_total" the data from the database and then display the values of "be_total" in the form of bar chart on my webpage?
Can anyone please help me ?
My codes are:
index.html:
<form class="form-row" method="post" >
{% csrf_token %}
<div class="form-group col-md-2" >
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m1">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m2">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m3">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m4">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m5">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<button type="button" onclick="submitData()">Submit</button>
</div>
</form>
````
````
<script type="text/javascript">
function submit(){
// Get answer from the input element
var dt = document.getElementById("m1").value;
var dtt = document.getElementById("m2").value;
var dttt = document.getElementById("m3").value;
var dtttt = document.getElementById("m4").value;
var dttttt = document.getElementById("m5").value;
// add the url over here where you want to submit form .
var url = 'home';
$.ajax({
url: url,
data: {
'm1': dt,
'm2': dtt,
'm3': dttt,
'm4': dtttt,
'm5': dttttt,
},
dataType: 'JSON',
success: function(data){
// show an alert message when form is submitted and it gets a response from the view where result is provided and if url is provided then redirect the user to that url.
alert(data.result);
if (data.url){
window.open(data.url, '_self');
}
}
});
}
</script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
**views.py:**
def home(request):
majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk")
if request.method == 'POST':
form = request.POST.get('be_nextyr_total')
line_chart = pygal.Line(width=1500)
line_chart.title = 'Budget Estimation'
context = {
"chart": line_chart.render_data_uri(),
'majors': majors
}
return render(request, "website/index.html" , context )
you have to specify type in your ajax code like this
type:'POST'
nam and mob field are userinput fields which i am using for user input and later i am using them for filtering
{% block content %}
<form class="form-signin" action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Nam" autofocus>
</div>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="mob" id="mob" >
<option>{{ customer.sponsor }}</option>
{% for i in sponsor %}
<option value="{{ i.mobile }}"> {{ i.mobile|add:' - '|add:i.name }} </option>
{% endfor %}
</select>
<div class="invalid-feedback">
Please select a valid Existing Customer.
</div>
</div>
<div class="mb-3">
Search
Urls.py
path('customer_view',views.customer_view,name='customer_view')
Views.py
def customer_view(request):
print(request.method )
name1 = str(request.POST.get('nam'))
print(name1)
mobile1 = str(request.POST.get('mob'))
print(mobile1)
customers_list = customer.objects.filter(
mobile=mobile1) & customer.objects.filter(name=name1)
sponsors = customer.objects.all().distinct('mobile')
ctx = { 'customer': customers_list, 'sponsor': sponsors }
return render(request, 'pages/customer_view.html', ctx)
You use href which does not submit the form. You need a submit button and change your action of your form to your view url. Try this:
{% block content %}
<form class="form-signin" action="{% url 'customer_view' %}" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Nam" autofocus>
</div>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="mob" id="mob" >
<option>{{ customer.sponsor }}</option>
{% for i in sponsor %}
<option value="{{ i.mobile }}"> {{ i.mobile|add:' - '|add:i.name }} </option>
{% endfor %}
</select>
<div class="invalid-feedback">
Please select a valid Existing Customer.
</div>
</div>
<div class="mb-3">
<input type="submit" value="Search"/>
.
.
...
In your form, you write a button as:
Search
But this thus means that this is just a link that links to a new page. As a result, the browser will make an (empty) GET request to the given url, and never submit the form.
You can construct a button that submits the form with:
<form class="form-signin" action="{% url 'customer_view' %}" method="post">
<!-- … -->
<button type="submit" class="btn btn-primary btn-sm" role="button">Search</button>
<!-- … -->
</form>
That being said, a search is often done with a GET request, so you might want to change method="get", and obtain the parameters through request.GET.get(..) instead.
I am having problem to get the selected data from a form. Here is my form
<form action="#" method="GET">
{% csrf_token %}
<select name="country" id="selectcountries" class="custom-select">
<option>Select country</option>
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="city" id="selectcities" class="custom-select">
<option>Select city</option>
</select>
<select class="custom-select" name="option" >
<option selected> Tourist Spot </option>
<option> Hotel </option>
<option> Restaurent </option>
</select>
<button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i> Search </button>
</form>
And my views.py is
def advanceSearch(request):
country = request.GET.get('country')
city = request.GET.get('city')
option = request.GET.get('option')
if request.method == "GET" :
if country:
message = 'q= %s' % country
else:
message = 'Empty'
else:
message = 'oops'
return HttpResponse(message)
HTTPResponse always give me empty message even after with passing values by the form. I want to get the data from this form but i cant.
I tried to replicate the scenario with the provided code, and I think your search view is not getting executed. You have provided {% url 'advanceSearch' %} in the anchor tag inside button. It should be in the action attribute of the form.
<form action="{% url 'advanceSearch' %}" method="GET">
{% csrf_token %}
<select name="country" id="selectcountries" class="custom-select">
<option>Select country</option>
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="city" id="selectcities" class="custom-select">
<option>Select city</option>
</select>
<select class="custom-select" name="option" >
<option selected> Tourist Spot </option>
<option> Hotel </option>
<option> Restaurent </option>
</select>
<button type="submit" class="btn tour-btn"><i class="fa fa-search pr-2" aria-hidden="true"></i>Search</button>
</form>
I have the following code below, which would be the editing of a form of a request I made here for my work, as I had to change some of the views my update has to be manual, and the select field is not getting the result that I'm bringing it from the db, all fields are working except the select.
as it is now ||| as should be
class EditPedido(View):
def get(self, request, venda):
data = {}
venda = fixa.objects.get(id=venda)
data['filial'] = venda.regional
return render(request, 'fixa/fixa_update.html', data)
<select name="filial" class="select form-control" required="" id="filial">
<option value="" selected="">---------</option>
{% for filial in filiais %}
<option value="{{ filial.id }}">{{ filial.nome }}</option>
{% endfor %}
</select>
EDIT
class EditPedido(View):
def get(self, request, venda):
empresa_logada = request.user.funcionario.empresa
data = {}
data['filiais'] = empresa.objects.filter(nome=empresa_logada)
venda = fixa.objects.get(id=venda)
data['filial'] = venda.regional
return render(request, 'fixa/fixa_update.html', data)
<select name="filial" class="select form-control" required="" id="filial">
<option value="" selected="">---------</option>
{% for filial in filiais %}
<option value="{{ filial.id }}">{{ filial.nome }}</option>
{% endfor %}
</select>
<form method="POST" action="{% url 'create_fixa' %}">
{% csrf_token %}
<h2>number do Pedido: {{ sell.number }}</h2>
<p><font color="RED">{{MSG}}</font></p>
<hr>
<br>
<div class="form-row">
<div class="form-group col-md-3 mb-0">
<label for="number">Nº da Simulação</label>
<input type="text" name="number" class="form-control" value="{{number}}" required="">
</div>
<div class="form-group col-md-9 mb-0">
<label for="razao">Razão Social</label>
<input type="text" name="razao" class="form-control" value="{{razao}}" required="">
</div>
</div>
<br>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label for="razao">CNPJ</label>
<input type="text" name="cnpj" class="form-control" data-mask="00.000.000/0000-00" value="{{cnpj}}" required="">
</div>
<div class="form-group col-md-6 mb-0">
<label for="tipo">TIPO</label>
<select name="tp_cli" class="select form-control" required="" id="tp_cli">
<option value="" selected="">---------</option>
<option value="FRESH">FRESH</option>
<option value="BASE">BASE</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label for="razao">Filial</label>
<select name="filial" class="select form-control" required="" id="id_regional">
{% for filial in filiais %}
<option value="{{filial.id }}">{{ filial.nome }} {% if filial.id == filial %}selected{% endif %}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-6 mb-0">
<label for="tipo">Indicação</label>
<select name="indicacao" class="select form-control" id="indicacao">
<option value="" selected="">---------</option>
{% for indicacao in indicaoes %}
<option value="{{ indicacao.id }}">{{ indicacao.nm_primeiro_nome }} {{indicacao.nm_segundo_nome}}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-6 mb-0">
<label for="tipo">Status</label>
<select name="status" class="select form-control" id="status">
<option value="" selected="">---------</option>
{% for statu in status %}
<option value="{{ statu.id }}">{{ statu.nome_st }}</option>
{% endfor %}
</select>
</div>
</div>
<br>
<input type="hidden" value="{{sell.id}}" name="sell_id">
<button type="submit" class="btn btn-success">Salvar</button>
</form>
class EditOrder(View):
def get(self, request, sell, *args, **kwargs):
company_entered = request.user.employee.company
parent_company = request.user.employee.company.company_pai
data = {}
data['status'] = tb_status.objects.all()
sell = fixa.objects.get(id=sell)
if parent_company:
data['filiais'] = company.objects.filter(nome=company_entered)
data['indicaoes'] = employee.objects.filter(cargo__nome='Vendedor', company__nome=company_entered)
else:
data['filiais'] = company.objects.filter(nome=company_entered) | company.objects.filter(
company_pai=company_entered)
data['indicaoes'] = employee.objects.filter(cargo__nome='Vendedor')
data['number'] = sell.number
data['razao'] = sell.nm_razao
data['cnpj'] = sell.nr_cnpj
data['tp_cli'] = sell.tipo_cli
data['filia'] = sell.regional_id
data['indicacao'] = sell.indicacao
data['sell'] = sell
data['family'] = tb_tp_prod.objects.all()
data['type'] = tb_tipo_servico.objects.all()
data['qtds'] = tb_qtd.objects.all()
data['itens'] = sell.itemdopedido_set.all()
return render(request, 'fixa/fixa_update.html', data)
So this is what you had in your last comment (I don't know where the space before the words in the third and fourth options are coming from, but perhaps you should remove them)
<select name="filial" class="select form-control" required="" id="filial">
<option value="" selected="">--------</option>
<option value="1">TESTE</option>
<option value="2"> SOROCABA</option>
<option value="5"> MARILIA</option>
</select>
You have the 1st option selected, which is --------. I think you want this
<select name="filial" class="select form-control" required="" id="filial">
<option value="1">TESTE</option>
<option value="2"> SOROCABA</option>
<option value="5" selected=""> MARILIA</option>
</select>
You will have to indicate to the template which option to select, you could pass this as a variable something like
data['selection'] = 5
Then in the template
<option value="{{ filial.id }}" {% if filial.id == selection %}selected=""{% endif %}>{{ filial.nome }}</option>
I'm not certain about the syntax of the {% if filial.id == selected %} statement. I don't use it much but the idea is to just put the tag in the option that requires it.
I'm really stuck on this one. I have a working view/template that has a form select option that populates options from my model
views.py
def random(request):
classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block')
classblock = request.GET.get('class_block')
students = Student.objects.all().filter(classroom__course_block=classblock)
nicknames = [s.nickname for s in students]
data = serializers.serialize("json", students, fields = ("nickname", "attend"))
student_names = json.dumps(list(nicknames))
context = {'students': students}
context['classroom'] = classroom
context['student_names'] = student_names
context['data'] = data
template = loader.get_template('randomizer/randomize.html')
print (data)
return render(request, 'randomizer/randomize.html', context)
ramdomize template
{% extends 'randomizer/base.html' %}
{% load static %}
{% block body %}
<div id="djangorandom">
{{ classroom.id }}
<form action="{% url 'randomizer:random' %}" method="get">
{% csrf_token %}
<div class="form-group">
<select class="form-control" name="class_block">
{% for room in classroom %}
<option value={{ room.course_block }}>{{ room.get_course_block_display }}</option>
{% endfor %}
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
</div>
Page source returns:
<div class="form-group">
<select class="form-control" name="class_block">
<option value=11>Block 1-1</option>
<option value=13>Block 1-3</option>
<option value=14>Block 1-4</option>
<option value=P13>Pair 1-3</option>
</select>
</div>
Now I've copied a lot of this code for a slightly different template and purpose:
def pair(request):
classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block')
classblock = request.GET.get('class_block')
students = Student.objects.all().filter(classroom__course_block=classblock)
nicknames = [s.nickname for s in students]
data = serializers.serialize("json", students, fields = ("nickname", "attend"))
student_names = json.dumps(list(nicknames))
context= {'classroom': classroom}
context['students'] = students
context['student_names'] = student_names
context['data'] = data
template = loader.get_template('randomizer/pairing.html')
print(data)
return render(request, 'randomizer/pairing.html')
{% extends 'randomizer/base.html' %}
{% load static %}
{% block body %}
<div id="djangorandom">
{{ classroom.id }}
<form action="{% url 'randomizer:pair' %}" method="get">
{% csrf_token %}
<div class="form-group">
<select class="form-control" name="class_block">
{% for room in classroom %}
<option value={{ room.course_block }}>{{ room.get_course_block_display }}</option>
{% endfor %}
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
</div>
But the page source doesn't show any of the options for the form selects:
<form action="/randomizer/pairing/" method="get">
<input type='hidden' name='csrfmiddlewaretoken' value='ADVUsnTserljrnDvRlmeTPyvjMOzva5xj7t8LSeDmPxnkBUtx4XmfXAI5aRfJky6' />
<div class="form-group">
<select class="form-control" name="class_block">
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
I've practically copied everything from the first view/template to the second view/template. I wondered if there was a scope issue where def pair re-uses the code from def random, but I commented out def random and that didn't help.
Your second view doesn't pass the context into the render() call, so there is no classroom variable and nothing to iterate over in the template.
(Note, in both views the template = loader.get_template(...) call is irrelevant and not used; you should remove those lines.)