Displaying Django Admin Navigation on non-model template - python

I have made an HTML form(with only HTML's form tag, not Django) which I have put inside {% block content %} for Django to display.
{% extends "admin/base_site.html" %}
{# mainapp/templates/VideoTracker.html #}
{% block content_title %}
{{ 'Execution Status' }}
{% endblock %}
{% block content %}
<form>
<table> <br>
<tr>
<td>
<div>
<input type="checkbox" name="adhocexec", value="Adhoc" checked/> Adhoc Request
</div>
</td>
<td>
<div>
<input type="checkbox" name="periodicexec", value="Periodic" checked> Periodic Request
</div>
</td>
</tr>
<tr>
<td>
<div>
Start : <input type="date" name="frdt">
</div>
</td>
<td>
<div>
End : <input type="date" name="todt">
</div>
</td>
</tr>
</table>
<br>
<div>
<button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search Reports </button>
</div>
<br>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search in results..." title="Type Here">
<table id="myTable">
<tr class="header">
<th>BOX ID</th>
<th>MSO ID</th>
<th>Execution Type</th>
<th>Channel ID</th>
<th>Execution Date Time</th>
<th>Result</th>
<th>Detailed Report</th>
</tr>
{% for queue in results %}
<tr>
<td>{{ queue.box_id }}</td>
<td>{{ queue.mso_id }}</td>
<td>{{ queue.exec_type }}</td>
<td>{{ queue.channel_id }}</td>
<td>{{ queue.exec_time }}</td>
<td>{{ queue.result_status }}</td>
<td>{{ queue.result_link }}</td>
</tr>
{% endfor %}
</table>
<script>
function myFunction()
{
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++)
{
td_col0 = tr[i].getElementsByTagName("td")[0];
td_col1 = tr[i].getElementsByTagName("td")[1];
td_col2 = tr[i].getElementsByTagName("td")[2];
td_col3 = tr[i].getElementsByTagName("td")[3];
td_col4 = tr[i].getElementsByTagName("td")[4];
td_col5 = tr[i].getElementsByTagName("td")[5];
td_col6 = tr[i].getElementsByTagName("td")[6];
if (td_col0 && td_col1 && td_col2 && td_col3 && td_col4 && td_col5 && td_col6)
{
cond0 = td_col0.innerHTML.toUpperCase().indexOf(filter) > -1
cond1 = td_col1.innerHTML.toUpperCase().indexOf(filter) > -1
cond2 = td_col2.innerHTML.toUpperCase().indexOf(filter) > -1
cond3 = td_col3.innerHTML.toUpperCase().indexOf(filter) > -1
cond4 = td_col4.innerHTML.toUpperCase().indexOf(filter) > -1
cond5 = td_col5.innerHTML.toUpperCase().indexOf(filter) > -1
cond6 = td_col6.innerHTML.toUpperCase().indexOf(filter) > -1
if (cond0 || cond1 || cond2 || cond3 || cond4 || cond5 || cond6)
{
tr[i].style.display = "";
}
else
{
tr[i].style.display = "none";
}
}
}
}
</script>
</form>
{% endblock %}
I have linked this HTML on urls.py and from my views.py I am calling a function which does some processing and displays data on the HTML. So far so good.
Now I wanted to display this HTML on admin as a link, ideally, all Class Model is shown as the link on Admin but for my case, the data which I am presenting is non-model. So to display this as a clickable link on Admin I made test model on models.py
class TestModel(models.Model):
try:
print('TestModel')
except Exception as ex:
logging.error('Exception : models --> TestModel ' + str(ex))
And in my admin.py I made class with base AdminViews
class TestAdmin(AdminViews):
admin_views = (
('Track Executions', 'redirect_to_executions'),
)
def get_model_perms(self, request):
"""
Return empty perms dict thus hiding the model from admin index.
"""
return {}
def redirect_to_executions(self, *args, **kwargs):
return redirect('/track_execution')
With this, I am able to see link on the Admin page
After clicking the link, I see default admin page like I am not logged in.
How can I make my logged in details i.e. same context to persist as with model links to be shown on my non-model template as well?
I am a bit struggling with it.

You can use do it at the lazy way or the hard way...
The lazy way Build onde Proxy Models, so that way he wont persist the data, and you can show it as any other models in admin, and change what you want to do with it at your admin view
Proxy Models: https://docs.djangoproject.com/en/2.0/topics/db/models/#proxy-models
The Hard way You can override this template and add it manualy with the same classes and css stuffs to looks like the others.
Override Template: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates
Maybe there is other simple way to do that, if you find one better please share :)

Related

How to download an updated file by admin in Django

