Ajax pagination with class based view - python-3.x

I am trying apply ajax with pagination on my app .Using Class based Listview
#views.py
class HomePage(ListView):
model = Video
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(HomePage, self).get_context_data(**kwargs)
videos = Video.objects.filter(category='sub')
paginator = Paginator(videos, 5)
page = self.request.GET.get('page2')
try:
videos = paginator.page(page)
except PageNotAnInteger:
videos = paginator.page(1)
except EmptyPage:
videos = paginator.page(paginator.num_pages)
context['videos'] = videos
if self.request.is_ajax():
html = render_to_string('videos/index.html', context, request=self.request)
print(html)
return JsonResponse({'form' : html })
The Home template script
<script type="text/javascript">
$(document).ready(function(event){
$(document).on('click', '.page-link', function(event){
event.preventDefault();
var page = $(this).attr('href');
console.log(page)
$.ajax({
type: 'GET',
url: ,
data: {'page':'{{ page.number }}'},
dataType: 'json',
success: function(response){
$('#ajax_page_template').html(response['form'])
console.log("success")
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
1.The current error is in views.py local variable 'html' referenced before assignment
2.And what should I put in ajax --url: I tried to put url:page but that return url to 127.0.0.1:8000/?page=2/?page=2.

I had the same problem and got it working:
In views.py add "paginate_by = 4" and def get_template_names:
class HomePage(ListView):
...
paginate_by = 4
def get_template_names(self):
template_name = 'list.html'
if self.request.is_ajax():
template_name = 'list_ajax.html'
return template_name
Use 2 templates:
New list_ajax.html with the for loop:
{% for video in video_list %}
...
{% endfor %}
Existing template list.html:
<div id="image-list">
{% include 'list_ajax.html' %}
</div>
In the script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2.2.1/src/js.cookie.min.js"></script>
<script>
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$(document).ready(function(){
var page = 1;
var empty_page = false;
var block_request = false;
var num_pages=parseInt('{{ page_obj.paginator.num_pages }}')
$(window).scroll(function() {
var margin = $(document).height() - $(window).height() - 200;
if ($(window).scrollTop() > margin && empty_page == false &&
block_request == false) {
block_request = true;
page += 1;
if(num_pages-page >= 0) {
$.get('?page=' + page, function(data) {
block_request = false;
console.log(data)
$('#image-list').append(data);
}
);
}}
});
});
</script>

You have to declare the html variable before you use it. Like this:
html = ""
if self.request.is_ajax():
html = render_to_string('videos/index.html', context, request=self.request)
And the url you should put in the ajax call is the one corresponding to the relevant view (HomePage).
And change the following line:
return JsonResponse({'form' : html })
To:
render(request,'videos/index.html',JsonResponse(html))

Related

WKWebView addEventListener not receiving Calendly events

I'm trying to use Calendly within a WKWebView and receive an event when the user has created an appointment. The app is successfully receiving message events, however Calendly events are not appearing.
Here's the code:
import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
var webView: WKWebView!
var count = 0
var html = """
<html>
<head>
<meta name='viewport' content='width=device-width' />
</head>
<!-- Calendly inline widget begin -->
<div class="calendly-inline-widget" data-auto-load="false">
<script type="text/javascript" src="https://assets.calendly.com/assets/external/widget.js"></script>
<script>
Calendly.initInlineWidget({
url: 'https://calendly.com/XXX',
prefill: {
name: "John Doe",
email: "john#joe2.com",
customAnswers: {
a1: "yes"
}
}
});
</script>
</div>
<!-- Calendly inline widget end -->
</html>
"""
override func viewDidLoad() {
let config = WKWebViewConfiguration()
let js =
"""
function isCalendlyEvent(e) {
return e.data.event &&
e.data.event.indexOf('calendly') === 0;
};
window.addEventListener(
'message',
function(e) {
if (isCalendlyEvent(e)) {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(e.data);
}
}
);
function isCalendlyEvent(e) {
console.log('testing' + e.name);
return e.data.event &&
e.data.event.indexOf('calendly') === 0;
};
window.addEventListener('message', function(e){
console.log('In listener. Event.type: ' + event.type +
' e.data.event: ' + e.data.event + ' event: ' + JSON.stringify(e.data));
if (isCalendlyEvent(e)) {
console.log('calendly event!!!!');
window.webkit.messageHandlers.clickListener.postMessage('Calendly:' + e.data);
} else {
window.webkit.messageHandlers.clickListener.postMessage('Other:' + e.data);
}
});
"""
let script = WKUserScript(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
config.userContentController.addUserScript(script)
config.userContentController.add(self, name: "clickListener")
webView = WKWebView(frame: view.bounds, configuration: config)
view.addSubview(webView!)
self.webView.loadHTMLString(self.html, baseURL: nil)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
count = count + 1
print("Msg \(count): \(message.body) ")
}
}
The calendly message is only sent when the url includes the embed_domain query parameter. When Calendly.initInlineWidget is called inside of WKWebView the embed_domain query parameter is set to undefined.
To resolve this issue, you can update the url to include an embed_domain parameter:
Calendly.initInlineWidget({
url: 'https://calendly.com/XXX?embed_domain=example',
prefill: {
name: "John Doe",
email: "john#joe2.com",
customAnswers: {
a1: "yes"
}
}
});

How to select option from dropdown in selenium (NodeJs)

I want to write a script for testing dropdown inside the webpage. But, I was unable to do so in selenium using Nodejs. Is there any method to test dropdown in selenium(NodeJs).
Thanks in advance
You can create a select class like this and then use method based on your selection.
var SelectWrapper = function(selector) {
this.webElement = element(selector);
};
SelectWrapper.prototype.getOptions = function() {
return this.webElement.all(by.tagName('option'));
};
SelectWrapper.prototype.getSelectedOptions = function() {
return this.webElement.all(by.css('option[selected="selected"]'));
};
SelectWrapper.prototype.selectByValue = function(value) {
return this.webElement.all(by.css('option[value="' + value + '"]')).click();
};
SelectWrapper.prototype.selectByPartialText = function(text) {
return this.webElement.all(by.cssContainingText('option', text)).click();
};
SelectWrapper.prototype.selectByText = function(text) {
return this.webElement.all(by.xpath('option[.="' + text + '"]')).click();
};
module.exports = SelectWrapper;
Usage in test class
var SelectWrapper = require('./select-wrapper.js');
var mySelect = new SelectWrapper(by.id("validSelectTagID"));
describe("Select Wrapper",function(){
it("Handling the dropdown list",function(){
browser.get("http://validURL");
mySelect.selectByText("TextinDrop");
mySelect.selectByValue("ValueInDrop");
}) ;

Outdated Browser - Only show banner from IE8 and lower. Currently IE9 is included

I want this code to only display outdated browser from IE8 and lower. Currently it also shows a message for IE9, which I want to exclude. I did try to remove the IE9 part of the code from the lowerthan part of the code, but no luck.
I got the code from: https://github.com/burocratik/outdated-browser
/*!--------------------------------------------------------------------
JAVASCRIPT "Outdated Browser"
Version: 1.1.0 - 2014
author: Burocratik
website: http://www.burocratik.com
* #preserve
-----------------------------------------------------------------------*/
var outdatedBrowser = function(options) {
//Variable definition (before ajax)
var outdated = document.getElementById("outdated");
// Default settings
this.defaultOpts = {
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
}
if (options) {
//assign css3 property to IE browser version
if(options.lowerThan == 'IE8' || options.lowerThan == 'borderSpacing') {
options.lowerThan = 'borderSpacing';
} else if (options.lowerThan == 'IE9' || options.lowerThan == 'boxShadow') {
options.lowerThan = 'boxShadow';
} else if (options.lowerThan == 'IE10' || options.lowerThan == 'transform' || options.lowerThan == '' || typeof options.lowerThan === "undefined") {
options.lowerThan = 'transform';
} else if (options.lowerThan == 'IE11' || options.lowerThan == 'borderImage') {
options.lowerThan = 'borderImage';
}
//all properties
this.defaultOpts.bgColor = options.bgColor;
this.defaultOpts.color = options.color;
this.defaultOpts.lowerThan = options.lowerThan;
this.defaultOpts.languagePath = options.languagePath;
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
} else {
bkgColor = this.defaultOpts.bgColor;
txtColor = this.defaultOpts.color;
cssProp = this.defaultOpts.lowerThan;
languagePath = this.defaultOpts.languagePath;
};//end if options
//Define opacity and fadeIn/fadeOut functions
var done = true;
function function_opacity(opacity_value) {
outdated.style.opacity = opacity_value / 100;
outdated.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
// function function_fade_out(opacity_value) {
// function_opacity(opacity_value);
// if (opacity_value == 1) {
// outdated.style.display = 'none';
// done = true;
// }
// }
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
outdated.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
//check if element has a particular class
// function hasClass(element, cls) {
// return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
// }
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
return true;
}
}
return false;
};
})();
//if browser does not supports css3 property (transform=default), if does > exit all this
if ( !supports(''+ cssProp +'') ) {
if (done && outdated.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x);
};
})(i), i * 8);
}
}
}else{
return;
};//end if
//Check AJAX Options: if languagePath == '' > use no Ajax way, html is needed inside <div id="outdated">
if( languagePath === ' ' || languagePath.length == 0 ){
startStylesAndEvents();
}else{
grabFile(languagePath);
}
//events and colors
function startStylesAndEvents(){
var btnClose = document.getElementById("btnCloseUpdateBrowser");
var btnUpdate = document.getElementById("btnUpdateBrowser");
//check settings attributes
outdated.style.backgroundColor = bkgColor;
//way too hard to put !important on IE6
outdated.style.color = txtColor;
outdated.children[0].style.color = txtColor;
outdated.children[1].style.color = txtColor;
//check settings attributes
btnUpdate.style.color = txtColor;
// btnUpdate.style.borderColor = txtColor;
if (btnUpdate.style.borderColor) btnUpdate.style.borderColor = txtColor;
btnClose.style.color = txtColor;
//close button
btnClose.onmousedown = function() {
outdated.style.display = 'none';
return false;
};
//Override the update button color to match the background color
btnUpdate.onmouseover = function() {
this.style.color = bkgColor;
this.style.backgroundColor = txtColor;
};
btnUpdate.onmouseout = function() {
this.style.color = txtColor;
this.style.backgroundColor = bkgColor;
};
}//end styles and events
// IF AJAX with request ERROR > insert english default
var ajaxEnglishDefault = '<h6>Your browser is out-of-date!</h6>'
+ '<p>Update your browser to view this website correctly. <a id="btnUpdateBrowser" href="http://outdatedbrowser.com/">Update my browser now </a></p>'
+ '<p class="last">×</p>';
//** AJAX FUNCTIONS - Bulletproof Ajax by Jeremy Keith **
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
};//end function
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
displayResponse(request);
};
request.open("GET", file, true);
request.send(null);
}
return false;
};//end grabFile
function displayResponse(request) {
var insertContentHere = document.getElementById("outdated");
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
insertContentHere.innerHTML = request.responseText;
}else{
insertContentHere.innerHTML = ajaxEnglishDefault;
}
startStylesAndEvents();
}
return false;
};//end displayResponse
////////END of outdatedBrowser function
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Outdated Browser</title>
<meta name="description" content="A time saving tool for developers. It detects outdated browsers and advises users to upgrade to a new version.">
<!-- Styles -->
<link rel="stylesheet" href="../outdatedbrowser/outdatedbrowser.min.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
font-family: 'Open Sans', sans-serif; text-align: center;
background-color: #fafafa; color: #0a0a0a; line-height: 1.5em;
}
h1{font-size: 2.6em; line-height: 2em;}
h3, h4{line-height: 1em; margin: 2.5em 0 -.4em 0; text-transform: uppercase;}
h3 span, h4 span{text-transform: none;}
p{padding-bottom: 1em;}
p.designBy{position: absolute; bottom: 0; right: 1em; font-size: .8em;}
a {color: #0a0a0a;}
ul{list-style-type: none; padding: 0;}
</style>
</head>
<body>
<!-- ============= YOUR CONTENT ============= -->
<h1>Outdated Browser</h1>
<p>Remember: If you can't see the message, it's a good thing! You are using a modern browser :D</p>
<h3>DEFAULT properties but using jQuery (must support IE6+)</h3>
<p>bgColor: '#f25648', color: '#ffffff', lowerThan: 'transform' (<IE10), languagePath: 'your_path/outdatedbrowser/lang/en.html'</p>
<h3>What does it look like? <span>(it may differ in your tests) </span></h3>
<ul>
<li>IE7 - VISTA</li>
</ul>
<p class="designBy">by Bürocratik</p>
<!-- ============= Outdated Browser ============= -->
<div id="outdated"></div>
<!-- javascript includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="../outdatedbrowser/outdatedbrowser.js"></script>
<!-- plugin call -->
<script>
//USING jQuery
$(document).ready(function() {
outdatedBrowser({
bgColor: '#f25648',
color: '#ffffff',
lowerThan: 'transform',
languagePath: '../outdatedbrowser/lang/en.html'
})
})
console.log(outdatedBrowser);
</script>
</script>
</body>
</html>

Redirecting to mobile website using opencms

I have a website developed using OPENCMS. Now we have developed a mobile website. How do i add code or module to opencms so that when user visits from mobile, it will be redirected to mobile website.
Insert at the beginning of one of the pages in the editor.
<?php
function detect_mobile()
{
if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|sagem|sharp|sie-|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
return true;
else
return false;
}
$mobile = detect_mobile();
if($mobile === true)
header('Location: /mobile');
?>
<script type="text/javascript">
var url=***'http://yourmobilesite.com/***';
var host_name=document.location.hostname;
var request_uri=document.location.pathname;
var no_mobile=location.search;
var cookie=document.cookie;
function detect()
{
var ua=navigator.userAgent.toLowerCase();
var devices=['vnd.wap.xhtml+xml','sony','symbian','nokia','samsung','mobile',
'windows ce','epoc','opera mini','nitro','j2me','midp-','cldc-',
'netfront','mot','up.browser','up.link','audiovox','blackberry',
'ericsson','panasonic','philips','sanyo','sharp','sie-',
'portalmmm','blazer','avantgo','danger','palm','series60',
'palmsource','pocketpc','smartphone','rover','ipaq','au-mic',
'alcatel','ericy','vodafone','wap1','wap2','teleca',
'playstation','lge','lg-','iphone','android','htc','dream',
'webos','bolt','nintendo'];
for (var i in devices)
{
if (ua.indexOf(devices[i]) != -1)
{
return true
}
}
}
if (no_mobile!='?nomobile=1' && cookie.indexOf('no_mobile')==-1)
{
is_mobile=detect();
if (is_mobile)
{
window.location = url
}
}
else
{
if (cookie.indexOf('no_mobile') != -1)
{}
else
{
cookie_expires = new Date();
cookie_expires.setTime(cookie_expires.getTime()+60*60*24);
document.cookie = "no_mobile=1; expires="
+ cookie_expires.toGMTString()
+ "; path=/;"
}
}
</script>

How to make a Sharepoint Survey window open on page load

I've been working on looking for an answer to this issue for several days. I've created a survey on a Sharepoint 2010 site, and the person who I made it for wants it to open in a modal window on page load, instead of having to click "Respond to Survey" for this to happen.
I've tried multiple javascript based solutions, and so far I've gotten nothing. Is there any way to do this? And, if there is, is it possible that this solution could be ported to other pages, so that I can make other surveys or other sharepoint pages open in a modal window (on page load) instead of on a separate page?
Use .../yoursite/lists/yoursurvey/NewForm.aspx - It seems the Advanced setting "use open forms in dialog" doesn't work.
I have made this for a policy window. I made the whole thing inside of a content editor webpart which basically in invisible because the code has no appearence and I set the chrome type to none.
The other option is a feature which would replace the masterpage which is also not hard but requires a developement system for VS2010.
For the first method mentioned. You may have to strip the cookie stuff if you want it to load every time.
Create a new Content Editor Web Part with this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="disclaimer.js"></script>
Then create disclaimer.js:
_spBodyOnLoadFunctionNames.push("initialDisclaimerSetup");
var dialogTitle = "";
var dialogBody = "";
var dialogReturn = "";
var userID = _spUserId;
function initialDisclaimerSetup() {
if(getCookie("DisclaimerShown" + userID) == "Yes") {
return;
} else {
setCookie("DisclaimerShown" + userID, "No", 365);
}
getDisclaimerListItems();
}
function setCookie(cookieName, cookieValue, numExpireDays) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + numExpireDays);
document.cookie = cookieName + "=" + cookieValue + ";" +
"expires=" + ((numExpireDays == null) ? "" : expirationDate.toUTCString());
}
function getCookie(cookieName) {
if(document.cookie.length > 0) {
return document.cookie.split(";")[0].split("=")[1];
} else {
return "";
}
}
function getDisclaimerListItems() {
var listName = "Disclaimer";
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\/\">"
+ "<soap:Body>"
+ "<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
+ "<listName>" + listName + "</listName>"
+ "<query><Query><Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where></Query></query>"
+ "<ViewFields><ViewFields>"
+ "<FieldRef Name=\"Title\"/><FieldRef Name=\"Disclaimer\"/>"
+ "</ViewFields></ViewFields>"
+ "</GetListItems>"
+ "</soap:Body>"
+ "</soap:Envelope>";
$.ajax({
url: "_vti_bin/Lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=\"utf-8\"",
complete: processResult
});
}
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
dialogTitle = $(this).attr("ows_Title");
dialogBody = $(this).attr("ows_Disclaimer");
launchModelessDialog();
if(dialogReturn == 0) {
return false;
} else if(dialogReturn == 1) {
} else if(dialogReturn == 2) {
return false;
}
});
if(dialogReturn == 0) {
getDisclaimerListItems();
} else if(dialogReturn == 1) {
setCookie("DisclaimerShown" + userID, "Yes", 365);
} else if(dialogReturn == 2) {
window.close();
}
}
function GetRootUrl() {
var urlParts = document.location.pathname.split("/");
urlParts[urlParts.length - 1] = "";
return "https://" + document.location.hostname + urlParts.join("/");
}
function launchModelessDialog(){
if (window.showModalDialog) {
window.showModalDialog("./disclaimer.htm", window, "dialogWidth:700px;dialogHeight:700px");
} else {
objPopup = window.open("./disclaimer.htm", "popup1", "left=100,top=100,width=800,height=800,location=no,status=yes,scrollbars=yes,resizable=yes, modal=yes");
objPopup.focus();
}
}
Then create disclaimer.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript">
function initialRun() {
//var allArgs = dialogArguments;
var dialogTitle = dialogArguments.dialogTitle;
var dialogBody = dialogArguments.dialogBody;
dialogArguments.dialogReturn = "0";
document.getElementById('mainWrapper').innerHTML = "<h1>" + dialogTitle + "</h1>"
+ "<br/>" + dialogBody + "<br/><br/>";
}
function returnYes() {
dialogArguments.dialogReturn = 1;
window.close();
}
function returnNo() {
dialogArguments.dialogReturn = 0;
window.close();
}
function returnClose() {
dialogArguments.dialogReturn = 2;
window.close();
}
</script>
</head>
<body onload="initialRun()">
<div id="mainWrapper">
</div>
<div align="center">
<input name="acceptTOS" type="button" value="I Accept" onClick="returnYes();" />
<input name="acceptTOS" type="button" value="I Do NOT Accept" onClick="returnNo();" />
<input name="acceptTOS" type="button" value="Close" onClick="returnClose();" />
</div>
</body>
</html>
Then create a new Custom List called 'Disclaimer' and add a new column called 'Disclaimer' which allows for free text.

Resources