calling a view in django again and again - django

Suppose I have a list of buttons in my django template and I want to change a variable in my database on clicking that button. Here is the code of that template.
{% for i in data %}
<tr>
<td>{{ i.rollno }}</td>
<td>{{ i.name }}</td>
<td>
<a class='btn btn-danger' href='add/{{i.id}}/{{stri}}'> {{stri}} </a>
</td>
</tr>
{% endfor %}
Jquery code of this template:
$(document).ready(function(){
$(".btn").click(function(){
$(this).toggleClass('btn-success');
$(this).toggleClass('btn-danger');
});
});
The button in above code is a toggle(on/off) button. Therefore, in jquery I wrote a code to switch it on/off.
By default all the buttons are in off state.
I have called a view every time a button is clicked and then returned this url. But this switches every button in default state ie off state. And because every time the same page is loaded, I am unable to get to the previous page on clicking back button but getting the same page the no of times I called the view.
Every button belongs to an IntegerField() in database.
I am new to Django. Please suggest me a better way to do this. Maybe I could save the changes in an array and then pass it to view at the time of submitting or something similar to this and more efficient.

First off you might want to use a form instead. Since you are going to store the data
in your dbms, use "POST". Your above code, activates every button because you did not specify which button you wanted to press. So to prevent that from happening, you can either do it as shown below, to create an onclick event which only sents the id and string to the respective url, or do it the django way
"{% url 'urlname' id=id, stri=stri %}", whichever you prefer.
<form id="activate" method="POST">
{% for i in data %}
<tr>
<td>{{ i.rollno }}</td>
<td>{{ i.name }}</td>
<td>
<a class='btn btn-danger' id="activateButton" onclick="activate({{i.id}}, {{stri}})"> {{stri}} </a>
</td>
</tr>
{% endfor %}
</form>
function activate(id, string){
if($('#activateButton').hasClass('btn-success');
$('#activateButton').toggleClass('btn-danger');
}else{
$('#activateButton').toggleClass('btn-success');
}
var url = 'add/{{i.id}}/{{str}}'
$('#change').attr('action', url)
$('#change').submit()
});
You can access the id and string parameter in your view depending on how you write it.
for this case, I am assuming you are using url params. So your view should look something like that
def activate(request, id, strin):
# view code
#store id and string into dbms
I hope this helps clarify some doubts on the usage of django, and I hope I have understood your question correctly.

Related

#DJANGO - I need to display two (or more) rows of a table in my view, currently I can only display one of the rows

Hello people I am working with ticket creation and there is a 1-N relationship, (a ticket can have multiple messages)
I have a view that creates a ticket, in the creation process a message is added - All right here
I have a view that adds a new message to the ticket(s), thus 'activating' the 1-N - All right here
I have a ticket detail view view (code below) - Here starts my difficulty
def ticket_by_id(request, ticket_id, message_id):
mesTicket = MessageTicket.objects.get(pk=message_id)
ticket = Ticket.objects.get(pk=ticket_id)
return render(request, 'support/ticket_by_id.html', {'ticket': ticket, 'messageticket': mesTicket})
the code view above works when the ticket has only one message, but how can I display the multiple messages in this view?
For example in the image below there is my database, highlighting two lines that are linked to ticket 9
database, highlighted in ticket messages 9
Below is an image of my ticket detail view
my detail view of the ticket
How should I display in the view the two messages (or 3, or 4, anyway... more than one) that are related to the ticket, as I would show in my view (image 2) lines 9 and 12 (currently it is only displaying the first registered line linked to the ticket, in this case line 9 of the table) of the my table which are the ones that make up the 1-N with the ticket 9 (image 1)
my html page:
{% extends 'web/base.html' %}
{% block title %} Ticket #{{ticket.id}} {% endblock %}
{% block content %}
<div class="ticket">
<table class="styled-table">
<h2> Ticket #{{ticket.id}}</h2>
<style>
td {
padding: 15px;
}
</style>
<br>
<tbody>
<tr>
<td>ID: </td>
<td>{{ticket.id}}</td>
</tr>
<tr>
<td>Author: </td>
<td>{{messageticket.author_id}}</td>
</tr>
<tr >
<td>Status: </td>
<td>{{ticket.status}}</td>
</tr>
<tr>
<td>Content: </td>
<td>{{messageticket.content}}</td>
</tr>
<tr>
<td>Created At: </td>
<td>{{ticket.created_at}}</td>
</tr>
</tbody>
</table>
</div>
{% endblock %}
First of all, why does your message is not fetch with the id of your ticket, this would ease your work
Second to print multiple "messageticket" you should use something like:
{% for t in messageticket %}
<tr>
<td>Content: </td>
<td>{{ t.content }}</td>
</tr>
{% endfor %}
A loop is needed. As i don't know how messageTicket is done i can't really help you.
But if messageticket have a foreign_key to Ticket then you should be able to to acces it through ticket with ticket.messageticket_set (messageticket_set can be modified if "related_name=" is used in your foreign_key field)
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
and there you'll have all your messageticket
Hope it help =)

