Facebook Graph api profile picture URL - facebook-graph-api

I'm trying to display the profile pic of the logged in user but for some reason the url gets changed. This is the function i've put together
function testAPI() {
FB.api('/me','GET',{"fields":"picture{url},name"},function(response) {
var url = response.picture.data.url;
console.log(url);
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
console.log(document.getElementById('status').innerHTML);
});
}
the first console log returns:
"https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p50x50/12036592_10153768750487873_8195289030629933305_n.jpg?oh=5488c4b312a1b077b68243a7998d217e&oe=56BA5DE5&gda=1454718467_89331767e8555ed196c5559340774fbb"
the second returns the correct inner html as the users name diplays but its adding amp; after the & symbols in the url so the profile pic isn't displaying. No idea how to fix this. Any help would be great thanks.

You have incorrect <img/> tag syntax, you should be using src instead of href
Change:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img href="'+response.picture.data.url+'"/></figure>');
To:
$("#status").html('<p>'+response.name+'</p><figure id="profilePicture"><img src="'+response.picture.data.url+'"/></figure>');

Related

Django funcion views, creating a company with user associated

So, i have this problem when im trying to create my "company", when i didnt have user authentication the view worked just fine. Now i've added django allauth, and this screen appears to me:
enter image description here
So i will leave here my model and my view to create the company
Im just a begginner so sry for my bad explanation
enter image description here
enter image description here
The URLS : https://prnt.sc/K-lKvmfuQtvR
It looks like the problem is with the way your url is setup. Do you have a screenshot of the urls.py as well so we can see how you setup your url mapping. (OP added this screenshot: prnt.sc/K-lKvmfuQtvR)
Your companies/<pk>/ endpoint is catching your "create_company" value and storing it as a variable. Try moving your companies/create_company path above your companies/<pk>/ like so
path('companies/', listing_companies),
path('companies/create_company/', company_create),
path('companies/<pk>', retrieve_companies),
path('companies/<pk>/update/', company_update),
path('companies/<pk>/delete/', company_delete),
Alternatively rename companies/create_company/ to create_company/ like so
path('companies/', listing_companies),
path('companies/<pk>', retrieve_companies),
path('create_company/', company_create),
path('companies/<pk>/update/', company_update),
path('companies/<pk>/delete/', company_delete),
The end goal in either case is simply to make sure your paths are not capturing your "create_company" and storing it as that variable that it is passing along to your path's method.

How to add URL component to current URL via a HTML button? (Django 2.1)

I have a HTML button that is supposed to sort the search results by alphabetical order.
Button HTML code:
A-Z
views.py:
def query_search(request):
articles = cross_currents.objects.all()
search_term = ''
if 'keyword' in request.GET:
search_term = request.GET['keyword']
articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity')
if request.GET.get('a-z') == 'True':
articles = articles.order_by('Title')
Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen?
I think this is not specific to Django only, you can use javascript to do that:
Add a function that will get the current url and do the sorting function and call that function via onclick.
Then add the necessary param.
A-Z
Then in your js part, you can check the url contains a keyword param, if not, just add the sort param.
function sort(foo) {
let url = window.location.href;
// check if current url includes a "keyword" param else add the sort as param
if(url.includes("?") && url.includes("keyword")) window.location.href = url + "&" + foo;
else window.location.href = url + "?" + foo;
}
This is just an idea and might not work since I never tried to run this.

Handle a click event in django-tables2

I am starting to use django-tables2 and I have added a column which should allow user to delete a record when the user clicks on the button. The code looks as follows:
class ReviewTable(tables.Table):
delete = tables.LinkColumn('review_delete', args=[tables.A('pk')], orderable=False,
empty_values=(), verbose_name='')
def render_delete(self, record):
url = static('remove.png')
href = '#'
return mark_safe('')
This basically enders the image fine in a column but all I can do is set the link to it. How can I get it to call some method where I can then filter by the record ID and delete the relevant record? Is this the correct way to do this?
When you generate HTML from code, you still have access to onclick events.
return mark_safe(''.format(href, url)
Now your delete_action can be a javascript function that gives you more control. Generated HTML is basically just any old type of HTML, so you can still use jquery event handlers with it
BTW, please note how string formatting has been used in stead of concatenation. This is more pythonic

cloudinary direct upload form is not valid, need to re upload

i am using django and cloudinary direct upload to upload iamges
it is working if the form is valid.
but if my form is not valid, my page reloaded, and then the form will ask the user to upload the image again.
any way to solve this?
my code is attached below.
since i use direct upload, after an image is uploaded. it will be displayed immediately on the front end.
but when the form is invalid and the form is refreshed, the image is gone. ( after your latest update, it is true i do not need to re upload the photo again. but the photo is gone. how to display that again?)
thanks.
<script>
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
var imag_var = $.cloudinary.image(data.result.public_id, {
format : data.result.format,
version : data.result.version,
transformation : 'form_preview'
});
$('.preview').html(imag_var);
$('.status_value').text('Uploaded:' + data.result.public_id);
$('#id_cover_image').val(data.result.public_id);
return true;
});
$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
$('.progress').attr({
style : "visibility:show",
});
$('.status_value').text('Uploading...');
});
</script>
The Cloudinary javascript plugin puts the preloaded resource URI in a hidden field.
See here.
From the above one sees that if the field already exists the javascript plugin will populate it. Otherwise, it will create it.
In order to retain that URI across invalid form submissions you should create a hidden field named according to the field name you specified for cloudinary_direct_upload_field and which is populated with the value from the failed submission.
Another way to work around the issue would be to submit the form using an AJAX call. That way the data on page is retained even if validation failed and resubmission is possible. See here for an example of how that may be done.
EDIT:
Version 1.0.12 of the Cloudinary Python client library now adds the hidden field when needed out of the box so resubmissions should work. See the change log.
EDIT 2:
In order to regenerate a preview image in case of form validation error you can add something like this to the javascript code you run on page load (assuming the field name in the form is "image"):
//If form validation failed have the posted preloaded URI from the earlier
//submission so we can show preview
//pull the value from the hidden field
var imageUri = $('#direct_upload input[name="image"]').val();
//preloaded image URI structure
//{resource_type}/{type}/v{version}/{filename}#{signature}
var regex = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
//if there is value and it matches the pattern:
if (imageUri && regex.test(imageUri)) {
var uriParts = regex.exec(imageUri);
var version = uriParts[3];
var filename = uriParts[4];
//reconstruct a viable source
var src = "v" + version + "/" + filename;
//generate a cloudinary image tag and add it to the 'preview' div
$(".preview").append(
$.cloudinary.image(src, {
transformation: "form_preview" //your named transformation
})
);
}

