change value form after press button (django) - html

I have a form where when I select my option and press the "Select" button I need to update the form with the data of my selected object. My problem is that when I do my static object the {% for%} already marks me an error because it is not a list. I do not know if this is the correct way to do it.
This is running Mysql, django 1.11 and python 2.7.15
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
competencias = Competencias.objects.all()
context = {
'alumno': alumno,
'mapa': mapa,
'competencias': competencias
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
context = {'alumno': alumno}
return render(request, 'competencias_app/competencias.html', context)
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
the output when press "seleccionar" is
Request Method: POST
Request URL: http://localhost:8000/seleccion
Django Version: 1.11.21
Exception Type: TypeError
Exception Value:
'Alumnos' object is not iterable
Images for more details

I solve my problem with one if, i don't know if is the correct solution but works!
competencias.html
<form action="/seleccion" method="POST">
{% csrf_token %}
<div>
<select id="carrera" name="Carrera">
<option value="1">TICS</option>
<option value="2">Carrera</option>
<option value="3">Carrera</option>
<option value="4">Carrera</option>
<option value="5">Carrera</option>
</select>
</div>
<div>
<select id="Alumno" name="Nombre">
{% if alumno|length > 1 %}
{% for alumno in alumno %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{% endfor %}
{% else %}
<option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option>
{%endif%}
<input type="submit" name="Seleccionar">
</select>
</div>
<label for="ID">ID</label>
<input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br>
<label for="apellidos">Apellidos</label>
<input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br>
<label for="Correo">Correo</label>
<input type="input" name="Correo" disabled value="{{alumno.correo}}"><br>
</form>
views.py
def administrador(request):
alumno = Alumnos.objects.all()
mapa = mapas.objects.all()
context = {
'alumno': alumno
}
return render(request, 'competencias_app/competencias.html', context)
def seleccion(request):
lstCompetencias = []
alumno = Alumnos.objects.get(pk=request.POST['Nombre'])
for p in Competencias.objects.raw('Select * from test_app_competencias where idmapasfk_id = %s', [request.POST['Nombre']]):
lstCompetencias.append(p)
context = {
'alumno' : alumno,
'competencias' : lstCompetencias
}
return render(request, 'competencias_app/competencias.html', context)

Related

HTML form with post method sent get request

I had a form which used post method. However, after I clicked sumbmit, only get request was sent. Can I please know why?
<form action="/review_page/{{yelp_id}}" method=post>
<label for="review-score">Your overall rating of this restaurant</label>
<select name="score" id="review-score">
{% for num in range(1,6) %}
<option value="{{ num }}">{{ num }}</option>
{% endfor %}
</select>
<div>
<label for="review-title">Title of your review</label><br>
<input type="text" name="title" id="review-title">
</div>
<div>
<label for="reviewText">Your review</label>
<div>
<textarea name="review" id="reviewText" data-minlen="100" data-maxlen="20000"
placeholder="Tell people about your experience"></textarea>
</div>
</div>
<input type="submit" value="Submit Your Review">
</form>
Please also find my routes below.
#app.route("/review_page/<yelp_id>", methods=["POST"])
def save_user_review(yelp_id):
"""Save user review into database"""
user_id = session.get("user_id")
print(user_id)
if user_id is None:
flash("Please log in to leave a review")
return redirect(f"/review_page/{yelp_id}")
else:
user = User.query.get(session["user_id"])
title = request.form.get("title")
score = int(request.form.get("score"))
review = request.form.get("review")
yelp_id = yelp_id
rating = crud.create_rating_without_pic(user, title, score, review, yelp_id)
db.session.add(rating)
db.session.commit()
return redirect(f"/rest_details/{yelp_id}")
Maybe is it.
You have this
<form action="/review_page/{{yelp_id}}" method=post>
And probably you should have this
<form action="/review_page/{{yelp_id}}" method="post">

Extracting data using ajax from a database in django and then display it in view

How should I extract data from a database using ajax in Django and display it in view in the form of charts. I wanna select items from dropdown options and then display those selected data in the webpage in the form of charts.
Can anyone please guide me in this.
My codes are:
index.html:
<div class="row">
<form class="form-row" action="{{ }}" method="post">
{% csrf_token %}
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select Major Head</option>
{% for major in majors %}
<option value="{{ major.pk }}">{{ major.pk }}: {{ major.description } </option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<input type="submit" value="Display">
</div>
</form>
</div>
.
.
.
<div class="card-body" >
<div id="chart">
<embed type="image/svg+xml" src= {{ chart|safe }} />
</div>
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 )
charts.js
$('form').on('Display',function(e){
e.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
success : function(data) {
// $(".printArea").empty().append(data).css('visibility','visible');
return data;
}
});
});

How can I get value of input tag type hidden to ngModel?

I tried to get value of input tag but I always receive name of asset. Anyone can help me? Thanks very much.
<select class="form-control" [(ngModel)]=id name="assetID">
<option *ngFor="let asset of arrAssets" selected>
<input type="hidden" value="{{ asset.Id }}" name="id">
{{ asset.Name }}
</option>
</select>
You can do it by using (input) on your <input> element like:
<select class="form-control" [(ngModel)]=id name="assetID">
<option *ngFor="let asset of arrAssets; let i = index;" selected>
<input type="hidden" (input)="inputChanged($event , i)" value="{{ asset.Id }}" name="id">
{{ asset.Name }}
</option>
</select>
I have add the i as index in case you want to detect each input on its own
Moving to .ts file
export class Home {
constructor(){}
inputChanged(eve, i) {
console.log(eve.target.value); // This should print the value of input element
console.log(i); // This should print the index of input element which has changed
}
}

