django template - html

I have a drop-down list
In my template,
<form name="languages" method="post">
<select id="langSelect" onchange="showDiv(this.value);">
<option>en (default)</option>
{% for ele in comments.languages.all %}
<option>{{ele.lang}}</option>
{% endfor %}
</select>
<div><a onclick="getIndex()">Submit</a></div>
</form>
Javascript:
function getIndex(){
var x = document.getElementById("langSelect").selectedIndex;
}
In the html:
{{obj.comments.all.index.value}}
How can I get the value of index from getIndex() and pass it back to django template
obj.comments[index].value and index = getIndex()
{{obj.comments.all.index.value}}?
Thanks.

check this link, you can use the forloop.counter0 and drop completely the getIndex() javascript function
i don't know exactly what you need, but you can then do something like
{{ c.comments.all.index.text forloop.counter0 }}
aka: pass the forloop.counter0 value to what you need
nb: i know nothing about {{c.comments.all.index.text}} so maybe my syntax won't work, you have to adapt it to your real usecase

Related

Datalist tag not working on making changes in HTML file related to Django

I am working on a task where I have to make a drop-down box with search filter.
Here:-
What is happening here is after selecting Fiscal year, it is displaying Annual work plan for the user according to that (after filtering).
But it is displaying the drop down only, what I want is it should display the drop down with a filterbox too.
In forms.py, select annual work plan is as follows:-
Select_Annual_Work_Plan = forms.ModelChoiceField(queryset=annual_work_plan.objects.none().order_by("Annual_Work_Plan_ID"), label='Select Annual Work Plan', )
-> Its a ModelChoiceField.
This is the function in views.py as ajax_load_Select_Annual_Work_Plan, by which we are rendering the html to display the dropdown, function is as follows:-
#login_required()
def ajax_load_Select_Annual_Work_Plan(request):
Fiscal_year_val = request.GET.get("Fiscal_year")
Select_Annual_Work_Plan_list = annual_work_plan.objects.filter(Fiscal_year = Fiscal_year_val).order_by("Annual_Work_Plan_ID")
return render(request, "procurement_data/Select_Annual_Work_Plan_dropdown_list_options.html", {"Select_Annual_Work_Plan_list": Select_Annual_Work_Plan_list})
Select_Annual_Work_Plan_dropdown_list_options.html file is as follows(This is the complete code of this file):-
{% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %}
<option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option>
{% endfor %}
I tried datalist tag of the html, which is basically used for the dropdown with search box but that is not working here as:-
<div>
<datalist id="suggestions">
{% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %}
<option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option>
{% endfor %}
<input autoComplete="on" list="suggestions"/>
</datalist>
</div>
I tried some jQuery solutions too...but nothing is working.
Can anyone help here?

How to modify AJAX request so that the empty dependent drop-down is hidden when page loads?

I have a form that has a dependent drop-down. Currently, it displays the main drop-down and the dependent one when the page loads, and when you select a "Work Area" that does not have a "Station", then the station drop-down disappears from the page.
What I'm trying to achieve is hiding the Station drop-down when the page first loads, and only have it show when a Work Area that does have Stations is selected. How could I modify the AJAX request (or the html tags, not sure where the change would have to occur) so that it is hidden from the beginning?
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_work_area").change(function () {
var url = $("#warehouseForm").attr("data-stations-url");
var workAreaId = $(this).val();
$.ajax({
url: url,
data: {
'work_area': workAreaId
},
success: function (data) {
$("#id_station_number").html(data);
// Check the length of the options child elements of the select
if ($("#id_station_number option").length == 1) {
$("#id_station_number").parent().hide(); // Hide parent of the select node
} else {
// If any option, ensure the select is shown
$("#id_station_number").parent().show();
}
}
});
});
</script>
{% endblock main %}
station_number_dropdown_options.html
<option value="">---------</option>
{% for station in stations %}
<option value="{{ station.pk }}">{{ station.name }}</option>
{% endfor %}
Not sure if this part is necessary, but just in case:
views.py
def load_stations(request):
work_area_id = request.GET.get('work_area')
stations = Station.objects.filter(work_area_id=work_area_id).order_by('name')
return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations})
Hide your div initially.
<div id="my-hidden-div" style="display:none">
<label>Station</label>
{{ form.station_number }}
</div>
then in your ajax method :
success: function (data) {
$("#my-hidden-div").show(); // show it
$("#id_station_number").html(data);
// Check the length of the options child elements of the select
if ($("#id_station_number option").length == 1) {
$("#id_station_number").parent().hide(); // Hide parent of the select node
} else {
// If any option, ensure the select is shown
$("#id_station_number").parent().show();
}
}
or make an css rule
#id_station_number {display:none}
then show it in the success like this
$("#id_station_number").show();

