Display QuerySet result as Array - javascript

I'm asking a question about my HTML template. I displayed results from some QuerySet with Django and I would like to modify the display user aspect.
I don't know if I can make this kind of things with Django or if JavaScript lets to make that.
I have an HTML template :
<h2 align="center"> Affichage de toutes les fiches individuelles </align> </h2>
<br></br>
{% block content %}
<h4> Récapitulatif des 10 dernières fiches individuelles créées: </h4>
<ul>
{% for item in identity %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<h4> Récapitulatif des 10 dernières fiches individuelles créées habitant en France: </h4>
<ul>
{% for item in identity_France %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endblock %}
From this view :
def Consultation(request) :
identity = Identity.objects.all().order_by("-id")[:10] #Les 10 dernières fiches créées
identity_France = Identity.objects.filter(country='64').order_by("-id")[:10] #Les 10 dernières fiches où la personne habite en France
context = {
"identity" : identity,
"identity_France" : identity_France,
}
return render(request, 'resume.html', context)
Is it possible to display the result as an array ? With column, tags for each column etc ... ?
Something like that :
Thank you !
EDIT :
I found that JQuery makes that : JQuery Array

You can do whatever you want inside {% for %} {% endfor %} template tags.
like, you could put your objects inside a table
<table>
<thead>
<tr>
<th>Field 1 Name</th>
<th>Field 2 Name</th>
</tr>
</thead>
<tbody>
{% for item in identity_France %}
<tr>
<td>{{ item.field1 }}</td>
<td>{{ item.field2 }}</td>
<tr>
{% endfor %}
<tbody>
</table>

Related

Django dynamic formset only saving last entry

I have created a page where users can enter details to forms relating to a parent model (Patient) and two child models (CurrentMed and PastMed) linked to that parent.
Both the child forms use dynamic formsets where the user can add or delete rows to the form. My problem is only the last row of the currentmed and pastmed formsets is saving to my database when the user submits the form?
models.py
class Patient(TimeStampedModel):
# get a unique id for each patient - could perhaps use this as slug if needed
patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False)
name = models.CharField("Patient Name", max_length=255)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True,
on_delete=models.SET_NULL)
class Med(TimeStampedModel):
med_name = models.CharField(“med name“, max_length=20)
dose = models.IntegerField("Dose (mg)", default=0)
timepoint = models.CharField(
"timepoint", max_length=20,
choices=[('current','current'), ('past', 'past')], default='unspecified')
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
class Meta:
abstract = True
class CurrentMed(Med):
timepoint = models.CharField(
"", max_length=20,
choices=[('current','current'), ('past', 'past')], default='current')
class PastMed(Med):
timepoint = models.CharField(
"", max_length=20,
choices=[('current','current'), ('past', 'past')], default='past')
forms.py
from .models import CurrentMed, PastMed, Patient
CurrentmedFormSet = inlineformset_factory(
Patient, CurrentMed, fields=("med_name", "dose",), extra=2)
PastmedFormSet = inlineformset_factory(
Patient, PastMed, fields=("med_name", "dose",), extra=2)
class PatientForm(ModelForm):
class Meta:
model = Patient
fields = ['name', 'sex', 'age', 'diagnosis']
views.py
class PatientAddView(LoginRequiredMixin,TemplateView):
model = Patient
template_name = "../templates/patient/add.html"
def get(self, *args, **kwargs):
patient_form = PatientForm
currentmed_formset = CurrentmedFormSet(queryset=CurrentMed.objects.none())
pastmed_formset = PastmedFormSet(queryset=PastMed.objects.none())
return self.render_to_response({'currentmed_formset': currentmed_formset,
'pastmed_formset': pastmed_formset,
'patient_form': patient_form})
def post(self, *args, **kwargs):
form = PatientForm(data=self.request.POST)
currentmed_formset = CurrentmedFormSet(data=self.request.POST)
pastmed_formset = PastmedFormSet(data=self.request.POST)
if form.is_valid():
patient_instance = form.save()
if currentmed_formset.is_valid():
med_name = currentmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
if pastmed_formset.is_valid():
med_name = pastmed_formset.save(commit=False)
for med in med_name:
med.patient = patient_instance
med.save()
return redirect(reverse(
'patient:treatment_detail',
kwargs={"patient_id": patient_instance.patient_id}))
html
{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block javascript %}
<script type="text/javascript" src="{% static 'js/jquery/dist/jquery-1.3.2.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$(function() {
$('#currentmeds_table tbody tr').formset({
prefix: 'current_meds'
})
});
$(function() {
$('#pastmeds_table tbody tr').formset({
prefix: 'past_meds'
})
});
</script>
<style type="text/css">
.delete-row {
margin-left:5px;
}
</style>
{% endblock %}
{% block content %}
<div>
<div class="entry">
<form id="form" method="POST">
<h1>Patient Details</h1>
{% csrf_token %}
<h3>Demographics</h3>
{{patient_form}}
<h3>Current Medication</h3>
<table id="currentmeds_table" border="0" cellpadding="0" cellspacing="5">
<thead>
<tr>
<th scope="col">Medication</th>
<th scope="col">Dose</th>
</tr>
</thead>
<tbody>
{% for form in currentmed_formset %}
<tr id="{{ form.prefix }}-row"></tr>
<td>
{% for fld in form.hidden_fields %}{{ fld }}{% endfor %}
{% if form.instance.pk %}{{ form.DELETE }}{% endif %}
{{ form.med_name}}
</td>
<td>{{ form.dose }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{currentmed_formset.management_form}}
<h3>Past Medication</h3>
<table id="pastmeds_table" border="0" cellpadding="0" cellspacing="5">
<thead>
<tr>
<th scope="col">Medication</th>
<th scope="col">Dose</th>
</tr>
</thead>
<tbody>
{% for form in pastmed_formset %}
<tr id="{{ form.prefix }}-row"></tr>
<td>
{% for fld in form.hidden_fields %}{{ fld }}{% endfor %}
{% if form.instance.pk %}{{ form.DELETE }}{% endif %}
{{ form.med_name}}
</td>
<td>{{ form.dose }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{pastmed_formset.management_form}}
<button type="submit">Create Patient</button>
</form>
</div>
</div>
{% endblock %}
The prefixes in the javascript were incorrect, found the correct ones by looking at the html source, instead of
$('#currentmeds_table tbody tr').formset({
prefix: 'current_meds'
})
Should have been
$('#currentmeds_table tbody tr').formset({
prefix: 'currentmed_set'
})

