Like button showing same number of likes on different pages - facebook-like

I have a site problemio dot com (not posting url so it doesnt look like I am just trying to get links, etc.)
On the photo in the home page, there are 7 different links to categories. In each category there is the same number of likes. I don't understand why.
Here is the FB snippet I use:
<div style="margin: 0 auto; width: 100px; padding-left: 55px; padding-bottom: 15px;">
<center><div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=234415063262341";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://www.problemio.com" data-send="false" data-layout="button_count" data-width="450" data-show-faces="true"></div>
</center>
</div>
Thanks!

Does data-href="http://www.problemio.com" have to be a unique page?
like data-href="http://www.problemio.com/category/photos" and or
data-href="http://www.problemio.com/about"
so that way each page can be liked?

Use each page's own canonical URL on each data-href.

Related

Django Template Variable Failing as href Value

I have created a Django template which serves as an email template for my app. Upon certain actions, a celery task sends an email from this template using Sendgrid. Previously I hard-coded the URLs but now I need them to be dynamic. I am passing the url string as a variable called profile_url. I know that the URL is formatted correctly because I am printing it before calling the send_mail() function. If I use the value like so it works:
<p>{{ profile_url }}</p>
However, when I use it as an href value the link renders unclickable:
<a
href="{{ profile_url }}"
target="_blank"
style="
text-decoration: none;
color: #ffffff;
line-height: 40px;
display: block;
"
>Go to your profile</a>
If anyone can assist me or at least point me in the right direction here I'd greatly appreciate it!
<a
href="{{ modelname.profile_url }}"
target="_blank"
style="
text-decoration: none;
color: #ffffff;
line-height: 40px;
display: block;
"
>Go to your profile</a>
you have to called field with its model name and i also assume that this profile_url is in models.URLField still getting error add your model

My "cart" cookie in the request passed to my Django view is empty despite it showing in browser storage