FF92.0 on linux introduces caching issues with django 3.2 inline forms

I've noticed a strange behavior with FF 92.0 (Manjaro Linux, but likely all linux I guess) when using inline forms.
Setup:
Django inline forms
A way to add inlines ajax. I'm using the django forms empty_form
Some arbitray # of inline saved on the server for that object (for example, say 3)
Load the form, add say 2 inlines using javascript. TOTAL_FORMS now shows value=5
Do NOT submit the form, but F5 for a refresh instead
After reload, the inlines shown in the table will mirror that of the server
However the TOTAL_FORMS from the management_form will show value=5, instead of the 3 it should.
page.js:
function insert_inlinedets_form () {
let form_idx = $('#id_details-TOTAL_FORMS').val();
console.log("inserting new form " + form_idx);
let newrow = $('<tr></tr>').appendTo($('#details_form'));
newrow.append($('#empty_form_inlinedets').html().replace(/__prefix__/g, form_idx));
$('#id_details-TOTAL_FORMS').val(parseInt(form_idx)+1);
console.log("added row to inlinedets formset");
};
function remove_inlinedets_form () {
console.log("remove last form ");
let form_idx = $('#id_details-TOTAL_FORMS').val();
if (form_idx>0) {
$('#details_form > tr').last().remove();
$('#id_details-TOTAL_FORMS').val(parseInt(form_idx)-1);
console.log("removed row from inlinedets");
calc_grand_total(); // existing rows haven't changed but the total might
} else {
$('#id_details-TOTAL_FORMS').val(); // if no form left, this SHOULD be 0.
console.log("No more dets left - nothing done.");
}
};
html - empty form:
<div style="display:none">
<table>
<thead></thead>
<tbody>
<tr id="empty_form_inlinedets">
{% for field in formset.empty_form %}
{% if field.is_hidden %}
<td style="display:none;">{{field}}</td>
{% else %}
<td>{{field}}</td>
{% endif %}
{% endfor %}
</tr>
</tbody>
</table>
</div>
html - target table to append to:
<div class="table-responsive shadow encart">
{{ formset.management_form }}
{{ formset.non_form_errors }}
<table class="table table-bordered dbase-table" id="bottom_product_form" width="100%" cellspacing="0">
<caption style="caption-side:top">Products</caption>
<thead>
<tr>
<!-- th content -->
</tr>
</thead>
<tbody id="details_form">
{% for form in formset %}
<tr>
<!-- td content -->
</tr>
{% endfor %}
</tbody>
</table>
</div>
I have validated the following:
The response.rendered_content that the server returns does indeed show the correct TOTAL_FORMS number (3, in the above example)
This does NOT happen upon a hard refresh (ctrl shift r on FF). TOTAL_FORMS, under the same setup, shows the correct # of 3.
This does NOT happen on Google Chrome upon a normal refresh.
So.... any ideas on how I should approach this? What setting could be causing the issue? Please consider in any answer:
I won't have control of user behavior. So simply "not using soft refresh on FF" isn't valid.
I won't have control of user browser settings, so adjusting some settings wouldn't really work (although KNOWING which FF setting may cause the issue is still useful)

Django: how to refresh html content on new database entry