Django: How can I delete specific records out of tables by using a view, a template and confirm in JavaScript in a django-template?

I have a model named Actie in models.py.
The context I passed: {'actie': Actie.objects.all(), 'user': request.user}
This is my template I rendered by a view:
{% for actie in actie %}
{% if actie.actie_gebruiker.id == user.id %}
<tr onclick="window.location.href={{ actie.id }}">
<td>{{ actie.id }}</td>
<td>{{ actie.actie_naam }}</td>
<td>{{ actie.actie_status.status_naam }}</td>
<td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td>
<td>{{ actie.actie_einddatum|date:"d-m-y" }}</td>
<td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td>
<td>{{ actie.actie_gebruiker }}</td>
</tr>
<a id="verwijderenButton" href="" onclick="bevestigVerwijdering({{ actie_id }});"><img class="icontje"
src="{% static 'MyApp/verwijderen.png' %}"></a>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
<script>
function bevestigVerwijdering(id) {
var actie_id = '{{ actie.id }}';
var antwoord = confirm("Weet u zeker dat u deze actie wilt verwijderen?");
if (antwoord == true) {
document.getElementById('verwijderenButton').href = 'verwijderen/' + id + '/';
alert(id);
alert(document.getElementById('verwijderenButton').href);
//window.location.href= 'verwijderen/' + id + '/';
}
}
</script>
Now what I want this code to do is that when I click on the image, that it deletes that specifc record out of the database.
It deletes nothing when I don't click on the first record but deletes the last record when I click on the first record.
This is my view:
def verwijderActie(request, id):
Actie.objects.filter(id=id).delete()
return HttpResponseRedirect('../../')
You are creating a list of elements with the same id, then, when you call the javascript function, it gets the first element with the called id.
I would make something like that:
{% for actie in actie %}
{% if actie.actie_gebruiker.id == user.id %}
<tr onclick="window.location.href={{ actie.id }}">
<td>{{ actie.id }}</td>
<td>{{ actie.actie_naam }}</td>
<td>{{ actie.actie_status.status_naam }}</td>
<td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td>
<td>{{ actie.actie_einddatum|date:"d-m-y" }}</td>
<td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td>
<td>{{ actie.actie_gebruiker }}</td>
</tr>
<a id="verwijderenButton_{{ actie.id }}" href="#" onclick="bevestigVerwijdering({{ actie.id }});return false;"><img class="icontje" src="{% static 'MyApp/verwijderen.png' %}"></a>
{% endif %}
{% endfor %}
<script>
function bevestigVerwijdering(id) {
var actie_id = id;
var antwoord = confirm("Weet u zeker dat u deze actie wilt verwijderen?");
if (antwoord == true) {
document.getElementById('verwijderenButton_'+id).href = 'verwijderen/' + id + '/';
alert(id);
alert(document.getElementById('verwijderenButton').href);
//window.location.href= 'verwijderen/' + id + '/';
}
}
</script>

How to get element id based on class name properly?

