Fullcalender display events in Django - python

I am using full calendar in my in my Django project and I was wondering how I would get the model data to load as an event within the calendar. The issue is whenever I try to load the template into my code it loads up a white page with text in JSON format.
I was wondering if it was possible to get by this.
This is how my model looks like:
class CalenderEvent(models.Model):
event_name = models.CharField(max_length = 30)
start_date = models.DateTimeField(null=True,blank=True)
end_date = models.DateTimeField(null=True,blank=True)
event_description = models.TextField()
def __str__(self):
return self.event_name
This is how my view looks like:
def calender(request):
events = CalenderEvent.objects.all()
if request.method == 'GET':
form = ContactToAddEventForm()
event_arr = []
for i in events:
event_sub_arr = {}
event_sub_arr['title'] = i.event_name
start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
event_sub_arr['start'] = start_date
event_sub_arr['end'] = end_date
event_arr.append(event_sub_arr)
return HttpResponse(json.dumps(event_arr))
context = {
"events" : events
}
return render(request, 'calender.htm', {'form': form}, context)
This is how my template looks like:
<link rel="stylesheet" href="{% static "fullcalender/daygrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/timegrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/core/main.css" %}" >
<script rel="stylesheet" href="{% static "fullcalender/core/main.js" %}" ></script>
<script src="{% static "fullcalender/core/main.js" %}"></script>
<script src="{% static "fullcalender/daygrid/main.js" %}"></script>
<script src="{% static "fullcalender/timegrid/main.js" %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'timeGrid' ],
defaultView: 'timeGridWeek',
events: [
{% for i in events %}
{
title: "{{ i.event_name}}",
start: '{{ i.start_date|date:"Y-m-d" }}',
end: '{{ i.end_date|date:"Y-m-d" }}',
},
{% endfor %}
]
});
calendar.render();
});
</script>
<section>
<div class="container">
<div id = "calendar"></div>
</div>
</section>
I was looking at this stack overflow answer:
FullCalendar in Django

Related

How to send data with Url Django

I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem
Image Error
Views.py:
def Detail_pem(request, idor):
print(idor)
return render(request, 'store/detail.html' )
pemby.html:
<!-- <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> -->
<button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> -->
<script>
var id_order = document.getElementsByClassName('id_order')
for (i = 0; i < id_order.length; i++) {
id_order[i].addEventListener('click', function(){
var orid = this.dataset.product
var ornm = this.dataset.act
console.log('orid :', orid)
console.log('ornm :', ornm)
window.location.href = "{% url 'Detail_pem' %}"
})
}
urls.py:
path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'),
You are redirecting through
window.location.href = "{% url 'Detail_pem' %}" without a variable.
But in your urls.py you are passing idor variable.
It should be: window.location.href = "{% url 'Detail_pem' order.id } %}".
And your urls.py change to this:
int:id
#if you are passing integer
path('Detail_pem/<int:id>', Detail_pem, name='Detail_pem'),
#or if you are passing string
path('Detail_pem/<str:id>', Detail_pem, name='Detail_pem'),

My point annotation in Chart.js 3.3.2 won't render in my Django template. Making a realtime graph of temperature for my wood-fired pizza oven