I have a store page on my site (written in Django w/ a Passenger server) where users can add products to their shopping cart. The cart is stored as a cookie. When they proceed from the store page to the cart page, the cart view should list all of the items in their cart (which it gets from the cart cookie in the request). This works fine when I run it locally. However, when I run this in production, it almost always says the cart is empty. It only lists the cart items properly if I do a hard refresh of the page.
I've added some print statements to the server, and I can see that the view for the page is being called twice in prod (it's only called once in dev). The first time the view is called, the cart cookie has the correct values. The second time it's called however, the cart cookie in the request is an empty object {}. All other cookies in the request look normal (session id, csrftoken, etc). What's very strange is I can see in the browser's developer panel that the cart cookie is populated in both the request's header cookie tab as well as the storage tab.
Django view/utility functions:
def cart_view(request):
data = cart_data(request)
context = {
'items': data['items'],
'order': data['order'],
'cart_items': data['cart_items'],
}
return render(request, 'store/cart.html', context)
def cart_cookie(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
return cart
def cart_data(request):
cart = cart_cookie(request)
items = []
order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False}
cart_items = order['get_cart_items']
'''
Logic to parse the cart cookie
'''
return {
'items': items,
'order': order,
'cart_items': cart_items,
}
Here's the functions on the store page to populate the cart:
var updateBtns = document.getElementsByClassName('update-cart');
for (var i = 0; i < updateBtns.length; i++) {
updateBtns[i].addEventListener('click', function() {
var productId = this.dataset.product;
var action = this.dataset.action;
updateCartCookie(productId, action);
})
}
function updateCartCookie(productId, action) {
if (action == 'add') {
if (cart[productId] === undefined) {
cart[productId] = {'quantity':0};
}
cart[productId]['quantity'] += 1;
} else if (action == 'remove') {
cart[productId]['quantity'] -= 1;
if (cart[productId]['quantity'] <= 0) {
delete cart[productId];
}
}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/;SameSite=Strict;Secure;";
location.reload();
}
This code is in the page header to initialize the cookies. It's not being called on navigation to the cart page.
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++){
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken'); // this is just a string
var cart = JSON.parse(getCookie('cart')); // this is a json object, so we need to parse it
if (cart == undefined) {
cart = {};
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/;SameSite=Strict;Secure;";
}
</script>
And finally, here are the templates for the Store and Cart pages
#Store
{% block content %}
{% load static %}
<div class="container">
<h1 class="page-title">Store</h1>
<div class="row" style="margin-bottom: 20px">
{% for product in products %}
<div class="col-lg-4" style="margin-bottom: 20px">
<img class="thumbnail" src="{{product.imageURL}}">
<br>
<div class="box-element product">
<div>
<h4><strong>{{product.name}}</strong></h4>
<hr>
<p>
{{product.description}}
</p>
</div>
<div style="display: flex; justify-content: space-between; align-items: center;">
<h4>{{ product.price|floatformat:-2 }}</h4>
<button data-product={{product.id}} data-action="add" class="btn light update-cart">Add</button>
</div>
</div>
</div>
{% endfor %}
</div>
<div>
<a style="float: right; margin: 5px;" class="btn dark" href="{% url 'cart' %}">Cart</a>
</div>
</div>
{% endblock content %}
#Cart
{% block content %}
<div class="container">
<h1 class="page-title">Cart</h1>
<div class="">
<a class="btn button light" href="{% url 'store' %}">← Store</a>
<br>
<br>
{% if cart_items == 0 %}
<p style="text-align: center;">Your cart is empty.</p>
{% else %}
<div>
<div class="cart-row">
<div class="shrinking-flex-column-2-1"><strong>Item</strong></div>
<div class="static-flex-column-1"><strong>Price</strong></div>
<div class="static-flex-column-1"><strong>Quantity</strong></div>
<div class="static-flex-column-1"><strong>Total</strong></div>
</div>
{% for item in items %}
<div class="cart-row" style="align-items: center;">
<div class="shrinking-flex-column-2-1">{{item.product.name}}</div>
<div class="static-flex-column-1">${{item.product.price}}</div>
<div class="static-flex-column-1">
<p class="quantity">x{{item.quantity}}</p>
<div class="quantity">
<img class="chg-quantity update-cart" src="{% static 'store/images/arrow-up.png' %}" data-product={{item.product.id}} data-action="add" >
<img class="chg-quantity update-cart" src="{% static 'store/images/arrow-down.png' %}" data-product={{item.product.id}} data-action="remove" >
</div>
</div>
<div class="static-flex-column-1">${{item.get_total}}</div>
</div>
{% endfor %}
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<h5>Total Order Items: <strong>{{order.get_cart_items}}</strong></h5>
<h5>Total Order Amount: <strong>${{order.get_cart_total}}</strong></h5>
</div>
<a class="btn dark" role="button" href="{% url 'checkout' %}">Checkout</a>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock content %}
This ended up being entirely a caching issue. Adding the #never_cache decorated to the cart/checkout views fixed the problem.
How to set cache control headers in a Django view class (no-cache)

Maps java script API to Django project

I am creating a real estate web platform with Django and postgresql back-end. I have implemented maps API in my HTML template in order to show where the real estate is located.
The code:
<!--Map-->
<div class="row mb-5">
<div class="col-md-12">
<style>
#map{
height:250px;
width: 100%;
}
</style>
<div id="map"></div>
<script>
function initMap(){
var myLatLng = {lat:-33.90, lng:151.16};
var options = {
zoom:10,
center:myLatLng
};
var map = new
google.maps.Map(document.getElementById('map'),options);
}
</script>
</div>
</div>
Markers will be added in the next step because I have to figure out how I can retrieve my LAT and LNG values from the database and display them inside the script. Does anyone have the answer?
To explain that a bit further, I want to make something like
<script>
function initMap(){
var myLatLng = {lat:{{listing.geo_lat}}, {{listing.geo_lng}}};
var options = {
zoom:10,
center:myLatLng
};
But I have tried that and it seems that either google api cant read the proper format of my values or listing.geo_lat is not properly working inside the script.
Dont really know if it's an optimised solution but that works.
<div class="row mb-5">
<div class="col-md-12">
<style>
#map{
height:250px;
width: 100%;
max-width: none;
}
</style>
<div id="map"></div>
<script>
let lat = "{{listing.lat}}";
let lng = "{{listing.lng}}";
let geo_lat = parseFloat(lat);
let geo_lng = parseFloat(lng);
function initMap(){
var myLatLng = {lat:geo_lat, lng:geo_lng};
var options = {
zoom:11,
center:myLatLng
};
var map = new
google.maps.Map(document.getElementById('map'),options);
}
</script>
</div>
</div>

How to use GeoDjango Pointfield in Form?