Add form choices as options in a select tag html

I'm in my final project and I'm a little bit lost on what I'm doing now.
I'm developping a website and I need to insert some choices into a html select tag, I mean, that choices must be options of this select tag. I'm trying it, but the dropdown doesn't appear as it should, and, when I try to submit my form, it gives me an error. I wish you could help me, I'm becoming crazy. Here I leave my code, feel free to ask anything you want
forms.py
class FormCancion(forms.ModelForm):
NOTAS_CHOICES=(('35','Acoustic Bass Drum'),('36','Bass Drum 1'),('37','Side Stick'),('38','Acoustic Snare'),('39','Hand Clap'),
('40','Electric Snare'),('41','Low Floor Tom'),('42','Closed Hi Hat'),('43','High Floor Tom'),('44','Pedal Hi-Hat'),
('45','Low Tom'),('46','Open Hi-Hat'),('47','Low-Mid Tom'),('48','Hi-Mid Tom'),('49','Crash Cymbal 1'),('50','High Tom'),
('51','Ride Cymbal 1'),('52','Chinese Cymbal'),('53','Ride Bell'),('54','Tambourine'),('55','Splash Cymbal'),
('56','Cowbell'),('57','Crash Cymbal 2'),('58','Vibraslap'),('59','Ride Cymbal 2'),('60','Hi Bongo'),('61','Low Bongo'),
('62','Mute Hi Conga'),('63','Open Hi Conga'),('64','Low Conga'),('65','High Timbale'),('66','Low Timbale'),('67','High Agogo'),
('68','Low Agogo'),('69','Cabasa'),('70','Maracas'),('71','Short Whistle'),('72','Long Whistle'),('73','Short Guiro'),
('74','Long Guiro'),('75','Claves'),('76','Hi Wood Block'),('77','Low Wood Block'),('78','Mute Cuica'),('79','Open Cuica'),
('80','Mute Triangle'),('81','Open Triangle'))
nota_pad_gris = forms.ChoiceField(choices=NOTAS_CHOICES, widget=forms.Select())
views.py:
def crearCancion(request):
cancion=Cancion()
if request.method=="POST":
formulario=FormCancion(request.POST,request.FILES,instance=cancion)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/ListadoCanciones/')
else:
formulario=FormCancion()
context={'formulario':formulario}
return render(request,"nuevaCancion.html",context)
.html:
<br><br><br>
<div class="container">
<form id='formulario' method='post' {% if formulario.is_multipart %} enctype="multipart/form-data" {% endif %} action=''>
{% csrf_token %}
<center>
<label for="nota_pad_gris">Nota del pad Gris:</label>
<select id="nota_pad_gris" onchange="validar();">
{% for value in formulario.nota_pad_gris %}
<option value="hola">{{ value }}</option>
{% endfor %}
</select>
<br><br>
<p><input type='submit' class="btn btn-success btn-lg" value='AƱadir'/>
Cancelar</p>
</center>
</form>
<br>
</div>
Edit:
Look at Nota del pad gris. This is what the list shows. It shows the choices, but also shows a blank space between the choices.
[
This is the error that the web gives me when I try to submit the form

Django : HTML form action directing to view (or url?) with 2 arguments

Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment...
models.py
class data(models.Model):
course = models.CharField(max_length = 250)
def __str__(self):
return self.course
html
Converted the objects in models.course to schlist
<link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %} method="GET">
<div>
<h4 style="font-family:verdana;">First Course: </h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<div>
<h4 style="font-family:verdana;">Second Course:</h4>
<select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
<option value=""></option>
{% for item in schlist %}
<option> {{ item }} </option>
{% endfor %}
</select>
</div>
</br>
<input type="submit" value="Compare!" />
</form>
urls.py (having my doubts if this works..)
urlpatterns = [
url(r'^(\d+)/(\d+)$',views.process, name = 'process'),
]
view.py
def process(request,q1 ,q2):
obj1= get_object_or_404(Schdata, course = q1)
obj2= get_object_or_404(Schdata, course = q2)
........
Was wondering if it is possible for the form action to direct the action to
(1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected?
If so how should the form action be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML?
Directing to views.py:
User input is CharField, could use get_object_or_404 to get the model pk. However when defining my urls.py I would get a Noreverse error as my url arguments is the primary key.
Directing to urls.py:
Url arguments is primary key. From the way I see it, I need to magically convert my User input Charfield to a pk before passing it to urls.py
Is there a (or) function for get() in django? E.g get_object_or_404(pk = q1 or course = q1)?
Would really appreciate any advice. Been staring at this for hours.
You are trying to use the reverse resolution of urls in Django.
In your html file correct form action url to the following and method should be POST:
<form action={% url 'process' %} method="POST">
In case you are trying to pass parameters along then use this:
<form action={% url 'process' request.user.id 4 %} method="POST">
Reference:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Yes i'm late but it can help others for better understanding how Django processes the request.
Django 3.0 pattern
How Django processes the request
Basic :
First Django check the matching URL.
If URL is matched then calling the defined view to process the request. (Success)
If URL not matched/found the Django invokes error Page Not Found
In detail reading :
Official Django Documentations How Django processes a request
These are your URL patterns :
urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]
Third argument in urlpatterns is for if you want to change the url pattern from current to this :
urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]
You don't need to redefine url pattern in all Templates where you using url name.
For Example :
This is my template profile.html where i used the url name instead of hard coded url.
<a class="item" href="{% url 'editprofile' user.id %}" >Edit profile </a>
Solution of your problem :
.html
Only use url name instead of hard coded url in your templates and pass arguments.
<form action={% process no_of_arguments %} method="POST">
views.py
Here you can process your request
def process(request,no_of_arguments):
Become good django developer
You can also use Django ModelForms for your model.
Using model forms or simple form you can do multiple things
Modular approach
Write server side validation in related form instead of doing in views.py
Readable code - Clean code