The goal and problem:
I'm having trouble getting an annotation to render in Chart.js. My project is a Django/Chart.js-run graph that shows the temperature of my wood fire pizza oven. I would like to see the temperature graphed over time and be able to submit a model form indicating when I have shut the door, and to have that annotated on the graph.
Specific issue
The issue is that I can't get the annotation to render on my graph, partly because I am unsure what x/y coordinate to put in. This can be seen in the const options variable in my index.html. In order, have attached my base.html, index.html, view.py, and forms.py. I also included a link to a screen shot of the graph so far and of my pizza oven in case you're curious. :P
Versions
I'm using Python 3.9.5, Chartjs 3.3.2, and Django 3.2.4.
Would be grateful for some help!
-Mike
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<!--Chartjs CDN-->
<!--<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock content %}
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper)
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>-->
</body>
</html>
{% extends 'base.html' %}
{% block content %}
<body>
<canvas id="myChart" width="600" height="400"></canvas>
<!--This chart will graph temperature of my oven. I would like to be able to annotate
the graph to show when I have closed my oven door. This annotation will be handled by a form, which
will store data inthe sqlite database. I would like to display an annotation on the graph but
I can't seem to get it working-->
<script>
const options = {
plugins: {
autocolors: false,
annotation: {
annotations: {
point1: {
type: 'point',
xValue: '{{ q_recent.dateposted }}', //I don't know what to put here to get the annotation
yValue: '{{ q_recent.dateposted }}', //I don't know what to put here to get the annotation
backgroundColor: 'rgba(255, 99, 132, 0.25)'
}
}
}
}
};
const config = {
type: 'line',
data: {
/* the labels and data are created in the view variable "q_recent" and then using the for loop
the labels and data are plugged in to the labels and data below*/
labels: [{% for q_recent in q_recent %} '{{ q_recent.dateposted }}', {% endfor %}],
datasets: [{
label: 'Pizza Oven Temp',
data: [{% for q_recent in q_recent %} '{{ q_recent.oventemperature }}', {% endfor %}],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.3
}]
},
options
};
var myChart = new Chart(document.getElementById('myChart'),config);
</script>
<!--reference to the model form below (called form, see forms.py) allows me to submit a true value
for the boolean variable "isdoorclosed'" to the database, marking when I have closed my oven door-->
<br>
<div class="col-md-4">
<div class="border p-3 shadow">
<form method="POST">
{% csrf_token %}
{{form}}
<input class="btn btn-danger btn-lg btn-block" type="submit" value="Enter">
</form>
</div>
</div>
</body>
{% endblock content %}
from django.shortcuts import render, redirect
from django.utils import timezone
import random
import time
from .forms import OvenDataForm
from .models import OvenData
def index(request):
#The next oven temperature data and store it in the database.
for i in range(1,15):
temp_random = random.randint(400,1000)
ambient_random = random.randint(13,20)
#the below two lines puts values in the database and sets the object to q for further refernece in the context
q = OvenData.objects.create(oventemperature=temp_random, ambienttemperature = ambient_random, dateposted = timezone.now(), timecloseddoor = timezone.now(), isdoorclosed = False)
q.save()
#this gives me the last 10 database values to be printed in the graph.
q_recent = OvenData.objects.all().order_by('-id')[:5]
#this will confirm that the latest value I am getting from the database is properly printed to the template
print(ambient_random)
print(temp_random)
"""the model variables below:
oventemperature = models.FloatField(null = True)
ambienttemperature = models.DecimalField(decimal_places=2, max_digits=20, null=True)
dateposted = models.TimeField(null = True)
timecloseddoor = models.DateTimeField(blank = True, null=True)
isdoorclosed = models.BooleanField(blank = True, default=False) """
if request.method == 'POST':
form = OvenDataForm(request.POST)
if form.is_valid():
# here I'm saying, don' save it yet, I want to change something about the data.
# In my case I'm putting other values along with the door closed variable coming from the form.
obj = form.save(commit=False)
obj.oventemperature = 799.9
obj.ambienttemperature = ambient_random
obj.dateposted = timezone.now()
obj.timecloseddoor = timezone.now()
print(q.isdoorclosed)
obj.save()
#I took out this redirect to the home page because it was loading the page again. I stopped
# this given this cues up the index view which causes random data to be generated and saved.
#return redirect('/')
else:
form = OvenDataForm()
context = {
'q_recent': q_recent,
'q': q,
'form': form
}
return render(request, 'index.html', context)
from django import forms
from .models import OvenData
"""
oventemperature = models.FloatField(null = True)
ambienttemperature = models.DecimalField(decimal_places=2, max_digits=20, null=True)
dateposted = models.TimeField(null = True)
timecloseddoor = models.DateTimeField(blank = True, null=True)
#using blank=false means that the field is required. Null=True means it can be empty in the database
isdoorclosed = models.BooleanField(blank = True, default=False)
"""
class OvenDataForm(forms.ModelForm):
#meta describes anything thats not a field
class Meta:
model = OvenData
fields = ['isdoorclosed']
exclude = []
#the labels section is a piece of meta data in the form allowing you to cutomize a field.
labels = {
'isdoorclosed': 'Tick here and submit when the door is closed ',
}
Goal Graph
My pizza oven
The reason there are no annotations showing is because you don't have a script tag pointing to the annotations plugin so it's never installed, if you add a script tag pointing at a CDN for the annotations lib as described here they will show: https://www.chartjs.org/chartjs-plugin-annotation/guide/integration.html#script-tag

Update a variable every 5 second using jquery