what i am trying to do is:
Admin uploads a PDF file from admin panel. (1)
It needs to go to the specified template. (2)
And it should be downloaded by pressing download button in the template.
So here are codes:
(1)
class Reports(models.Model):
name = models.CharField(max_length=100, null=False, blank=False, verbose_name="File Name")
report = models.FileField()
(2)
<tr>
<td>"File Name must be showed in here"</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><i class="fas fa-file-download"></i></td>
<td class="text-center lang-en-src"><i class="fas fa-file-download"></i></td>
</tr>
In the website there will be one report for every month. I want to list them in the template and make them downloadable.
Should i write a view for that(if yes how it should be?) or what should i do?
Every single data you want to show to your template you need write it in your views.py, so this case is so specefic.
views.py:
def your_view_name(request):
reports = Reports.objects.all()
context = {
'reports': reports
}
return render(request, 'your_template.html', context)
Then make a url for your view in urls.py
urlpatterns = [
path("", views.your_view_name, name='your_url_name')
]
Your template:
<tr>
{% for obj in reports %}
<td>{{ obj.name }}</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><a href="{{ obj.report.url }}" Download
target="_blank"><i class="fas fa-file-download"></i></a></td>
<td class="text-center lang-en-src"><a href="" target="_blank"><i
class="fas fa-file-download"></i></a></td>
{% endfor %}
</tr>
create a new view firstly.
def report_view(request):
context = {}
reports= Reports.objects.all()
context['reports'] = reports
return render(request, "pages/report.html", context)
create an url for this view in urls.py
path('reports', report_view, name='report_view'),
in your template create forloop for this context like below:
{% for report in reports %}
<tr>
<td>"File Name must be showed in here"</td>
<td class="text-center">PDF</td>
<td class="text-center lang-tr-src"><i class="fas fa-file-download"></i></td>
<td class="text-center lang-en-src"><i class="fas fa-file-download"></i></td>
</tr>
{% endfor %}

converting and multiply float to int in django templates

