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

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>

Related

Error while sending JavaScript generated image to Django ModelForm

I’m trying to use https://github.com/szimek/signature_pad to attach a signature to a form and send it to the server. I’ve been able to successfully upload images with a standard ImageField, and have also used szimek/signature_pad to download the signature. But when I try to get the signature to the server, I get "(Hidden field signature) No file was submitted. Check the encoding type on the form." So I think I’m at least successfully sending an image to the field, but am not sure how to encode it.
HTML
<form id="form" action="{% url ‘my_app:testFormPage' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<div id="signature-pad">
<canvas></canvas><br>
</div>
 <input type="hidden" name="signature" value=“signatureImage”>
<button type="submit" data-action="formSig">Submit</button>
</form>

Python
# Models.py
class testModel(models.Model):
name = models.CharField(max_length=50)
date = models.DateTimeField(default=timezone.now)
signature = models.ImageField (null=True, max_length=3000)
# Forms.py
class testForm(forms.ModelForm):
class Meta:
model = testModel
fields = ‘__all__’
widgets = { 'signature': forms.HiddenInput(),}
# Views.py
def testFormPage(request):
if request.method == 'POST':
form = testForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = testForm()
context = {'form': form}
return render(request, 'client_visits/testFormPage.html', context)
Javascript

The full javascript app can be found at https://github.com/szimek/signature_pad/tree/master/docs/js. Here’s just what I added
var formSig = wrapper.querySelector("[data-action=formSig]");
formSig.addEventListener("submit", function (event) {
var signatureImage = signaturePad.toDataURL();
});

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.

REST API ajax not working