I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Like Post App</title>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div>
{% for post in posts %}
<div class = 'container jumbotron'>
<h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3>
<p class="lead">{{ post.post_text }} </p>
<p>
<div type="text/css" class = "container">Author : {{ post.post_author }}</div>
<a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}">
</p>
</div>
{% endfor %}
<script type="text/javascript">
setInterval(function() {
getvalue(); // Do something every 5 seconds
}, 5000);
getvalue();
function getvalue(){
var id;
id = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "like",
data:{
post_id: id
},
success: function( data )
{
$( '#like'+ id ).text("Like(" + data +")");
var i=parseInt(data);
console.log("Value= "+i);
}
}
)
}
</script>
</body>
</html>
Below is the views.py code:
import json
from django.shortcuts import render
from .models import Post, Like
from django.http import HttpResponse
# Create your views here.
#DataFlair #AJAX_tutorial
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', { 'posts': posts })
def like(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.objects.get(id = post_id )
m = Like.objects.filter( post=likedpost ).first()
m.counter +=1
m.save()
value1= int(m.counter)
#data1= {'cmd': 'success', 'ctr': str(m.counter) }
return HttpResponse(value1)
#return HttpResponse(json.dumps(data1))
else:
return HttpResponse("unsuccesful")
I keep getting the following errors:
1) GET http://localhost:8000/ajax/like/ 500 (Internal Server Error)
2) GET http://localhost:8000/favicon.ico 404 (Not Found)
Please help.
I believe:
id = $(this).attr("data-catid");
is not pointing to the button... maybe you should try:
id = $(".likebutton").attr("data-catid");

Flask variables not showing up in HTML

I have a small flask app I am using it to:
Make an HTML page with a leaflet map
Take user input from the HTML page...
Run calculations on that input using certain python modules
Return those variable to JS functions in the page to populate the map
I cannot get ANYTHING but lat and lng to return into my HTML {{}} flask variables.
Here is my HTML page:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 != None and lng1 != None %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
Here is my Flask Python code:
from flask import Flask, render_template, request, flash, redirect, url_for,jsonify
from forms import RegistrationForm
import json
import osmnx as ox
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
import pandas as pd
import mplleaflet
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY="powerful secretkey",
WTF_CSRF_SECRET_KEY="a csrf secret key"
))
#app.route('/')
def my_form():
return render_template('map.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
lat = (request.form['lat'])
lng = (request.form['lng'])
lat = lat
lng = lng
point = (lat,lng)
G = ox.core.graph_from_point(point, distance = 500, network_type='walk')
fig, ax = ox.plot_graph(G)
GJ = mplleaflet.fig_to_geojson(fig=ax.figure)
#return lat, ",", lng
return render_template('map.html', lat1=lat, lng1=lng, GeJ=GJ, point="test_string")`
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
The Flask app is working fine so the file structure is not a concern. I just cannot get any other variables to return into my HTML. I even tried making little string dummy variables other that the real ones. No Dice.
Thanks
You could try using the builtin none value http://jinja.pocoo.org/docs/templates/#none
Then do something like:
{% if lat1 is not none and lng1 is not none %}
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 is not Null and lng1 is not Null %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
It would help if you provided an example of what exactly happens when you pass all the values.
Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as:
{%if lat%} {{lat}} {% endif %}
Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there?
P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.

django two digit integer in choice field

I have a form that I want to submit date as mm/yyyy.
class Add_Serv(forms.Form):
month_add = forms.ChoiceField(required=True, choices=['01','02'])
year_add = forms.ChoiceField(required=True,
choices=[(x, x) for x in xrange(date.today().year - 1, date.today().year + 1)])
When my month prints out in form, it's only one digit integer 1 instead of 01. It doesn't sound like a big deal but it screws up my date format when handling these dates (and also looks very ugly). Is there any way to keep that zero before the number?
add validation in form's clean method and check if the length of month field is 1 or 2.
Append 0 before if length is 1 and return value of month
Print it out using format:
print("{:02d}".format(my_number))
See Pyformat for more formatting tips
use jquery library
You need only one field.
forms.py
class FormA(forms.Form):
fecha = forms.DateField(input_formats=['%m/%Y'])
views.py
def formulario(request):
if request.method == "POST":
form = FormA(request.POST)
if form.is_valid:
# action
else:
form = FormA()
return render(request,"add.html",{'form':form})
Your template
I add bootstrap css library and django-bootstrap-from
<div class="row">
<div class="col-lg-8">
<form id="form" action="" method="POST">
{{form|bootstrap_horizontal}}
{%csrf_token%}
<p align="right"><button id="enviar" type= 'submit' class="btn btn-success"> Guardar</button>
<button type= "reset" class="btn btn-warning"> Limpiar</button></p>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('#id_fecha').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
The result
http://prntscr.com/7qd01v

Categories

Resources