I am fetching some data from a stocks API and I get some values (stored in the DB as float)
as follow:
YTD Change 0.379996
daily % change 0.00854
my view is as follow:
def get_stock(request):
empty = True
localStocks = Stock.objects.all()
if len(localStocks) > 0 :
empty = False
return render (request,'get_stock.html',{'empty':empty, 'output':list(localStocks)})
and my template
<section class="section-typography container u-readable">
<table>
<thead>
<tr>
<th>Ticker</th>
<th>Name</th>
<th>Price</th>
<th>Last Time</th>
<th>% Change</th>
<th>52W High</th>
<th>52W Low</th>
<th>YTD Change</th>
</tr>
</thead>
<tbody>
{% if not empty %}
{% for list_item in output %}
<tr>
<td> {{list_item.symbol }}</td>
<td> {{ list_item.companyName }}</td>
<td> {{ list_item.latestPrice }}</td>
<td> {{ list_item.latestTime }}</td>
<td> {{ list_item.changePercent }}</td>
<td> {{ list_item.week52High }}</td>
<td> {{ list_item.week52Low}}</td>
<td> {{ list_item.ytdChange }}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</section>
{% endblock %}
the % change for the stock YTD is not 0.379996 but 37.99% and this is what I would like to display. Similarly the daily change is not 0.00854 but 0.85% . How can I manipulate the date either on the view or template to basically multiply it and display only the first 2 decimals of the float?
You need to implement a custom template tag. In your app directory create a new module named templatetags. Inside this module there should be a blank __init__.py and a random named file like percentage.py.
Your percentage.py should contain:
#percentage.py
from django import template
register = template.Library()
#register.simple_tag(name="percentage")
def percentage(value):
return str(round(value *100,2))+'%'
In any html file you want to use this tag, you should load this tag at the start of the file with {% load percentage %}. In order to pass the required value to the templatetag, you need to use it like: {% percentage list_item.changePercent %}
The best way is to change the value in view as follow:
YTD_to_pass = ((YTD*10000)//1/100)
this will multiply the value by 100 and keep 2 digits after whole number
then simply add a % symbol in template.

How to concatenate a varibale from a function in a form action with Django?

i want to concatenate a variable in a form action. for example:
<form action="{% url 'addAlumn' ${id} %}" method="POST">
im sure im wrong but i dont have idea how to do this.
this is my function:
<script>
function alumno(obj, obj2, obj3, obj4) {
id = obj;
var no_certificado = obj2;
var nom = obj3;
var curp = obj4;
$("#nombre").val(nom);
$("#cert").val(no_certificado);
$("#curp").val(curp);
}
</script>
Change the form url, remove the ID from urls.py and get the object with the post request. Something like this:
Form
<form action="{% url 'editarAlumno' %}" method="POST">
urls.py
path('NuevaSolicitud/editarAlumno/', login_required(views.EditarAlumno), name='editarAlumno'),
views.py
def EditarAlumno(request):
id = request.POST["id"]
alumno = Alumnos.objects.get(pk=id)
...
...
...
# Make sure you save your object before redirecting
alumno.save()
return redirect('Alumnos')
From what I can see your form action should be '=' to not ':' I'm not sure what the function is used for, looks like you are adding values to the form.
You also need to remove $ from 'id'
Abit more info on what you are trying to do can make it easier to give more help
<form action="{% url 'addAlumn' id %}" method="POST">
this is my table:
<tbody>
{% if lista_alumnos %}
{% for alumno in lista_alumnos %}
<tr>
<td>{{ alumno.no_certificado }}</td>
<td>{{ alumno.nombre_alumno }}</td>
<td>{{ alumno.CURP }}</td>
<td>
<i class="material-icons" data-toggle="tooltip" title="Edit"></i>
<i class="material-icons" data-toggle="tooltip" title="Delete"></i>
</td>
</tr>
{% endfor %}

Django: writing a view to delete multiple object with checkboxes

So I have a table that lists all the record from my model.
But now I'm trying to make a Checkbox and delete it (kinda like the Django admin way), I can't find the documentation for this , as I'm sure there are several ways to to this.
But I'm trying to figure out like whats the proper way for doing this , should I do this via view ?
How to create single delete button for multiple delete instances in html and view.I am not using form
I refreed this side but not get correct solution
Django: writing a view to delete an item with checkboxes
Deleting multiple rows in Django frontend
list.html
{% for obj in object_list %}
<tbody>
<tr>
<td><input type="checkbox" name="data" value="{{obj.id}}" ></td>
<td><a href='#' data-toggle="collapse" value="{{obj.id}}">{{ obj.id }}</td>
<td>{{ obj.Full_Name }}</td>
<td>{{ obj.Agency_Name}}</td>
<td>{{ obj.Date_of_Birth}}</td>
<td>{{ obj.Agency_Code}}</td>
<td><span class="label label-primary">{{ obj.Agent_Status}}</span></td>
<td class="text-right">
<i class="fa fa-list-alt" aria-hidden="true"></i>
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
#<i class="fa fa-trash" aria-hidden="true"></i>
#Remove this button and create single button for multiple delete
</td>
</tr>
</tbody>
{% endfor %}
view.py
def Agent_List(request, id=None): #list items
queryset = Agent.objects.order_by('id')
#queryset = Agent.objects.all()
query = request.GET.get('q')
if query:
queryset=queryset.filter(
Q(Aadhaar_Number__icontains=query) |
Q(PAN_Number__icontains=query) |
Q(Account_Number__icontains=query)
).distinct()
context = {
"object_list": queryset,
"Full_Name ": "Agent_List",
}
return render(request, "customer/Agent_List.html", context)
def Agent_Delete(request, id=None):
instance = get_object_or_404(Agent, id=id)
instance.delete()
messages.success(request, "Successfully deleted")
return redirect("customer:Agent_List")
In def Agent_Delete(request, id=None) it delete single id.but How to delete selected multiple id.Thank you in advance.

Django: Receiving data from dynamic form value field

Working on converting an app from Flask to Django and getting stuck on how I can pull data from the value of a form button. I have some data that is rendered in a table with a for loop. Each entry has a button displayed that allows my to flip an integer field for the rendered data. Once it's flipped, it's no longer listed.
# manage.html
{% for ticket in tickets %}
<tr>
<td>{{ my_obj.id }}</td>
<td>{{ my_obj.tt }}</td>
<td>{{ my_obj.user }}</td>
<td>{{ my_obj.time }}</td>
<td><form action="/flip/" method="post">{% csrf_token %}
<input type="hidden" name="flip" value="{{ my_obj.id }}"/>
<input type="submit" class="btn btn-xs btn-danger" value="Kill"/>
</form>
</td>
</tr>
{% endfor %}
# views.py
def flip(request):
if request.method == 'POST':
tt_id = request.POST.get('value')
return HttpResponse(tt_id )
def manage(request):
my_obj = MyObject.objects.filter(status=1)
return render(request, 'manage.html', {'my_obj': my_obj})
Currently I am getting a response of None rather than the actual ID which is showing in the value field with firebug.
Thanks for looking!
You have to access the fields by the name, not with value. e.g.
request.POST.get('flip')
If you want to access the buttons value, you need to set the name attribute on it.
For details on your request it is helpful for print or return the whole request object. A debugger would be an other way to take a look at it.

Categories

Resources