I wanted to know to to use the PointField widget that is automatically generated from a Django form.
I am using the generic views for this (CreateView)
This is what my model looks like.
from django.contrib.gis.db import models
class Post(models.Model):
title = models.CharField(max_length=60)
text = models.CharField(max_length=255)
location = models.PointField(geography=True, null=True, blank=True)
objects = models.GeoManager()
The form is then automatically generated for me and I just call it in my view. As such:
{{ form.as_p }}
This is the output of that piece of code.
<form method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='wVZJIf7098cyREWe3n3jiZinPdbl8nEe' />
<p><label for="id_title">Title:</label> <input id="id_title" maxlength="60" name="title" type="text" /></p>
<p><label for="id_text">Text:</label> <input id="id_text" maxlength="255" name="text" type="text" /></p>
<p><label for="id_location">Location:</label> <style type="text/css">
#id_location_map { width: 600px; height: 400px; }
#id_location_map .aligned label { float: inherit; }
#id_location_div_map { position: relative; vertical-align: top; float: left; }
#id_location { display: none; }
.olControlEditingToolbar .olControlModifyFeatureItemActive {
background-image: url("/static/admin/img/gis/move_vertex_on.png");
background-repeat: no-repeat;
}
.olControlEditingToolbar .olControlModifyFeatureItemInactive {
background-image: url("/static/admin/img/gis/move_vertex_off.png");
background-repeat: no-repeat;
}
</style>
<div id="id_location_div_map">
<div id="id_location_map"></div>
<span class="clear_features">Delete all Features</span>
<textarea id="id_location" class="vSerializedField required" cols="150" rows="10" name="location"></textarea>
<script type="text/javascript">
var map_options = {};
var options = {
geom_name: 'Point',
id: 'id_location',
map_id: 'id_location_map',
map_options: map_options,
map_srid: 4326,
name: 'location'
};
var geodjango_location = new MapWidget(options);
</script>
</div>
</p>
<input type="submit" value="Create" />
</form>
In the head tags I import an OpenLayers script from
http://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js
However, the page will not show anything for the pointfield. (The other fields work just fine).
In chromedevtools it shows this error
Uncaught ReferenceError: MapWidget is not defined
For this line of code
var geodjango_location = new MapWidget(options)
Basically I want to know if there is someother javascript library I should be linking to or am I missing something else?
I've looked through the documentation on GeoDjango forms, but don't know what else to try
https://docs.djangoproject.com/en/dev/ref/contrib/gis/forms-api/
Add this to the head section:
<head>
{{ form.media }}
</head>
I have a related problem with my Admin UI. My solution is just a reference for your problem. Firefox browser was blocking the loading of mix http/https http://openlayers.org/api/2.13/OpenLayers.js because my geodjango site forces https.
One solution is to download the OpenLayer.js into my geodjango project static directory, and add the following line to my CustomGeoModelAdmin:
class MyCustomGeoModelAdmin(....):
openlayers_url = '/static/mygeodjangoproject/OpenLayers.js'
#property
def media(self):
"Injects OpenLayers JavaScript into the admin."
media = super(MyCustomGeoModelAdmin, self).media
media.add_js([self.openlayers_url])
return media
and voilà, my admin site now shows a Geographical Map for the Point Field.

Cant get Facebook like button to include certain image

I cant seem to get the Facebook like button to include my image, checked the facebook dev docs and implemented what they say but i must be doing something wrong cause its picking a completely different image.
Here is my code:
in
<meta property="og:image" content="http://url.com/images/81341089.jpg" />
And the button..
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=313222255403082";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://url.com/index.php" data-send="false" data-layout="button_count" data-width="120" data-show-faces="true"></div>
Any ideas?
Getting super frustrated :))
Try this
<script>function fbs_click() {u=location.href;t=document.title;
window.open(‘http://www.facebook.com/sharer.php?u=’+encodeURIComponent(u)+
’&t=’+encodeURIComponent(t),’sharer’,'toolbar=0,status=0,width=626,height=436′);
return false;}</script>
<a href=”http://www.facebook.com/share.php?u=<url>” onclick=”return fbs_click()” target=”_blank”>
<img src=”**ADD_IMAGE_URL_HERE**” alt=”Share on Facebook” />
</a>
I found it here http://www.business.com/b2bmarketing/create-share-buttons/