I am trying to get the id which is dynamically generated. I am using a class name to access it. If I click on the td item once, there is no alert. But when I click twice I will get the alert (for the first time). If I click on the second item, I get an alert two times. If on third, I get it three times and so on. What is the error?
My JavaScript code:
function myFunction() {
$('.task0').click(function() {
var x = $(this).data('id');
alert(x);
});
}
My HTML-Flask code:
<tbody>
{% set ns = namespace(num=1) %}
{% for task in tasklist %}
<tr>
<td>{{ ns.num }}</td>
<td class="task0" data-id="{{ task[0] }}"><a href="javascript:myFunction();" >{{ task[0] }}</a></td>
{% for i in range(1,task|count) %}
<td>{{ task[i] }}</td>
{% endfor %}
</tr>
{% set ns.num = ns.num+1 %}
{% endfor %}
</tbody>
You are calling the function twice. The .click you are using in jquery is already calls the function then your make the a tag call the JavaScript function as well. Remove the call to the function from the a tag
Every time you click on td you attach one more listener. you need to attach listner at once for all dynamically created elements.
remove javascript function call in your html part.
and change your javascript as below.
$(document).on(click, '.tasklink', function(e){
e.preventDefault();
var x = $(this).parents('td.task0').data('id');
alert(x);
})
<tbody>
{% set ns = namespace(num=1) %}
{% for task in tasklist %}
<tr>
<td>{{ ns.num }}</td>
<td class="task0" data-id="{{ task[0] }}"><a class="tasklink" href="#" >{{ task[0] }}</a></td>
{% for i in range(1,task|count) %}
<td>{{ task[i] }}</td>
{% endfor %}
</tr>
{% set ns.num = ns.num+1 %}
{% endfor %}
</tbody>

Problems using Ajax with Django