I am developing a MQTT Dashboard app with django. I have a mqtt thread running in background, periodically polling for data from remote device and saving it as a database (MariaDB) row. I also have a view that displays this row in simple table. Now, what I want to do is to refresh this view (without page reload) when new data appears and my question is how to do that. I thought of two different approaches:
Use JS's setInterval triggering ajax call to periodically refresh content. Problem here is that I'm not really proficient with JavaScript nor jQuery so I would love to get simple example how to do that
Somehow refresh data from within on_message function which is called when mqtt gets new data. Problem here is that I have no clue if it is even possible
I would appreciate any explanation of above or even more some description of different, more proper way to do that. Here is my code:
part of template with content i want to refresh:
<div class="row mb-4 justify-content-center text-center">
<h1 class="text-uppercase text-white font-weight-bold">{% translate "Parameters" %}</h1>
<table id="device-parameters-table">
<thead>
<tr>
<th scope="col">{% translate "Parameter" %}</th>
<th scope="col">{% translate "Value" %}</th>
<th scope="col">{% translate "Unit" %}</th>
</tr>
</thead>
<tbody>
{% for key, value in latest_read_data.items %}
<tr>
<td>{{key}}</td>
<td>{{value.value}}</td>
<td>{{value.unit}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
device view:
def device(request):
clicked = request.GET.get('device_id')
dev = Device.objects.get(id=clicked)
latest_read_data = ReadData.objects.filter(device=dev).order_by('timestamp')
if latest_read_data:
read_data = latest_read_data.values()
read_data = read_data[len(read_data)-1]
read_data.pop('id')
read_data.pop('device_id')
read_data.pop('timestamp')
parameters_get_units(read_data)
context = {'latest_read_data': read_data, 'device': dev}
return render(request, 'dashboard/device.html', context=context)
else:
return HttpResponseRedirect('/dashboard')

executing python script in django with arguments from the frontend

I want to manipulate the values associated with the entries of an external mongodb database using a django webapp.
I've created the app and I'm currently displaying all the entries and their associated value in a simple table.
My idea is simply to create a button, that calls a python script with an argument (the id of that entry) and then changes it from false to true. The problem is, this seems like rocket-science, I've been at this for days now and I just can't get it to work as I have little to no proficiency when it comes to Ajax or Jquery, and all relevant examples I can find don't simply seem to pertain very well to my situation despite how basic it would appear, nor fit with Django 2.0+.
I'm using Django 2.1.5
def change_value(idnumber):
db_value = get_db_status_value(idnumber)
if db_value is True:
change_db_entry_status(idnumber, False)
else:
change_db_entry_status(idnumber, True)
my_template.html
<table>
<thead>
<tr>
<th> Status </th>
<th> Button </th>
</tr>
</thead>
<tbody>
{ % for entry in entry_data % }
<tr>
<td> {{ entry.status }} </td>
<td> <button type="button">{{ entry.idnumber }}</button> </td>
</tr>
</tbody>
{% endfor %}
</table>
I simply can't figure out how I can get the change_value function in there that I can create a button for and include an argument ( entry.idnumber ). This seems incredibly difficult, which from what I understand is a design principle, but it seems a shame if I can't even accomplish something as basic as above.
I was hoping someone could explain how I'm actually supposed to go about this? So far, it seems I require AJAX or Jquery (unfortunately, I barely know the basics of this, and what usually trips me up is that the urls.py which exist in both project and application level seems to work a little different in django 2.0+ compared to older versions)
This isn't actually difficult. It's just that you're missing an understanding of the relationship between the client and the backend code.
Once the template is rendered, the user sees it as HTML in their browser. That's it as far as the backend (ie Django) is concerned. The only way to run any further code on the server is to send another request. A request involves the browser contacting the server, which requires a URL and a view in Django.
Now, one way to send that request is via Ajax, but for your purposes that isn't necessary; since you're just learning, it's easier if you make it a simple form. So, your template might look something like this:
{% for entry in entry_data % }
<tr>
<td> {{ entry.status }} </td>
<td><form action="{% url 'change_value' idnumber=entry.idnumber %}" method="POST"> {% csrf_token %} <button type="submit">{{ entry.idnumber }}</button> </form></td>
</tr>
{% endfor %}
</tbody>
Notice how every iteration of the for loop has a separate form, which posts to a specific URL including the ID number.
Next you need a URL:
path('change_value/<int:idnumber>/', views.change_value, name='change_value'),
and update your function to actually be a view, which needs to accept a request and return a response:
def change_value(request, idnumber):
if request.method != "POST":
return HttpResponseNotAllowed()
db_value = get_db_status_value(idnumber)
if db_value:
change_db_entry_status(idnumber, False)
else:
change_db_entry_status(idnumber, True)
return redirect('/')
You always need to redirect after a POST, but you could redirect back to the same URL that rendered my_template in the first place. (Also note I've put in a test to make sure the user is actually sending a POST; you don't want Google to crawl this URL and flip your values for you.)
And that's it, now you have a button that should toggle your value.
The answer from #Daniel is enough for you. But if you want to use ajax so that the page does not have to refresh to change the vaue, you may do something like:
In your template make changes as:
<table>
<thead>
<tr>
<th> Status </th>
<th> Button </th>
</tr>
</thead>
<tbody>
{ % for entry in entry_data % }
<tr>
<td id="status"> {{ entry.status }} </td>
<td> <button type="button" onclick="change_status(this)" id="{{ entry.idnumber }}">{{ entry.idnumber }}</button> </td>
</tr>
</tbody>
{% endfor %}
and a script as:
<script>
function change_status($this){
var request_data = $this.id;
console.log("data: " + request_data);
$.post({
url: "url that leads to your view",
data : { request_data: request_data},
success : function(json) {
document.getElementById('status').innerHTML = "" //insert the data returned from the function
}
})}
</script>

Add button against each record on django admin change list page?

I want to add a button against each row on django admin change list page. When that button is clicked, i want to make entries in some database table(all this happens on the backend) and after that the button should be disabled on the same page against that row.
How can i achieve this? I have searched a lot button there is no solution available.
You are going to have to edit the changelist_result_list template at the point where the result items are generated (near the bottom) to add an element that provokes a request. For example:
<tr class="{% cycle 'row1' 'row2' %}">
{% for item in result %}
{{ item }}
<!-- NEW STUFF --->
{% if forloop.last %}
<td>{% if pk %}CLICK ME{% endif %}</td>
{% endif%}
{% endfor %}
</tr>
(Don't forget to also update the table headers further up)
You are going to have to provide a template context variable for {{pk}} by messing with the templatetag result_list in django.contrib.admin.template_tags.admin_list -- meaning, you are creating your own templatetag for this.
Then you need to set up a view and an url conf to handle the request the links send.
Let's say you're at foo/bar and click on the link for the row with pk=2. A GET request will be send for foo/bar/do_things_with_object_2.
Your url conf needs to capture the pk (and the model, here: bar) and your view needs to do whatever it is you want on the object.