Django - Google Places API - Establishment - django

Trying to implement Google Places API, to look for businesses.
I am trying to break down the result in different sections (name,address,city...) to stick it in a form.
Doing a bit of research, I have actually found the ultimate code to copy. However, I am using Django and I am too much of a newbie in coding, to understand how to alter the code to make it work with the framework. (https://jsfiddle.net/geocodezip/ep5aw171/1/)
Here is the code I have:
js file
function initMap(){
autocomplete = new google.maps.places.Autocomplete(document.getElementById("input"),{
componentRestrictions: {'country':['uk']},
fields: ['name','geometry'],
types:['establishment']
});
autocomplete.addListener('place_changed');
}
html
<html>
<h1>Google Places API Test</h1>
<body>
<input id="input" placeholder="*Name API" style="height: 75px; width:1000px">
<script src="{% static 'google_places_names.js' %}"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=xxx&libraries=places&callback=initMap"></script>
</body>
</html>
This bit works. When I type an address, I get the address of the what I am looking for (see screenshot)
Given that I am planning to use a django form to capture the information, I am assuming the html to look like this:
<html>
<h1>Google Places API Test</h1>
<body>
<input id="input" placeholder="*Name API" style="height: 75px; width:1000px">
<form id="GoogleAPI" method="POST" action="{% url 'google_api_test'%}">
{% csrf_token %}
<label for="address" class="hidden-el" hidden>Address</label>
{{form.name}}
<label for="address" class="hidden-el" hidden>Address</label>
{{form.address}}
...
</form>
<script src="{% static 'google_places_names.js' %}"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=xxx&libraries=places&callback=initMap"></script>
</body>
</html>
Looking at the different answers on the topic, there seems to be lot of code to write,so I am expecting anyone to do this here. But I wondering if someone may know a link to a Django tutorial for Google API for businesses (establishment). Found a few online, but they do not cover establishements and the approach appears to be different.
I understand the next step would be to call is to call autocomplete.getPlace() within a function. But all attempts I made proved to unsuccessful.
Would be grateful if anyone had any pointers!

Related

How to Embed PDF in browser in Django instead of downloading it?

My problem is that the browser downloads the pdf instead of displaying it.
I tried some solutions from this site (for example) but none of them worked for me.
I use this code in my html file and nothing else:
{% load static %}
<body>
<object data="test.pdf" type="application/pdf" title="SamplePdf" width="500" height="720">
<embed src="{% static 'test.pdf' %}" >
</object>
</body>
Ideas?
Displaying PDF has nothing in common with Django, you can handle it with pure HTML:
Recommended way to embed PDF in HTML?
Have you tried:
<embed src="{% static 'test.pdf' %}" width="500" height="375"
type="application/pdf">
?

How to use django-markdownx in my view in similar way to admin?

I'm stuck using django-markdownx to automatically update page and to submit changes.
I followed this question and answer and managed to get django-markdownx working in admin, and within my view. However in my view editing the textarea does not automatically update the page.
The admin page with django-markdownx is exactly what I want, updating the textarea updates the page, but not the underlying database field until you hit save.
So I then tried to rip out the admin code into my own view.
In my view/template I have a form, textarea similar to admin one. I also included "/static/markdownx/js/markdownx.js" and set my form to mostly be similar to the admin page:
<form method="POST" action="">{% csrf_token %}
<div class="markdownx">
<textarea name="myfield" rows="10" cols="40" required="" data-markdownx-upload-urls-path="/markdownx/upload/" data-markdownx-editor-resizable="" class="markdownx-editor" id="id_myfield" data-markdownx-urls-path="/markdownx/markdownify/" data-markdownx-latency="500" data-markdownx-init="" style="transition: opacity 1s ease;">
{{ note.myfield }}
</textarea>
</div>
<div class="markdownx-preview">
{{ note.formatted_markdown|safe }}
</div>
</form>
This didn't work.
I see periodically there is requests to /markdownx/markdownify/ when you edit in admin, but not mine. I'm not sure if I should aim to do the same or just do some timed javascript page refresh and pass all the data from within my form back to my view to then re-render the page again.
I can't quite get my head around the django-markdownx documentation.
UPDATE:
The Documentation seems to suggest that a call to MarkdownX() should do the initialisation.
<script src="/static/markdownx/js/markdownx.js"></script>
...
<script type="text/javascript">
let parent = document.getElementsByClassName('markdownx');
let md = new MarkdownX( element, element.querySelector('.markdownx-editor'), element.querySelector('.markdownx-preview'));
</script>
But when I try this I get.
Uncaught ReferenceError: MarkdownX is not defined
Also I don't see any initialisation like this within the admin page.
Is there an example of using the django-markdownx in your own views similar to the usage within admin?
Thanks
LB
The following is a broken solution.
The correct method would be to use the MarkdownX's built-in Javascript, but I just can't get it to work, yet. So, I wrote my own. It may be of use to others.
In template html, include js.cookie.min.js in order to get the django csrftoken. Then a callback function which will be called when a change is made to the textarea. We then update the preview div with HTML code we received back from MarkdownX's markdownify call.
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
...
<script type="text/javascript">
function myMDFunc( elem ) {
input = elem.value;
var csrftoken = Cookies.get('csrftoken');
$.ajax(
{
type: "POST",
url: "/markdownx/markdownify/",
data: { CSRF: csrftoken, csrfmiddlewaretoken: csrftoken, content: input}
})
.done(function(data, status){
document.getElementById("markdownx-preview").innerHTML = data;
});
}
</script>
Still in the template html, in the form, call this function both for onchange and onkeyup.
<form method="POST" action=""> {% csrf_token %}
{{ note.title }}
<div class="markdownx">
<textarea onchange="myMDFunc(this)" onkeyup="myMDFunc(this)" cols="60" rows="5" name="text" >
{{ note.myfield }}
</textarea>
</div>
<div class="markdownx-preview" id="markdownx-preview">
{{ note.formatted_markdown|safe }}
</div>
<input type="submit" id="submit" name="submit">
</form>
In summary, a change to the textarea means we invoke the 'onchange' or 'onkeyup', which calls myMDFunc. Then myMDFunc does an ajax call with data which is the raw MarkDown code, the response to this call is the pretty HTML data. The callback within myMDFunc updates the preview with that pretty HTML.
It kinda works. I'm sure the real MarkdownX code will handle drag'n'drop of images and pacing the ajax calls to be nice to the server.

dotCMS - Creating a Custom page (page content-type)

EDIT:
My objective:
Create a news page template with header and footer and body.
The news page needs a form for a content editor to add content to with two fields: Headline and story.
Each news page requires its own SEO meta data (keywords / description title).
These stories need to be easy to find within the CMS for future editing etc etc.
What is the best way of going about this?
What I currently have is a "Page" content-type which has all the form fields I require.
To create a new news item, I currently do:
Go to Site Browser
Right-Click [myFolder]
Click "New" --> Page
Choose my page from the select box (that was the page content-type I created earlier)
I now see my form, fill it in and save/publish and I see it, but with the issues I expressed before.
I am pretty sure I am going about this in the wrong way, but what is the right way?
-------------
I am struggling to create a very basic page in dotCMS.
Here is what I want to do:
Create a form for a content editor to be able to add content to the page (Content-Type: Page called "myForm") DONE
The form contains all the default fields (seo stuff etc that comes with the Page content-type) + two extra text fields I have created (fieldA and fieldB) DONE
Create a container and add in the velocity variable names. DONE
Surround the velocity variable names in some HTML. <div>$fieldA</div> and <div>$fieldB</div> DONE
Create a new theme with a template.vtl file DONE
So that is all set up. I now go and create a new page in a folder via Site Browser choosing my new "Page" called "myForm" from the drop down menu. I see my form and enter my data, save and publish.
Result. I dont see any of my data. Just a blank page.
So I check the docs and see what I have missed.
There is a page explaining that I need to add in some velocity into my template.vtl that looks like this:
#if($dotPageContent && $dotPageContent.fieldA)
<div class="row">
#dotedit($!dotPageContent.inode,$!dotPageContent.fieldA)
</div>
#end
#if($dotPageContent && $dotPageContent.fieldB)
<div class="row">
#dotedit($!dotPageContent.inode,$!dotPageContent.fieldB)
</div>
#end
(link to dotCMS help page)
OK, so now when I check my page again, the data is indeed being displayed. But there is a problem. The HTML that is in my container does not get parsed.
E.g. <div>$fieldA</div> and <div>$fieldB</div> does not have the <div></div> tags.
So now I'm worried this is not the way to create pages.
The reason I chose the "Page" content-type was that it comes ready to go with the "Advanced Propertied" for the page like SEO meta data (which by the way all worked fine).
Can someone point out what I may have missed or perhaps a better way of going about this?
Thanks in advance.
If you could post your container and template code somewhere and include the links here I could help you resolve the issue for sure, but I think what might be happening is that you are confusing the Page Content Type with the Container defined Content Types.
Here is a quick explanation that might help conceptual differentiation:
http://screencast.com/t/PlEXKU9glGd
What I explain in the video is that the Page Content Types are for page properties only - not content addition. Like you want a different facebook link on many of your pages, or some other special property tied to each page. To place content in a container, you use a secondary "Content" Content Type, and you add that content type to a container's code field. When a page loads, the execution happens in this order, the Page content loads, page properties and metadata are set, the page calls a template that provides the layout, the template calls containers, the containers have the code that formats the content, and then the content executes in the order that it is placed in the container by the content publisher. The Page content type is not intended to really provide any information that the front end user actually sees other than the Page Title, page url, and properties and metadata that are set "silently" in the background html of the page.
You also might find it helpful to join the dotCMS communty forum: http://dotcms.com/forum/
Hope that helps
In addition to my other post, I did do the test with what you were trying to to, in a test advanced template, and the template.vtl file does display the Page Content, as long as you actually edit your page properties and set, in this case, field A:
<!DOCTYPE html>
<html lang="en">
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
#set($dotTheme = $contents.getEmptyMap())
#set($blah1 = $dotTheme.put("path", "/application/themes/one-pager/"))
#set($dotThemeLayout = $contents.getEmptyMap())
#set($blah2 = $dotThemeLayout.put("title", "Bear Mountain"))
<head>
#if($dotPageContent && $dotPageContent.fieldA)
<div class="row">
#dotedit($!dotPageContent.inode,$!dotPageContent.fieldA)
</div>
#end
##dotParse("${dotTheme.path}html_head.vtl")
</head>
#set($utilClass = $pageTitle.toLowerCase().replace(' ', '-'))
<body data-spy="scroll" data-target=".top-nav" data-offset="100">
<div class="body-wrapper">
#dotParse("${dotTheme.path}header.vtl")
<div class="content-wrapper" id="hotel">
<div class="container">
<div class="row">
<div class="col-sm-12">
<h2>The Lodge</h2>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-12">
<div class="wow fadeInLeft" data-wow-delay=".8s">
## Container: Default 2 (Page Content)
## This is autogenerated code that cannot be changed
#parseContainer('5eb11b21-6b13-4fb8-a823-1de20bba56c0')
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="wow fadeInRight" data-wow-delay="1.2s">
## Container: Default 3 (Page Content)
## This is autogenerated code that cannot be changed
#parseContainer('f1ba7688-453c-4c0d-a214-e5ac802b8034')
</div>
</div>
</div>
</div>
</div>
<div class="image-wrapper bg-image-1 hidden-xs" data-stellar-background-ratio="0.5"></div>
<div class="content-wrapper">
<div class="container">
<div class="row">
<div class="col-sm-12">
## Container: Default 1 (Page Content)
## This is autogenerated code that cannot be changed
#parseContainer('56bd55ea-b04b-480d-9e37-5d6f9217dcc3')
</div>
</div>
</div>
</div>
<div class="image-wrapper bg-image-2 hidden-xs" data-stellar-background-ratio="0.7"></div>
<div class="content-wrapper">
<div class="container">
<div class="row">
<div class="col-sm-12">
## Container: Default 4 (Page Content)
## This is autogenerated code that cannot be changed
#parseContainer('a6e9652b-8183-4c09-b775-26196b09a300')
</div>
</div>
</div>
</div>
</div>
#dotParse("${dotTheme.path}footer.vtl")
Powered by Dotcms - The Leading Open Source Java Content Management System
</body>
</html>
This was tested on demo.dotcms.com: U:admin#dotcms.com / P: admin

Struts OR Tiles OR ???...... JSP template solution

currently I'm using a JSP templating system which uses this example's lib ("/WEB-INF/tlds/template.tld").
I'm not even sure how it's called.
Anyway it seems like it's not too developed, it makes problems with form POST method, I have no idea who made it (just found it) and I've heard about Apache's Struts & Tiles.
I'm not even sure that Struts does what I'm talking about.
Down to business:
A page in my site has this JSP content, that utilizes the template:
<%# taglib uri="/WEB-INF/tlds/template.tld" prefix="template"%>
<template:insert template="/WEB-INF/main_template_page/template.jsp">
<template:put name="title" content="Title here" direct="true" />
<template:put name="content" content="/content.jsp" />
</template:insert>
The template is:
<%# taglib uri='/WEB-INF/tlds/template.tld' prefix='template'%>
<html>
<head>
<title>
<template:get name='title' />
</title>
<link type="text/css" rel="stylesheet" href="/styles.css" />
</head>
<body>
<div id="div_header">
<div class="content">
<%#include file='header.html'%>
</div>
</div>
<div id="div_content">
<template:get name='content' />
</div>
<div id="div_footer">
<%#include file='footer.html'%>
</div>
</body>
</html>
So as you see each page gives the template some parameters and it all works nice.
Is there a "well-established" system that does that? I'm sure there is; What its name? Which would you use for pretty much simple pages, but, has to support dynamic ones with code (JSP).
Quaternion is right that Tiles and SiteMesh are both pretty popular decoration frameworks. You can also use JSP .tag files to achieve this, as shown in this answer.
I've never used SiteMesh, but I've worked on several projects at work that use Tiles and I don't care for it -- to me it's just an extra layer that doesn't add enough bang-for-my-buck. Tag files have the added bonus of being a built-in part of JSP.
Apache Tiles and Sitemesh are the two most popular systems. Tiles is more in keeping with what you demonstrated.

build website for mobile and pc with django

I am trying to develop a website for mobile and pc browser with django.
and I am trying to figure out a best structure of the views and templates.
there is what I have tried:
1) use different url ( like http://example.com/mobile/ and http://example.com/ OR
http://example.com/?c=mobile ) to distinguish mobile and pc, and map them to different view which set different templates.
2) in the view set different template according to USER_CLIENT
3) use a wrapper layer of the view, the actual view just return the data to the wrapper, the wrapper set the different template.
Is there a common way to handle this in django? any suggestions and comments?
Use Django's "sites" framework for a mobile version at http://m.example.com.
I would recommended solution 3; using a decorator to inspect the clients User Agent and returning à different template in case of a mobile agent.
Have the decorator take two arguments: the normal template, and the mobile template.
From your view, return a dict The decorator may pass to the rendering function as context. There is a decorator called 'render_to' that does this very well, Google for it.
To deal with the use case where users want the full version, even when browsing from a mobile device, you may use a redirecting view that sets a cookie your decorator may check for.
best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
then in your template you are able to introduce stuff like:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>