Load dynamic HTML to display custom template

I own a small website that display to the users an html template (with css). Each user can change the template (customizable).
By default i have a template i copy everytime to a new user or if i get nice template (high rates) users can choose it.
instead of copying the template over and over, is there an easy way for me to create 1 template and then when the page load, it shows on the user page and then he can interact (ajax calls, href links etc...)
for example:
new user logged for the first time, the "user license agreement" shows then he click accept and his page shows up. this "home" page has forms, links, images etc... using a default template. that is the one i want to load dynamically instead of copying this template to each users.
why: i found HTML error in the page and now i need to copy this template to 127 users ... which is a pain.
i am using LAMP
thanks
yes using jQuery!
$('#divID').load('pathToHTMLTemplate') is your answer as long as you have the html file stored on same domain :)
This will fetch the html template using ajax and append its content to the div you want. It can also be 'body'.
Here is the documentation which should tell you everything you need to.
Once the template is loaded you can load the user specific data using ajax or any app server you are using. .load function provides a callback:
$('#divID').load('pathToHTMLTemplate', function(){
// now the template is loaded and you can maniupulate it further or load user specific data
});
It sounds to me (just going off of your post) that you have a directory somewhere with a bunch of files "user1.html", "user2.html" or something similar. All of these are either the same or similar, since they're basically the same template.
My recommendation:
Have a database table (or a flat file, but I recommend a database table) that maps a user ID (or name, however you have them arranged) to a template. For example, if user1 and user2 use template_default.html, but user3 uses template_popular.html, you would have the following in your database:
name|template
user1|template_default.html
user2|template_default.html
user3|template_popular.html
Then in whatever code is currently deciding which page to show the user, change it to pull the user's chosen template out of the database and display that instead. So then you only have 1 or 2 pages instead of 127.
If the user is allowed to make edits to their template, that could be stored as metadata in the table as well, then you could use substitution parameters to add it into the template.
Example:
MySQL table:
CREATE TABLE user_templates (
`user` varchar(100),
template varchar(100)
);
Upon receiving a new user:
INSERT INTO user_templates(`user`,template) VALUES("<username>","default_template.html");
Upon user choosing a new template:
UPDATE user_templates set template = "<new template>" WHERE `user` = "<username>";
Upon user loading the user's page (this done in php):
$template = "default_template.html";
$query = "SELECT template FROM user_templates WHERE `user` = \"" . mysql_real_escape_string($username) . "\"";
$result = mysql_query($query,$databaseHandle);
if ($result && mysql_num_rows($result) > 0) {
$template = mysql_result($result,0,"template");
}
// 1st way to do it
$pageToLoad = "http://www.someserver.com/templates/$template";
header("Location: $pageToLoad");
// 2nd way, if you want it embedded in a page somewhere
$directory = "/var/www/site/templates/$template";
$pageContents = file_get_contents($directory);
print "<div id=\"userPage\">$pageContents</div>";
I assume you mean that you have an HTML file that is customized for each user (look, feel, etc):
User1-theme.html
User2-theme.html
User3-theme.html
User4-theme.html
User4-theme.html
Then you would have a file that has all of your ajax calls, links, etc that you want for each user:
User-Controls.html
What you need to do is
Ensure jQuery is downloaded and included on each of your User Theme Pages.
Add this code snipplet to each of your User Theme Pages:
$("#myDiv").load("User-Controls.html")
(where #myDiv is the div ID on the template page that you want to load the controls into
and User-Controls.html is the path to the html file containing the controls you want to load