FullCalendar in Django - python

So, I have an appointment models
class Appointment(models.Model):
user = models.ForeignKey(User)
date = models.DateField()
time = models.TimeField()
doctorName = models.CharField(max_length=50)`
And I want to implement this in the FullCalendar tool. I'm not sure how to even begin. Any help is appreciated. Thanks.

Since your question shows you haven't tried anything , guessing you know javascript and tried some hands on full calendar js.
Suppose you have model named Event for displaying different events in calendar.
class Events(models.Model):
even_id = models.AutoField(primary_key=True)
event_name = models.CharField(max_length=255,null=True,blank=True)
start_date = models.DateTimeField(null=True,blank=True)
end_date = models.DateTimeField(null=True,blank=True)
event_type = models.CharField(max_length=10,null=True,blank=True)
def __str__(self):
return self.event_name
In your views.py
def event(request):
all_events = Events.objects.all()
get_event_types = Events.objects.only('event_type')
# if filters applied then get parameter and filter based on condition else return object
if request.GET:
event_arr = []
if request.GET.get('event_type') == "all":
all_events = Events.objects.all()
else:
all_events = Events.objects.filter(event_type__icontains=request.GET.get('event_type'))
for i in all_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":all_events,
"get_event_types":get_event_types,
}
return render(request,'admin/poll/event_management.html',context)
And finally in your template setup full calendar with including necessary CSS,JS Files and HTML code.And then ,
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultDate: '2016-07-19',
editable: true,
eventLimit: true, // allow "more" link when too many events
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 %}
]
});
});
</script>
Dynamically on some event you need to change events for example by changing dropdown you need to filter events ,
$(document).ready(function(){
$('.event_types').on('change',function(){
var event_type = $.trim($(this).val());
$.ajax({
url: "{% url 'manage-event' %}",
type: 'GET',
data:{"event_type":event_type},
cache: false,
success: function (response) {
var event_arr = $.parseJSON(response);
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', event_arr);
$('#calendar').fullCalendar('rerenderEvents' );
},
error: function () {
alert("error");
}
})
})
})

You can use following code to add, remove, update event in full calendar:
model:
class Events(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255,null=True,blank=True)
start = models.DateTimeField(null=True,blank=True)
end = models.DateTimeField(null=True,blank=True)
def __str__(self):
return self.name
view:
def calendar(request):
all_events = Events.objects.all()
context = {
"events":all_events,
}
return render(request,'calendar.html',context)
def all_events(request):
all_events = Events.objects.all()
out = []
for event in all_events:
out.append({
'title': event.name,
'id': event.id,
'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"),
'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"),
})
return JsonResponse(out, safe=False)
def add_event(request):
start = request.GET.get("start", None)
end = request.GET.get("end", None)
title = request.GET.get("title", None)
event = Events(name=str(title), start=start, end=end)
event.save()
data = {}
return JsonResponse(data)
def update(request):
start = request.GET.get("start", None)
end = request.GET.get("end", None)
title = request.GET.get("title", None)
id = request.GET.get("id", None)
event = Events.objects.get(id=id)
event.start = start
event.end = end
event.name = title
event.save()
data = {}
return JsonResponse(data)
def remove(request):
id = request.GET.get("id", None)
event = Events.objects.get(id=id)
event.delete()
data = {}
return JsonResponse(data)
urls:
from .views import calendar, add_event, update, remove, all_events
url('^calendar', calendar, name='calendar'),
url('^add_event$', add_event, name='add_event'),
url('^update$', update, name='update'),
url('^remove', remove, name='remove'),
url('^all_events', all_events, name='all_events')
html:
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css"/>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function () {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: '/all_events',
selectable: true,
selectHelper: true,
editable: true,
eventLimit: true,
select: function (start, end, allDay) {
var title = prompt("Enter Event Title");
if (title) {
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
type: "GET",
url: '/add_event',
data: {'title': title, 'start': start, 'end': end},
dataType: "json",
success: function (data) {
calendar.fullCalendar('refetchEvents');
alert("Added Successfully");
},
error: function (data) {
alert('There is a problem!!!');
}
});
}
},
eventResize: function (event) {
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
type: "GET",
url: '/update',
data: {'title': title, 'start': start, 'end': end, 'id': id},
dataType: "json",
success: function (data) {
calendar.fullCalendar('refetchEvents');
alert('Event Update');
},
error: function (data) {
alert('There is a problem!!!');
}
});
},
eventDrop: function (event) {
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
var title = event.title;
var id = event.id;
$.ajax({
type: "GET",
url: '/update',
data: {'title': title, 'start': start, 'end': end, 'id': id},
dataType: "json",
success: function (data) {
calendar.fullCalendar('refetchEvents');
alert('Event Update');
},
error: function (data) {
alert('There is a problem!!!');
}
});
},
eventClick: function (event) {
if (confirm("Are you sure you want to remove it?")) {
var id = event.id;
$.ajax({
type: "GET",
url: '/remove',
data: {'id': id},
dataType: "json",
success: function (data) {
calendar.fullCalendar('refetchEvents');
alert('Event Removed');
},
error: function (data) {
alert('There is a problem!!!');
}
});
}
},
});
});
</script>
</head>
<body>
<br/>
<h2 align="center">title</h2>
<br/>
<div class="container">
<div id="calendar"></div>
</div>
</body>
</html>
Example:To add event to fullcalendar you should add event to your model or if you don't want to save them you should create event and send to fullcalendar(in def calendar). For example to add event to all Sundays of 2020:
view:
def calendar(request):
from datetime import date, timedelta
d = date(2020, 1, 1)
d += timedelta(days=6 - d.weekday()) # First Sunday
all_sunday_in_2020 = []
while d.year != 2021:
all_sunday_in_2020.append({'name': 'my-title', 'start': d, 'end': d
+ timedelta(days=1)})
d += timedelta(days=7)
return render(request,'calendar.html',{'events':all_sunday_in_2020})

Related

jquery ajax function undo not working as expected

I have a list of words, and want users to be able to click a button if they know a word, then this word will change to 'Known', the css class will change and the field word_is_known will change from False to True. But I also want the user to be able to undo this action. This seems to be working fine the first time, i.e. if the user clicks and then unclicks. But if the user clicks the same word again, it creates another entry into the KnownWord model instead of updating the existing one. I've been playing around with this endlessly, but can't figure it out.
Here is my jquery:
$(document).ready(function() {
var known_words = 0;
var clicked_words = [];
var unclicked_words = [];
$(".word_known").click(function() {
var reference = this;
var objectpk = $(this).data('objectpk');
var userpk = $(this).data('userpk');
$(this).toggleClass('increment');
if ($(this).hasClass('increment')) {
known_words++;
clicked_words.push($(this).data('word'));
add_object = 'add';
$.ajax({
async: false,
url: "/videos/songs/vocab/known/"+objectpk+"/"+userpk+"/",
data: {'action': add_object, 'known_words': known_words, 'clicked_words': clicked_words},
success: function(data) {
$(reference).removeClass("btn-warning");
$(reference).addClass("btn-success");
$(reference).text("Known");
},
failure: function(data) {
alert("There is an error!")
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
})
console.log(known_words, clicked_words);
}
else {
known_words--;
unclicked_words.push($(this).data('word'));
remove_object = 'remove';
$.ajax({
async: false,
url: "/videos/songs/vocab/known-undo/"+objectpk+"/"+userpk+"/",
data: {'action': remove_object, 'known_words': known_words, 'unclicked_words': unclicked_words},
success: function(data) {
$(reference).removeClass("btn-success");
$(reference).addClass("btn-warning");
$(reference).text("Yes");
},
failure: function(data) {
alert("There is an error!")
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
})
console.log(known_words, unclicked_words);
}
})
});
My views:
def word_known(request, object_pk, pk_user):
if request.method == 'POST':
pass
elif request.method == 'GET' and request.GET['action'] == 'add':
known_words = request.GET.get('known_words', '')
clicked_words = request.GET.getlist('clicked_words[]')
request.session['known_words'] = known_words
request.session['clicked_words'] = clicked_words
user = request.user
song = models.Song.objects.get(pk=object_pk)
for word in set(clicked_words):
models.KnownWord.objects.get_or_create(word_is_known=True,
word=word, user=user, song=song)
print('The number of known words is {} and clicked words are {}'.format(known_words, clicked_words))
return HttpResponse(json.dumps(clicked_words), content_type='application/json')
def word_known_undo(request, object_pk, pk_user):
if request.method == 'POST':
pass
elif request.method == 'GET' and request.GET['action'] == 'remove':
known_words = request.GET.get('known_words', '')
unclicked_words = request.GET.getlist('unclicked_words[]')
request.session['known_words'] = known_words
request.session['unclicked_words'] = unclicked_words
user = request.user
song = models.Song.objects.get(pk=object_pk)
for word in set(unclicked_words):
models.KnownWord.objects.filter(word=word,
user=user, song=song).update(word_is_known=False)
print('The number of known words is {} and deleted words are {}'.format(known_words, unclicked_words))
return HttpResponse(json.dumps(unclicked_words), content_type='application/json')
The KnownWord model:
class KnownWord(models.Model):
word_is_known = models.BooleanField(default=False)
word = models.CharField(max_length=25)
user = models.ForeignKey(User, related_name="known_words", on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete=models.CASCADE, null=True, blank=True)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True)
And the relevant part from my template:
....
{% elif item.0 in known_words %}
Known
{% else %}
Yes
{% endif %}
Your problem here is you didn't remove the value from the other array
Its all about arrays push , check , splice take a look at the next example
$(document).ready(function(){
var clicked_words = [] ;
var unclicked_words = [];
var known_words = 0;
$(document).on('click' ,'.word_to_know:not(.pending)' , function(){ //<<<<<<<<<<< here
var This = $(this);
var This_data_word = This.data('word');
This.addClass('pending').toggleClass('increment');
if(This.hasClass('increment')){
known_words++;
clicked_words.push(This_data_word);
unclicked_words = remove_if_in_array(unclicked_words , This_data_word);
// inside ajax callback //<<<<<<< here
setTimeout(function(){ //<< don't use this .. this is just for the demo
This.removeClass('pending'); // <<<<<<<< here
} , 2000); //<< don't use this .. this is just for the demo
}else{
known_words--;
unclicked_words.push(This_data_word);
clicked_words = remove_if_in_array(clicked_words , This_data_word);
// inside ajax callback //<<<<<<< here
setTimeout(function(){ //<< don't use this .. this is just for the demo
This.removeClass('pending'); // <<<<<<<< here
} , 2000); //<< don't use this .. this is just for the demo
}
console.log('known_words '+known_words);
console.log('clicked_words [' +clicked_words +']');
console.log('unclicked_words [' + unclicked_words+']');
});
});
// remove value if is in the array
function remove_if_in_array(array , value){
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
// update value if is in the array
function update_if_in_array(array , value){
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
array.push(value);
return array;
}
a.increment{
border : 1px solid #000;
background : green;
color : #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Known
Yes
I make a single class for all <a> named it word_to_know you can change anything whatever you want .. But I hope you got the idea

How to pass parameters of Ajax URL in Django?

I used Ajax to add items to wishlist:
<a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to
wishlist</a>
the url looks like:
path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'),
but I don't know how to pass list.slug or title_slug in above url using Ajax:
$(document).on('click', '#wishlistbtn', function (e) {
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: e.target.getAttribute('data-slug')
},
success: function (response) {
alert('added to wishlist')
}
})
})
my above stated solution didn't work? Please help me with this. Thank you.
edit: View added
def wishlist(request):
slug = request.GET.get('title_slug')
obj = get_object_or_404(Listing, slug=slug)
profile = Profile.objects.all().filter(user=request.user).first()
profile.wishlist.add(obj)
return HttpResponse('true')
is this your solution to pass the data-slug ?
$(document).on('click', '#wishlistbtn', function (e) {
let el = $(this);
$.ajax({
type: 'GET',
url: "{% url 'listing:wishlist' %}",
data: {
title_slug: el.attr("data-slug"),
},
success: function (response) {
alert('added to wishlist')
}
})
})
use this path -
path('wishlist', wishlist, name='wishlist'),
in your views to get slug use - request.GET.get("title_slug")
I don't know exactly what you want to do but I had similar situation, I will share my code with you hopefully it helps you
HTML
<div class="btn-wrapper">
<p id="loadMore_articles" data-total="{{total_data}}" data-limit="3" data-slug="{{author.id}}" class="btn-default transparent-btn-2 .">load articles <i class=" load-more-icon"></i></p>
</div>
JQuery/JS
$(document).ready(function () {
$("#loadMore_articles").on('click', function () {
var _currentarticles = $(".article-box").length;
var _limit = $(this).attr('data-limit');
var _total = $(this).attr('data-total');
var _slug = $(this).attr('data-slug');
// Start Ajax
$.ajax({
url: 'author/articles/load-more-articles',
data: {
slug: _slug,
limit: _limit,
offset: _currentarticles
},
dataType: 'json',
beforeSend: function () {
$("#loadMore_articles").attr('disabled', true);
$("#loadMore_articles").html('');
$(".load-more-icon").addClass('fa-spin');
$("#loadMore_articles").addClass("button--loading");
},
success: function (res) {
console.log(res);
console.log(res.articles);
$("#articles").append(res.articles);
$("#loadMore_articles").attr('disabled', false);
$(".load-more-icon").removeClass('fa-spin');
$("#loadMore_articles").html('Load Articles');
$("#loadMore_articles").removeClass("button--loading");
if (res.articles == '') {
$("#loadMore_articles").remove();
}
}
});
// End
});
});
views.py
def author_ajax_articles(request):
author = int(request.GET['slug'])
offset=int(request.GET['offset'])
limit=int(request.GET['limit'])
data=News.objects.filter(Q(author=author)&Q(is_live=True))[offset:offset+limit]
t=render_to_string('author/ajax/article.html',{'articles':data})
return JsonResponse({'articles':t})
forgive my bad codes... I am still learning clean code but I hope this helps you in your quest

Django take value from url

I have problem with take value from url (?site=value). When I had function in views.py it was work, but now I moved this to another file. Can someone solve this problem?
functionAjax.py:
def htmlMain(request):
if request.is_ajax and request.method == "POST":
UrlCut = request.GET.get('site','Main')
Messages = NewsMessage.objects.all().order_by('-Data').values()
context = {
"Messags" : Messages
}
return render(request, 'ajax'+UrlCut+'.html', context)
AjaxFunction.js:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
let tech = ""
if($.urlParam('site') != null)
{
tech = "?site=" + $.urlParam('site');
}
UrlSet = "/get/ajax/validate/MainSite"+tech;
$.ajax({
url: UrlSet,
data: $('#FormSite').serialize(),
type: "POST",
async:false,
success: function(response) {
$("#AjaxChange").replaceWith(response);
},
error: function(data)
{
alert('Bad connection');
console.log(data);
}
});
use 'Site' instead of 'site' to get Site=value
UrlCut = request.GET.get('Site', 'Main')

error 405 get method not allowed

Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);

How can I display data sent through ajax in django?

I have the following setup but I can't seem to display content in ajax although it works if I go directly to the url.
<div class="test" style="width:200px; height:200px; border-style:solid;">
<button class="testb">click here</button>
</div>
Script:
$(".testb").click(function() {
$.ajax({
url: '../profile_page_tags_get/' + 'primary',
type: 'GET',
dataType: "json",
success: function(data) {
$(".test").html( "<div>" + data + "</div>")
}
})
});
View function:
def profile_page_tags_get(request, edit_type):
data = {}
if edit_type == 'primary':
p_options = Primary.objects.all()
data['p_options'] = list(p_options.values_list())
return HttpResponse(json.dumps(data), content_type = "application/json")
Url:
url(r'^profile_page_tags_get/(?P<edit_type>.*)/$', views.profile_page_tags_get, name='profile_page_tags_get'),

Categories