django-facebook like and share button for contents. template example - django

I am trying to get django-facebook work with my website .
I have this model
class Photo(models.Model):
name = models.CharField(max_length=100)
photo=models.ImageField(upload_to=/upload)
catagory= models.CharField(max_length=100,choices=Choice_c)
the template is
{% for p in photos %}
{% thumbnail p.photo as im %}
{% endthumbnail %}
{%endfor%}
the view for photos is
def home(request):
photos=Photo.objects.all()
return render_to_response(‘home.html’, {‘photos’:photos,},context_instance=RequestContext(request))
Now my question is how can I have facebook “like” and “share” button for contents i.e photo using django-facebook .
I have tried the facebook like code from facebook developers site but
it chooses all the photos if I iterate and all photos get liked which is
normal because I am iterating all of them.
Can you give a simple example how I can get individual likes for the photos by using django facebook.
Thanks in advance,

Related

Django & AJAX to show DB objects upon user's input submission

I'm pretty new in the Web development world, have been using Django so far.
I've been trying to figure out how to render data back to page after clicking on a submit button, so I see I'll need to use AJAX for that purpose.
I've created a very simple app just to understand the basics of AJAX.
However, googling, I couldn't really find a basic straight-forward implementation so I kinda got lost...
What I'm trying to achieve:
I have a model called Country:
class Country(models.Model):
name = models.CharField(primary_key=True, max_length=35)
continent = models.CharField(max_length=10)
capital = models.CharField(max_length=35)
currency = models.CharField(max_length=10)
And a super simple main page that asks the user to insert some country name.
The idea is to bring to the page all the info from the DB.
So it would look like this:
Main page HTML body:
<body>
<h2><em>Please type a country name:</em></h2><br><br>
<div class="container">
<form id="get_info" method="post">
{{ form }}
{% csrf_token %}
<input id="submit_button" type="submit" name="submit" value="Get info">
</form>
</div>
</body>
views.py:
from django.shortcuts import render
from country_trivia import forms
def main_page(request):
get_info_form = forms.GetInfo()
return render(request, 'country_trivia/index.html', {'form': get_info_form})
forms.py:
from django import forms
class GetInfo(forms.Form):
country_name = forms.CharField(label="")
I've seen some examples using forms, but I'm not even sure if it's needed, as I've seen some other examples that count on 'onclick' even listeners, then "grab" the text in the search field and pass it via AJAX...
How should I build my AJAX object for that simple purpose, and how should I integrate it?
Do I need to use forms at all?
I don't post anything to DB, just query it and print out data...
Thanks!!

How can i add a "like" button in a Django class ListView

I am pulling my hair out trying to add a "like" button in my site´s post app, but as i want to add it in a ListView that contains the rest of the posts entries and everyone has the option to be commented I have added a Formixin to do so, so, now i cannot add another form for the like button as it would mean two posts requests....so I am not finding a clear solution... I have read here and there about using AJAX or Json techs but as im new programing im kind of stuck in it... has anyone any tip to offer?
While using AJAX (javascript XHR requests) would be the proper way so the page doesn't need to be refreshed when just clicking a like button, you can do it without AJAX.
HTML
On the HTML side of things, you can have multiple forms (<form>), one for each post, which have a hidden input field that's the post's id. You have set that explicitly in the HTML template, e.g.
{% for post in post_list %}
<h3>{{ post.title }}</h3>
<p>{{ post.summary }}</p>
<form method="post">
{% csrf_token %}
<input type="hidden" value="{{ post.id }}" name="{{ form.id.html_name }}">
<input type="submit">Like</input>
</form>
{% endfor %}
So basically you're reusing the form multiple times, changing the "value" attribute to match the post.
Django Form
Adding the FormMixin to your view is the right step, just use the form_class to a custom LikeForm with just one field that's an IntegerField called id.
View
By adding the FormMixin you get the form_valid() method, which you'll want to override to save the like:
def form_valid(self, form):
id = form.cleaned_data['id']
try:
post = Post.objects.get(id=id)
except Post.DoesNotExist:
raise Http404
post.likes.add(self.request.user) # assuming likes is a m2m relation to user
return redirect('post_list') # this list view
Hopefully I am not so late, I had similar challenges trying to implement the same functionalities on my website.
I came to realize that each button id should be unique (Preferably the post id if blog), but the classes can be the same.
I was able to solve it. Here is an article I wrote on medium recently on the steps I followed to so get this working you can check it out here