Create hyperlink in django template of object that has a space

I am trying to create a dynamic hyperlink that depends on a value passed from a function:
{% for item in field_list %}
<a href={% url index_view %}{{ item }}/> {{ item }} </a> <br>
{% endfor %}
The problem is that one of the items in field_list is "Hockey Player". The link for some reason is dropping everything after the space, so it creates the hyperlink on the entire "Hockey Player", but the address is
http://126.0.0.1:8000/Hockey
How can I get it to go to
http://126.0.0.1:8000/Hockey Player/
instead?
Use the urlencode filter.
{{ item|urlencode }}
But why are you taking the name? You should be passing the appropriate view and PK or slug to url which will create a suitable URL on its own.
Since spaces are illegal in URLs,
http://126.0.0.1:8000/Hockey Player/
is unacceptable. The urlencode filter will simply replace the space with %20, which is ugly/inelegant, even if it does kind of get the job done. A much better solution is to use a "slug" field on your model that represents a cleaned-up version of the title field (I'll assume it's called the title field). You want to end up with a clean URL like:
http://126.0.0.1:8000/hockey_player/
To make that happen, use something like this in your model:
class Player(models.Model):
title = models.CharField(max_length=60)
slug = models.SlugField()
...
If you want the slug field to be pre-populated in the admin, use something like this in your admin.py:
class PlayerAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
....
admin.site.register(Player,PlayerAdmin)
Now when you enter a new Player in the admin, if you type "Hockey Player" for the Title, the Slug field will become "hockey_player" automatically.
In the template you would then use:
{% for item in field_list %}
<a href={% url index_view %}{{ item.slug }}/> {{ item }} </a> <br>
{% endfor %}
There is this builtin filter .
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlencode
Although you should be using one of these
http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield