Adding a Social Share button to your Django website. The statement is pretty straight forward isn’t it? In this tutorial we’ll learn about how to add a share button to our Django website. This is pretty short tutorial. But trust me, You’ll definitey learn from this. Let’s get started right away!
Project Setup
First things first! Install a package called django-social-share
:
pip install django-social-share
This package simplifies our work by providing custom inbuilt templatetags for sharing with various social sites.
Next few steps are self explanatory! Adding our app and our package to settings.py, configuring our root and app urls …
djang-admin startproject social_share cd social_share django-admin startapp app
Add the following line to settings.py file:
INSTALLED_APPS = [ .... 'app', 'django_social_share' ]
I’m not configuring the template lookup path. I’ll make a templates folder inside my app and I’ll add the templates inside.
Add the following lines to social_share/urls.py:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('app/', include('app.urls')), ]
Next, wee need to make a new urls.py file in our app/ directory to hold our app urls. Add the lines below to app/urls.py file:
from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name="home") ]
We now need to make a views function with name home
, and this will be pretty simple. Add the below lines to app/views.py file:
from django.shortcuts import render def home(request): return render(request, "home.html")
Make a folder called templates inside your app folder. Then make a template with name home.html inside that templates folder. Then add the below lines to it:
<!DOCTYPE html> <html lang="en"> {% load social_share %} <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Share Me!</title> </head> {% post_to_facebook object_or_url "Post to Facebook!" %} {% post_to_whatsapp object_or_url "Share To WA" %} {% post_to_reddit object_or_url "Share To Reddit" %} <body> </body> </html>
Basically what we’re doing is that we’re importing templatetag provided by django-social-share package with {% load social_share %}. Then we’re using that to make social sharing links.
Now run the server with the following command:
python manage.py runserver
Goto 127.0.0.1:800/app/home in your favourite browser. You should see three links. Clicking on one of that links will redirect you to respective social websites along with the url of our webpage (127.0.0.1:800/app/home).
So, that’s how we do it! Feel free to explore django-social-share here.
Check out the source code at : https://github.com/Chandu-4444/social_share