How to create a clean url for user profile in django

I am building an application . One of the functionalities of this application is to display objects created by users to other users when they login .Lets call these objects created by users (x).
Each of these objects displays the name of the user who created it . Bellow is my code of my view to display all objects created by users.
def CreatedObjects(request):
objects=Model-Class-Name.objects.all()
# to display all users .
users=User.objects.all()
template_name="blabla.html"
context={"objects":objects,"users":users}
return render(request,template_name,context)
my html file
<div class="objects>
<!--Display all available objects created by users-->
{% for obj in objects %}
<!--Display the name of the user who created object, with a link that will take you to user profile of this user -->
<div class="user'>
{% for user in users %}
<a href="{% url 'app_namespace:url_name' user.pk %}">{{obj.user.username}}
</div>
{% endfor %}
{% endfor %}
<div>
The userprofile link works ,but since i am using a for loop to loop through available users in the database ,the user name is displayed repeatedly . So my problem is how to avoid this .How can i create a userprfile link without for looping or how can i avoid the user name not to be displayed continuously on a single object .

Multiple views for webpage depending on authentication status in Django

I am currently working on a developing a web application that people can use to browse through book reviews, but if they login they can post comments on the book reviews, or post their own reviews of books.
While I have implemented posting new reviews. I am do not understand how to modify the method in my views.py file that renders a book review such that if the user is logged in, in shows all previous comments, a form for the user to post a comment and a logout button, and if the user is not logged in it simply shows the book review and a log in button.
You can tell if your user is logged in or not in your views like this:
if request.user.is_authenticated():
# logged in logic
return render_to_response("loggedin_templates.html")
else:
# not logged in logic
return render_to_response("not_loggedin_templates.html")
Or you can tell them in the templates like this:
{% if user.is_authenticated %}
<span>{{ user.username }}</span>
{% else %}
<li>login
{% endif %}

Dynamically create and save image with Django and PIL/Django-Photologue

I want to generate a page of html with dynamic content and then save the result as an image as well as display the page to the user. So, user signs up to attend conference and gives their name and org. That data is combined with html/css elements to show what their id badge for the conference will look like (their name and org on top of our conference logo background) for preview. Upon approval, the page is saved on the server to an image format (PNG, PDF or JPG) to be printed onto a physical badge by an admin later. I am using Django and django-photologue powered by PIL.
The view might look like this
# app/views.py
def badgepreview(request, attendee_id):
u = User.objects.get(id=attendee_id)
name = u.name
org = u.org
return render_to_response('app/badgepreview.html',
{'name':name,'org':org,},
context_instance = RequestContext(request),
)
The template could look like this
{# templates/app/badgepreview.html #}
{% extends "base.html" %}
{% block page_body %}
<div style='background:url(/site_media/img/logo_bg.png) no-repeat;'>
<h4>{{ name }}</h4>
<h4>{{ org }}</h4>
</div>
{% endblock %}
simple, but how do I save the result? Or is there a better way to get this done?
The only thing I can think is to do it in two passes:
a) Use http://www.xhtml2pdf.com/ to convert the HTML into a PDF.
b) Use something like http://www.swftools.org/gfx_tutorial.html to convert the PDF into an image.
I can't imagine that doing this would be fast...
You might be better off just converting and allowing them to download a PDF (i.e. use just step a) above) or trying to generate the badge directly without the HTML intermediate step.