I am having problems trying to update a block of my site (which includes another templates) by issuing an Ajax call. The that needs to be updated works just fine, but the JS script that is inside that template does not work (before, I was just adding the full request to my template, but that caused to have twice the content of the parsed template, but JS scripts were working).
PD: I am kind new to JS and have some experience with Django (still just digging in the world of Web Apps development).
My template:
{% load staticfiles %}
<script>
$(document).ready(function() {
var current_item_id = null;
var current_item_title = null;
var selected_items = null;
// Selección en las tablas
$('.table tr').on('click', function() {
$(this).toggleClass('selected');
});
// Comportamiento del toolbar flotante
$('.table tr').on('click', function() {
selected_items = $('.selected');
current_item_id = $(this).attr('id');
current_item_title = $(this).attr('name');
if (selected_items.length === 0) {
$('.modify-big').attr('disabled', true);
$('.delete-big').attr('disabled', true);
}
else if (selected_items.length > 1) {
$('.modify-big').attr('disabled', true);
}
else {
$('.modify-big').attr('disabled', false);
$('.delete-big').attr('disabled', false);
}
});
});
</script>
<div id='notifications'>
{% if notifications %}
<table class="table">
<thead>
<tr>
<!--<th class="text-left table-id">ID del Item</th>-->
<th class="text-left">Item</th>
<th class="text-left">Link de descarga</th>
<th class="text-left">Plantilla</th>
</tr>
</thead>
<tbody class="table-hover">
{% for notification in notifications %}
<tr id='{{ notification.item_id }}' name='{{ notification.item_title }}'>
<!--<td class='text-left'>{{ notification.item_id }}</td>-->
<td class='text-left'>
<a class='tooltip-right' href='#' tooltip='Ver item'>
<img src="{% static 'images/icon_notification_details.png' %}">
</a>
{{ notification.item_title }}
</td>
<td class='text-left'>
{% if notification.download_link %}
<a href='{{ notification.download_link }}' target='_blank'>{{ notification.download_link }}</a>
{% else %}
---
{% endif %}
</td>
<td class='text-left'>{{ notification.email_template.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% if first_time %}
<p class='info-msg first-time'>Últimas notificaciones agregadas.</p>
{% else %}
<div class="pagination">
<span class='step-links'>
{% if notifications.has_previous %}
<button class='previous' onclick='search_notifications("", "{{ notifications.previous_page_number }}");'></button>
{% else %}
<button class='previous' disabled></button>
{% endif %}
<span class='current'>
Página {{ notifications.number }} de {{ notifications.paginator.num_pages }}
</span>
{% if notifications.has_next %}
<button class='next' onclick='search_notifications("", "{{ notifications.next_page_number }}");'></button>
{% else %}
<button class='next' disabled></button>
{% endif %}
</span>
</div>
{% endif %}
{% else %}
<p class="info-msg info">No se han encontrado notificaciones.</p>
{% endif %}
</div>
Ajax Call:
search_notifications = function(first_time=false, page=null) {
show_div_loader($('#notifications'));
$.ajax({
url: "{% url 'notifications_loader' %}",
data: {
'search_notifications_query': $('#search-notifications-query').val(),
'search_notifications_listing': $('#search-notifications-listing option:selected').val(),
'first_time': first_time,
'page': page,
},
success: function(data){
// Solo necesitamos actualizar la sección #notifications
data = $(data).filter('#notifications').html();
notifications.html(data);
hide_div_loader($('#notifications-container'));
}
});
};
My view:
def notifications_loader(request):
[...]
return render(request, 'notifications_search_result.html', {'notifications': notifications, 'first_time': first_time})
As you can see in the Ajax sucess function, I do:
data = $(data).filter('#notifications').html();
notifications.html(data);
Before, I was doing:
notifications.html(data);
This last one was adding twice the parsed template but JS script inside it were working.
What I am doing wrong?
Thanks in advance.
EDIT:
I don't know if is the best way, but I've added a 'container' to my code and just insert parsed themplate there:
In my main template:
<div id='notifications-container'>
<!--{% include 'notifications_search_result.html' %}-->
</div>
JS scripts are working again and I don't have twice the parsed template. Now, for I was reading I think this is not the best way to work with Django and Ajax or I am wrong? Maybe I just need to return the view as JSON and replace only the needed data?
Still I have doubs about Ajax+Django and best practices way.
Thanks.
When doing AJAX using Django I do it this way:
Define a route(view) that will serve your default template containing your ajax call script.
Add another route(view) for the ajax call:
def auto_complete(request):
# do some actions and put the results in var
return HttpResponse(simplejson.dumps(var),content_type='application/json')
And you will call the second route in your ajax call
Hope it helps you

list all image button clicked change image

every one ,I am using django's template language with javascript to do "clicked image button change image" ,however,the result I got was only can change the last button.I do not know why what's wrong about the code , here is my
indext.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Homepage - {{ block.super }}
{% endblock title %}
{% block content %}
<script>
function setColor(e, btn, color) {
var target = e.target,
count = +target.dataset.count;
target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
target.dataset.count = count === 1 ? 0 : 1;
}
var img_array = [ src="{% static "img/published.png" %}" , src="{% static "img/draft.png" %}"];
i = 0;
{% for post in posts %}
function myFunction({{ post.model_number }}) {
i++;
document.getElementById("{{ post.model_number }}").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}
{% endfor %}
</script>
<table class="table table-bordered">
<tr>
<td>產品編號</td><td>產品名稱</td><td>建立日期</td><td>產品圖片</td><td>最後修改日期</td><td>產品說明</td><td>建立者</td><td>修改者</td><td></td>
</tr>
{% for post in posts %}
<tr>
<td> {{ post.model_number }} </td>
<td>{{ post.name }}</td>
<td>{{ post.created }} </td>
<td> <img src="{% if post.image %} {{ post.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}" height="100" width="100"> </td>
<td>{{ post.modified }} </td>
<td>{{ post.feature }}</td>
<td>{{ post.user }}</td>
<td>{{ post.useredit }}</td>
{% for cp in post.cataloggroup.all %}
<td> {{cp }}</td>
{% endfor %}
<td><a href="{% url 'edit_thing' slug=post.slug %}"><input class="button0 button2" type="button" id="button" value="編輯" style="color:#fffff0" onclick="setColor(event, 'button', '#101010')"; data-count="1" /><a></td>
<td><button onclick="myFunction({{ post.model_number }})"><img id="{{ post.model_number }}" src="{% static "img/published.png" %}" width="50" height="30"></button></td>
</tr>
{% endfor %}
</table>
{% include "pagination.html" with page=posts %}
{% endblock content %}
and it will render the web
however, when I click the top button ,it will change the bottom button,I have to let every button clicked can change image
above image I clicked top button but changed the bottom button's image "published ---> draft"
I have to let every button clicked can changed it's own image,how can I do it?
It is due to the fact you have your myFunction() definintion inside a <script> tag that is entered into the HTML every iteration of your for loop in django.
This means the function is constantly being redefined and therefore myfunction functionality will always be that of the last iteration.
If you define myFunction() outside of your django loop and pass in the model number to the function (as below) then it should work as expected`
function myFunction(model_number) {
i++;
document.getElementById(model_number).src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}
ok,I solve the problem
index.html
<script>
...........
var img_array = [ src="{% static "img/published.png" %}" , src="{% static "img/draft.png" %}"];
i = 0;
{% for post in posts %}
function a{{ post.model_number }}() {
i++;
document.getElementById("{{ post.model_number }}").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}
{% endfor %}
</script>
<table class="table table-bordered">
<tr>
{% for post in posts %}
<tr>
.........
<td><button onclick="a{{ post.model_number }}()"><img id="{{ post.model_number }}" src="{% static "img/published.png" %}" width="50" height="30"></button></td>
</tr>
{% endfor %}
</table>

Categories