Django form using bootstrap

I have the following dictionary:
POSSIBLE_POSITIONS = (
('1', 'Brazo'),
('2', 'Muñeca'),
('3', 'Pierna'),
('4', 'Pie'),
)
This is used in the following form:
from interface.positions import *
from django import forms
class PositionForm(forms.Form):
position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select())
This is the view that renders my html template:
def add(request):
return render(request, 'interface/add_user.html', {'device_list': Device.objects.all(), 'form': PositionForm()})
And this is the html code:
<body>
<form class="square" action="{% url 'interface:add_perform' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>ID paciente</label>
<input autofocus class="form-control" name="user_id" placeholder="Ejemplo: 58192">
</div>
<div class="form-group">
<label>Dispositivo a usar</label>
<select name="device_id" class="form-control">
{% for device in device_list %}
<option>{{ device.id }}</option>
{% endfor %}
<option selected="selected"> Sin dispositivo </option>
</select>
</div>
<div class="form-group">
<label>Posición dispositivo</label>
<div class="form-control"> {{ form }} </div>
</div>
<div class="form-group square_button">
<button class="btn btn-success btn-md form-control" type="submit"> Crear Paciente </button>
</div>
</form>
</body>
The problem is that as you can see on the following image, this isn't bootstrap css, so it is really weird. How I can fix that?
I want it like the 'Dispositivo a usar' selector.
SOLVED
I found the solution here: Define css class in django Forms
Loop through form object and set the form-control class in select tag. It should work.
def __init__(self, *args, **kwargs):
super(PositionForm, self).__init__(*args, **kwargs)
self.fields['position'].widget.attrs['class'] = 'form-control'
Can be solved adding the css class directly on the form:
class PositionForm(forms.Form):
position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select(
attrs={
'class': 'form-control'
}
))

Retain select option value after submit in Django

I am not using Ajax or django forms. I have plain HTML select tag inside the form tag and sending the selected option value in my view. I want to retain the select option value after the submission. Currently, it comes to default value of 1 irrespective of my selection. Help would be appreciated.
Here is my template code:
<form method = "post" action = "{% url 'index' %}">
{% csrf_token %}
<label class="mainlbl">Vega</label>
<select name = "drop1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<input class="btn btn-ocean btn-side-bar" type = "submit" value="Submit">
</form>
Here is my view for that:
def index(request):
if request.method == "POST":
vega = request.POST['drop1']
vega = int(vega)
gvo = GVOptimize('NSE', 'Nifty')
data = gvo.get_optimal_strategies(vega)
str1 = None
for i in range(0, len(data)):
if i == 0:
str1 = data[i]
elif i == 1:
str2 = data[i]
elif i == 2:
str3 = data[i]
elif i == 3:
str4 = data[i]
else:
break
context_dict = {'str1': str1, 'str2': str2, 'str3': str3, 'str4': str4 'vega': vega}
return render(request, 'demo/dashboard.html', context_dict)
else:
context_dict = {}
return render(request, 'demo/dashboard.html', context_dict)
If you really insist on having a hacky way of maintaining the selected option you can change your form to check every option to see if it equals the number you pass back in your context
<form method = "post" action = "{% url 'index' %}">
{% csrf_token %}
<label class="mainlbl">Vega</label>
<select name = "drop1" >
{% for idx in "useaformpls!" %}
<option value="{{ forloop.counter }}" {% if context_val == forloop.counter %}selected {% endif %}>
{{ forloop.counter }}
</option>
{% endfor %}
</select>
<input class="btn btn-ocean btn-side-bar" type = "submit" value="Submit">
</form>
Where context_val equals the index you pass back in the context data of your view.
this answer is here only, because this is not how it should be resolved!
you are using Django, so use Forms that are dedicated for such a use, there are many reasons why to use them, but there are few that matters:
simple code
straight-forward use of forms with generic views
data validation (yes, you do not need to check if this is an integer, or if somebody is hacking your page and posting value outside of range that is in your select)
data escape - yes, no more stupid security holes
validation tied to form elements, allowing to resubmit data and display to the user where is exactly an error
and don't tell me that this is more work...
forms.py
class MyForm(forms.Form):
drop1 = forms.IntegerField('Vega', choices=[(x,x) for x in range(1, 13)])
views.py
def index(request):
context_dict = {}
if request.method == "POST":
form = MyForm(data=request.POST)
if form.is_valid():
vega = form.cleaned_data['drop1']
gvo = GVOptimize('NSE', 'Nifty')
data = gvo.get_optimal_strategies(vega)
(str1, str2, str3, str4) = data[:4]
context_dict = {'str1': str1, 'str2': str2,
'str3': str3, 'str4': str4 'vega': vega}
else:
form = MyForm()
context_dict['form'] = form
return render(request, 'demo/dashboard.html', context_dict)
dashboard.html
{% if form.is_valid %}
<p>Vega: {{ vega }}</p>
{% else %}
<form method="post" action="{% url 'index' %}">{% csrf_token %}
{{ form }}
<input class="btn btn-ocean btn-side-bar" type="submit" value="Submit">
</form>
{% endif %}
I am not sure if this is a good practice but you may try creating a function in your view.
def send_selected_combo(self):
value_from_select = self.request.GET.get('select_html')
return value_from_select
Then in your template you can call the function.
<select name="select_html" selected="id_selector">
<option value="combo_value" {%if.view.send_selected_combo=="combo_value"%} selected {%endif%}></option>
</select>
<select name = "drop1" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
When you submit the form in views.py you can use
selected_value = request.POST.get("drop1"); // If incase you are using get method which you shouldn't then use request.GET.get("drop1")