I am working on a school project where I have to program a REST API application that interacts with a database with basic POST and DELETE operation:
Here is my Python Flask file:
from flask import Flask, render_template, redirect, url_for, jsonify, request, Response, abort
from flask_bootstrap import Bootstrap
import dbinteraction
app = Flask(__name__)
Bootstrap(app)
#app.route('/')
def hello_world():
return redirect(url_for('index'))
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/allrecipes')
def allrecipes():
return render_template('allrecipes.html')
#app.route('/ingredients')
def ingredients():
return render_template('ingredients.html')
#app.route('/api/v1.0/recipes', methods=['GET'])
def get_recipes():
# init
recipes = []
# get the task list from the db
recipes_list = dbinteraction.getRecipes()
# prepare the task list for jsonify
for item in recipes_list:
recipe = prepare_for_json(item)
recipes.append(recipe)
# return the task data
return jsonify({'recipes': recipes})
#app.route('/api/v1.0/ingredients', methods=['GET'])
def get_ingredients():
# init
ingredients = []
# get the user_ingredients list from the db
ingredients_list = dbinteraction.getIngredients()
# prepare the user_ingredients list for jsonify
for item in ingredients_list:
ingredient = prepare_for_json_ingredient(item)
ingredients.append(ingredient)
# return the ingredients data
return jsonify({'ingredients': ingredients})
#app.route('/api/v1.0/ingredients', methods=['POST'])
def insert_ingredient():
# get the request body
add_request = request.json
# check whether an ingredient is present or not
if (add_request is not None) and ('name' in add_request) and ('quantity' in add_request):
text = add_request['name']
quantity = add_request['quantity']
# insert in the database
dbinteraction.insertIngredients(text, quantity)
return Response(status=201)
# return an error in case of problems
abort(403)
#app.route('/api/v1.0/ingredients/<string:ing_name>', methods=['DELETE'])
def delete_ingredient(ing_name):
# delete the ingredient
ingredient = dbinteraction.removeIngredient(str(ing_name))
return Response(status=200)
def prepare_for_json(item):
"""
Convert the recipe in a dictionary for easing the JSON creation
"""
recipe = dict()
recipe['name'] = item[0]
recipe['link'] = item[1]
recipe['difficulty'] = item[2]
return recipe
def prepare_for_json_ingredient(item):
"""
Convert the ingredient in a dictionary for easing the JSON creation
"""
ingredient = dict()
ingredient['name'] = item[0]
ingredient['quantity'] = item[1]
return ingredient
if __name__ == '__main__':
app.run(debug=True)
I also programmed and tested the dbinteraction functions for the database and they work fine. My problem is in the ingredients.html part. I load and see the page as I want, a modifiable list of ingredients with the delete button. But when I click on the delete I get a Uncaught ReferenceError: (name of the ingredient) is not defined at HTMLAnchorElement.onclick
This are my html and javascript files:
{% extends "bootstrap/base.html" %}
{% block title %}All recipes page{% endblock %}
{% block styles %}
{{super()}}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.12/css/all.css"
integrity="sha384-G0fIWCsCzJIMAVNQPfjH08cyYaUtMwjJwqiRKxxE/rx96Uroj1BtIQ6MLJuheaO9" crossorigin="anonymous">
{% endblock %}
{% block scripts %}
{{ super() }}
<script src="{{ url_for('static', filename='kima2js.js') }}"></script>
{% endblock %}
{% block content %}
<div class="container" style="text-align: center">
<h1><i class="fas fa-utensils" style=""></i><br>
Insert an ingredient:
</h1>
<div id="ingredients_list" class="form-inline"></div>
<div id="insertingredient">
<form id="addForm"class="form-inline" method="POST">
<div class="form-group">
<label for="ingredientName">Ingredient:</label>
<input type="text" id="ingredientName" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="ingredientQuantity">Quantity:</label>
<input type="text" id="ingredientQuantity" class="form-control" name="quantity"/>
</div>
<button type="submit" class="btn-sm">Add</button>
</form>
</div>
</div>
{% endblock %}
... the javascript:
function addIngredient() {
$("#ingredients_list ul").empty();
$("#ingredientName").val('');
$("#ingredientQuantity").val('');
getIngredients();
}
function getIngredients() {
$.getJSON("http://127.0.0.1:5000/api/v1.0/ingredients", function(data){
var ingredients = data["ingredients"];
var len = ingredients.length;
for(var i = 0 ; i<len ; i++) {
var t = ingredients[i];
$("#ingredients_list ul").append("<li class='list-group-item list-group-item-text'>"+t.name+" "+t.quantity
+" <a class='delete btn btn-default' onclick='deleteIngredient("+ t.name +")'>" +
" <span class='glyphicon glyphicon glyphicon-remove'></span>Delete</a></li>");
}
});
}
function deleteIngredient(ing_name) {
$.ajax("/api/v1.0/ingredients/"+ing_name,
{
method: 'DELETE',
success: function (status) {
// update the list of printed ingredients: called when the DELETE is complete
getIngredients();
}
}
);
}
$(document).ready(function () {
$("#ingredients_list").append("<ul></ul>");
$("#ingredients_list ul").empty();
getIngredients();
$("#addForm").submit( function(){
var name = $("#ingredientName").val();
var quantity = $("#ingredientQuantity").val();
var ingredient = {'name': name, 'quantity': quantity};
var json = JSON.stringify(ingredient);
$.post({
"url": "http://127.0.0.1:5000/api/v1.0/ingredients",
"data": json,
"contentType":"application/json",
"success": addIngredient
});
return false;
});
});
I can't see what I am doing wrong. My only guesses are on the onclick part. Because I have tested singularly all the other pieces of code in previous labs
You just need to make sure that the value of ing_name is in quotes when you write it as a parameter to onclick, as follows:
$("#ingredients_list ul").append("<li class='list-group-item list-group-item-text'>"+t.name+" "+t.quantity
+" <a class='delete btn btn-default' onclick='deleteIngredient(\""+ t.name +"\")'>" +
" <span class='glyphicon glyphicon glyphicon-remove'></span>Delete</a></li>");
Otherwise javascript thinks ing_name is a variable name (and the variable is not defined).

Django website not checking the links correctly

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 %}

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()
...

Categories

Resources