Django website not checking the links correctly - javascript

I have a django website that contains a table with many servers details.
In one of the columns in the table there is "ILO" IP of a server.
I wanted the website to check if the "ILO" IP works in http request, and if it does, then it should show the link and if not, shows a text instead.
Therefore, in the result, will be servers that has http link to ILO IP and some without.
Under my main class in the views I created a function called "checkUrlAvailable" which I try to use in my index.html and check with if condition if I get true or false..
for some reason I get the errorr-
Could not parse the remainder: '(server.IP)' from 'checkUrlAvailable(server.IP)'
Does anyone know why?
index.html-
<tr>
<th><center> #</center></th>
<th width="100%"><center> Server Name </center></th>
<th><center> Owner </center></th>
<th><center> Project </center></th>
<th width="100%"><center> Description </center></th>
<th width="100%"><center> IP Address </center></th>
<th width="100%"><center> ILO </center></th>
<th><center> Rack </center></th>
<th><center> Status </center></th>
<th><center> Actions {{ response }} </center></th>
</tr>
</thead>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td></td>
<td style='white-space: nowrap'><center>{{ server.ServerName }}</center></td>
<td width="100%"><center>{{ server.Owner }}</center></td>
<td style='white-space: nowrap'><center>{{ server.Project }}</center></td>
<td style='white-space: nowrap'><center>{{ server.Description }}</center></td>
<td width="100%"><center>{{ server.IP }}</center></td>
<td style='white-space: nowrap'><center>
{% if checkUrlAvailable(server.ILO) is True %}
http://{{ server.ServerName }}.ilo.lab.radcom.co.il
{% else %}
http://{{ server.ServerName }}.ilo.lab.radcom.co.il
{% endif %}
<td width="100%"><center>{{ server.Rack }}</center></td>
<td width="100%"><h4><span class="badge badge-success">Online</span></h4></td></center>
views.py -
class HomeView(TemplateView):
template_name = 'serverlist.html'
def checkUrlAvailable(url):
resp = requests.head(url)
if resp.status_code == 200:
return True
else:
return False
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
forms = {}
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form,'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
forms = {}
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
post.save()
messages.success(request,'{0} has been added successfully!'.format(post.ServerName))
return redirect('serverlist')
messages.error(request,'Servername is required, please refresh the page and try again.')
for post in posts:
forms[post.id] = HomeForm(instance=post)
args = {'form' : form, 'forms': forms, 'posts' : posts}
return render(request, self.template_name,args)

You cannot call function inside django template. You need to define custom template tag or you can move checkUrlAvailable inside serverlist model:
class serverlist(models.Model):
...
def checkUrlAvailable(self):
resp = requests.head(self.ILO)
if resp.status_code == 200:
return True
else:
return False
and use it in template like this:
{% if server.checkUrlAvailable %}

Related

Django Form Disabled Select Option Values Not Submitted Even When They are Enabled with JavaScript Before Submission

My HTML displays about 20 or more forms via modelformset_factory and each having a preselected staff name (so this is disabled in forms.py). Staff name is primary key to Staff model, so I don't want all their names be available for selection. Logged in user have some staff assigned and so they are only required to enter phone number and address. The disabled fields are enabled with Javascript before the form is submitted but I still get {'staff_name': ['This field is required.']} error when the form is submitted.
Here are my codes:
forms.py
class StaffForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['staff_name'].disabled = True
views.py
class StaffModelFormSet(BaseModelFormSet):
def clean(self):
super().clean()
print(self.errors)
class StaffEntryView(LoginRequiredMixin, FormView):
def post(self, request, *args, **kwargs):
StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet)
submitted_form = StaffFormSet(request.POST)
if submitted_form.is_valid():
self.form_valid(submitted_form)
print("This form is valid, Sir!")
else:
self.form_invalid(submitted_form)
print("This is not a valid form.")
template.html
<form method="post" class="form-control" id="staff_form" name="staff-form" onsubmit="enablePath();">
<!-- form details goes here -->
<tbody>
{% for form in formset %}
<tr class="table-striped">
<td>{{ form.staff_name }}</td>
<td>{{ form.phone }}</td>
<td>{{ form.address }}</td>
</tr>
{% endfor %}
</tbody>
script.js
function enablePath(e) {
var options = document.getElementsByTagName('select');
for (var i=0, iLen=options.length; i<iLen; i++) {
options[i].disabled = false;
}

Sending data from JS to Python successfully but Flask render_template doesn't execute

I am using a Jinja loop to display a table of results in an html page. When someone clicks the button in a table row, the code should send the first column value in that row to the server. The server should then use the value to populate values in another page. All works fine except the render_template function in app.py isn't executing.
What am I doing wrong?
My last print(request_details) shows the data needed correctly. However the render_template that follows just doesn't want to execute.
HTML and JS:
{% extends "layout.html" %}
{% block body %}
<table>
<tr>
<th>Request ID</th>
<th>Origin</th>
<th>Destination</th>
<th>Distance</th>
<th>Cargo</th>
<th></th>
</tr>
{% for r in supplier_results %}
<tr>
<td>{{ r[0] }}</td>
<td>{{ r[2] }}</td>
<td>{{ r[3] }}</td>
<td>{{ r[4] }}</td>
<td>{{ r[5] }}</td>
<td><button onclick="passRequest({{ r[0]|safe }})">Offer</button></td>
</tr>
{% endfor %}
</table>
<script>
function passRequest(arg) {
let details = arg
console.log(details)
const request = new XMLHttpRequest()
request.open('POST', '/viewrequest/' + details)
request.send();
};
</script>
{% endblock %}
Python:
#app.route("/viewrequest/<int:details>", methods=["GET", "POST"])
def viewrequest(details):
# Retrieve request information with the request_id (details)
retrieve_request = f"SELECT * FROM requests WHERE request_id='{details}';"
cur.execute(retrieve_request)
request_details = cur.fetchall()
# Call the newoffer page and pass the request details
if request_details == []:
print("No data found")
return
else:
print(request_details)
return render_template("supplier/newoffer.html", request = request_details)

keyerror in formset form field

I am making a delivery note transaction form, I have created a formset for which I want Django to ignore item transactions where the item is not selected and is empty.
forms.py
class Delivery_note_transiction_form(forms.Form):
item = forms.CharField(widget=Select2Widget(attrs={"class" : "item"}),label=False,required=False)
description = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}),label=False,required=False)
quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class' : 'quantity'}),label=False,min_value=1)
id = forms.CharField(widget=forms.HiddenInput,required=False)
Delivery_note_transiction_form_formset = forms.formset_factory(Delivery_note_transiction_form,extra=1)
views.py
def feedback(request):
if request.method == "POST" and request.is_ajax():
form = Deliver_Note_Main_Modelform(request.POST)
formset = Delivery_note_transiction_form_formset(request.POST,request.FILES)
if form.is_valid() and formset.is_valid():
ins = form.save(commit=False)
ins.author = request.user
result = Customer_data.objects.get(pk=form.cleaned_data['customer'])
ins.customer_list = result
ins.save()
max_invoice = Invoice_max.objects.get(invoice_name='delivery')
max_invoice.invoice_no = max_invoice.invoice_no + 1
max_invoice.save()
print(formset)
for instant in formset:
if instant.cleaned_data['item']:
item = Product.objects.get(pk=instant.cleaned_data['item'])
description = instant.cleaned_data['description']
quantity = instant.cleaned_data['quantity']
Delivery_Note_Transiction.objects.create(
item=item,
description=description,
quantity=quantity,
delivery_invoice_no=ins
)
return JsonResponse({'success':True, 'next' : reverse_lazy('delivery note:delivery note home page')})
else:
return render(request,"delivery_note/ajax/delivery note error message.html",{"error" : form, "transiction_error": formset})
return HttpResponse("Hello from feedback!")
template.html
{% for delivery in delivery_transiction %}
<tr class=" delivery_form ">
<td class="col-sm-4">{{ delivery.item|as_crispy_field }}</td>
<td class="col-sm-4">{{ delivery.description|as_crispy_field }}</td>
<td class="col-sm-4">{{ delivery.quantity|as_crispy_field }}</td>
</tr>
{% endfor %}
The post data is sent by Ajax and the selected option is created on the template. When it is loaded, a new row is added by Ajax. The problem is I want to it ignore transaction entry if the item is not selected or is empty, but when I run it, it gives this error:
"KeyError: 'item'"
It should ignore empty or not selected items. This only happens when the item is not selected in the transaction. I want to fix this error so that it will simply ignore rows in which the item is not selected.
You have to use a try except when searching a dictionary for a key.
for instant in formset:
try:
item = Product.objects.get(pk=instant.cleaned_data['item'])
Except KeyError:
# What to do if no 'item'.
You will have to figure out where to put the rest of your code, but this will get you past the KeyError.

Refreshing a specific div every few seconds in django using javascript

I am trying to refresh the content of a table every few seconds in my HTML page using javascript. I keep getting 500 error when it tries to refresh the div, internal server error. Could someone enlighten the reason this is not working? I have used this: Refresh div using JQuery in Django while using the template system
as a reference to what I was doing. The page loads perfectly the first time just fails to refresh.
Here is my code:
urls.py
url(r'^specialScoreboard/$', views.specialScoreboard.as_view(), name='specialScoreboard'),
url(r'^specialScoreboardDiv/$', views.specialScoreboardDiv , name='specialScoreboardDiv'),
views.py
class specialScoreboard(generic.ListView):
template_name = 'CTF/specialScoreboard.html'
context_object_name = 'teams'
#method_decorator(login_required)
#method_decorator(never_ever_cache)
def dispatch(self, request, *args, **kwargs):
if getAnyActiveGame and request.user.is_staff:
return super(specialScoreboard, self).dispatch(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('CTF:no_active_game'))
def get_queryset(self):
"""
ordering teams by score
"""
game = getAnyActiveGame()
teams = get_teams_from_game(game)
return sorted(teams, key=lambda a: a.get_score(game), reverse=True)
def specialScoreboardDiv():
game = getAnyActiveGame()
teams = get_teams_from_game(game)
sortedList = sorted(teams, key=lambda a: a.get_score(game), reverse=True)
return render_to_response('CTF/specialscoreboardDiv.html' , {'sortedList' :sortedList})
scoreboardRefresh.js + scoreboardDiv.html
<script>
var scoreboardURL = '{% url '
CTF: specialScoreboardDiv ' %}';
function refresh() {
$.ajax({
url: scoreboardURL,
success: function(data) {
$('#scoreboardDiv').html(data);
}
});
};
$(document).ready(function($) {
refresh();
setInterval("refresh()", 3000);
})
</script>
<div class="panel panel-info">
<div class="panel-heading">Scoreboard</div>
<div class="panel-body">
<div class="table-striped">
<table id="scoreboardDiv" class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Team Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{% for team in teams %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{team.name}}</td>
<td>{{team|getScoreTeam}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
I can't seem to be able to format the error, here is a picture of it: http://i.imgur.com/Yc11juA.png
http://i.imgur.com/QluqZyc.png
http://imgur.com/QluqZyc
Your django view takes no arguments, but usually django tries to pass request param into it. From the error in the screenshot you provided in comments, looks likŠµ this is your problem.
I think you error will be fixed by making your view function take this argument:
def specialScoreboardDiv(request):
game = getAnyActiveGame()
...

django: How to set date and time to server from client

I try to semplify my situation:
I have two PC, PC1 ("server") is not on the web, instead the PC2 ("client") can surf on the web (they communicate between each other).
Into PC1 I have my Django project, DB etc.. while with PC2 I can access via browser to my project an so on.
I would like to reach this goal:
PC1 take the date and time from PC 2 automatically and in PC 1 every actions refers to time and date of PC2.
| PC1 (server-side) | <--datetime--- | PC2 (client-side) |<----- datetime from web
Actually I can take the client datetime with some js:
datetime.js
$(document).ready(function(){
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
var myDate = new Date();
var strDate = myDate.getFullYear()+ "-" +(myDate.getMonth()+1)+ "-" +myDate.getDate();
var strTime = myDate.getHours()+ ":" + myDate.getMinutes() +":" + myDate.getSeconds();
document.getElementById("data").innerHTML = myDate.toLocaleString();
}
})
models.py
from django.db import models
class ProvaTime(models.Model):
somewords = models.CharField(max_length=30)
myauthor = models.ForeignKey('auth.User', null=True, blank=False)
created_date = models.DateTimeField() # how tell it to pick js timedate?
def save(self, *args, **kwargs):
super(ProvaTime, self).save(*args, **kwargs)
forms.py
from django import forms
from .models import ProvaTime
class ProvaTimeForm(forms.ModelForm):
class Meta:
model = ProvaTime
fields = ('somewords',)
views.py
def testime(request):
elements =ProvaTime.objects.filter().order_by('-created_date')
if request.method == 'POST':
form = ProvaTimeForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.save()
else:
form = ProvaTimeForm()
return render(request, 'provapp/testime.html', {'form': form, 'elements': elements})
def myviewtomodel(request): # how to do?
provapp/testime.html
<form action="/testime/" method="post">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="LIST" />
</form>
<br />
<br />
<div class="table-responsive">
<table class="table table-bordered">
<tr class="info">
<td width="15%" align="center">SOMETHING WORDS</td>
<td width="15%" align="center"> CREATION DATETIME </td>
<td width="15%" align="center"> AUTHOR </td>
<td>
</td>
{% for stuff in elements %}
<div class="stuff">
<tr>
<td>{{stuff.somewords}}</td>
<td>{{stuff.created_date}}</td>
<td>{{stuff.myauthor}}</td>
</div>
{% endfor %}
</table>
</div>
How can I send JS datetime to models.py?
You should pass the javascript date to your models explicitly.
model.created_date = date_from_javascript
Since you have set the default value for created_date as timezone.now it will use the server's timezone when nothing is passed to it.
ex.
$.ajax({
url: '/myview/',
data: {'javascript_date' : javascript_date},
method: 'post',
....
});
in your django view:
def MyView(request):
javascript_date = request.POST['javascript_date']
m = MyModel(created_at=javascript_date)
m.save()
I would recommend to not save client time directly in the database. Because while there is multiple clients with different timezone, then one client will see wrong time as that was created in separate timezone. I will suggest you to use session to save the offset value (Or database)and use it for displaying data.
Now lets make an ajax request in home page or another page which will send the offset data to the server from browser.
$(document).ready(function(){
var now = new Date()
var value = now.getTimezoneOffset()
$.ajax({
url: "your-url",
type: "post", // or "get"
data: value,
success: function(data) {
console.log(data);
}});
});
add an extra field to model to save that offset. And a property method which will later calculate user's local time.
class ProvaTime(models.Model):
....
tz_offset = models.DecimalField(default=Decimal('0.0'),max_digits=3, decimal_places=1)
#property
def get_local_time(self):
return create_time - datetime.timedelta(tz_offset)
and ajax the view
import json
def post(request):
if request.POST():
data = {}
try:
get_value= request.body
prova_times = ProvaTime.objects.filter(myauthor=request.user)
if prova_times.exists():
for prova_time in prova_times:
prova_time.tz_offset = get_value
prova_time.save()
data['success'] = 'Success'
return HttpResponse(json.dumps(data), content_type="application/json")
except Exception as e:
data['error'] = e
return HttpResponse(json.dumps(data), content_type="application/json")
Now displaying the data:
def myviewtomodel(request):
context = dict()
context['elements'] = ProvaTime.objects.all()
return render(request, 'myapp/index.html', context,
content_type="application/xhtml+xml")
Showing time in template(using get_local_time).
<div class="table-responsive">
<table class="table table-bordered">
<tr class="info">
<td width="15%" align="center">SOMETHING WORDS</td>
<td width="15%" align="center"> CREATION DATETIME </td>
<td width="15%" align="center"> AUTHOR </td>
<td>
</td>
{% for stuff in elements %}
<div class="stuff">
<tr>
<td>{{stuff.somewords}}</td>
<td>{{stuff.get_local_time}}</td>
<td>{{stuff.myauthor}}</td>
</div>
{% endfor %}
</table>
</div>

Categories

Resources