Django is a high-level web framework for Python that provides a clean and pragmatic way to build web applications. It follows the Model-View-Controller (MVC) architecture and is designed to emphasize reusability and pluggability of components.
In this article, we will explore how to set up Django and create a basic web application.
Environment and Django Set up
Create a virtualenv
Virtualenv is a tool used to create isolated Python environments. It allows you to install packages locally without interfering with your system’s global installation.
To create a virtualenv, type the following command in your terminal:
python -m venv myenv
This command will create a folder called myenv in your current directory. You can activate the virtualenv by typing:
source myenv/bin/activate
Start a new Django project
Before we can start building our web application, we need to create a Django project. This can be done by typing the following command in your terminal:
django-admin startproject myproject
Here, myproject is the name of your project. This will create a new directory with the same name and some initial files.
You can navigate into this directory by typing:
cd myproject
Set up the initial tables
Django uses Object-Relational Mapping (ORM) to interact with databases. By default, Django comes with SQLite, a lightweight database engine.
To set up the initial tables, you need to create a database and apply the migrations. This can be done by typing the following commands in your terminal:
python manage.py migrate
python manage.py makemigrations
Add a superuser
To interact with our web application, we need a user account. A superuser has access to all parts of the application and can perform administrative tasks.
To create a superuser, type the following command in your terminal:
python manage.py createsuperuser
This will prompt you to enter a username, email, and password for the superuser.
Create a templates directory
Django uses a templating system to render HTML files with dynamic content. By default, Django looks for templates in a directory called templates in your project’s root directory.
To create this directory, navigate to your project’s root directory and type the following command in your terminal:
mkdir templates
Run a sanity check
Before we start building our web application, let’s run a sanity check to make sure everything is working as expected. Type the following command in your terminal:
python manage.py runserver
This will start a web server on your local machine.
You can access the server by opening a web browser and navigating to http://127.0.0.1:8000/. You should see a “Welcome to Django” page.
Conclusion
In this article, we have explored how to set up Django and create a basic web application. We have learned how to create a virtualenv, start a new Django project, set up the initial tables, add a superuser, create a templates directory, and run a sanity check.
With this knowledge, you should be able to start building your own web applications using Django.
Python Social Auth Set up
Python Social Auth is a Python library that provides support for social authentication in Django applications. Social authentication allows users to log in to your web application using their social media credentials, such as their Facebook or LinkedIn account.
In this section, we will explore how to set up Python Social Auth in your Django application.
Installation
The first step to using Python Social Auth is to install it in your Django application. This can be done using pip, Python’s package manager, by typing the following command in your terminal:
pip install python-social-auth
Configuration
Once Python Social Auth is installed, you need to configure it in your Django application. This involves adding some settings to your Django project’s settings.py file.
Here are the settings that you need to add:
# settings.py
INSTALLED_APPS = [
...,
'social_django',
... ]
MIDDLEWARE = [
...,
'social_django.middleware.SocialAuthExceptionMiddleware',
... ]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'social_core.backends.linkedin.LinkedinOAuth2',
]
SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'your-linkedin-app-id'
SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'your-linkedin-app-secret'
SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_emailaddress', 'r_liteprofile']
SOCIAL_AUTH_URL_NAMESPACE = 'social'
Here, we are adding ‘social_django’ to INSTALLED_APPS, ‘social_django.middleware.SocialAuthExceptionMiddleware’ to MIDDLEWARE, and ‘social_core.backends.linkedin.LinkedinOAuth2’ to AUTHENTICATION_BACKENDS.
We are also setting some LinkedIn-specific settings, such as your LinkedIn application’s ID and secret, and the desired scope of OAuth 2.0 access. Finally, we are setting SOCIAL_AUTH_URL_NAMESPACE to ‘social’ which is used by the application.
Run a migration
After you have added the settings to your Django application’s settings.py file, you need to run a migration to create the necessary database tables. This can be done by typing the following command in your terminal:
python manage.py migrate
Update the URLs
Next, you need to add the Python Social Auth URLs to your application’s URLs. This involves creating a new URL pattern in your application’s urls.py file. Add the following code to your app’s `urls.py` file:
# urls.py
from django.conf.urls import url, include
urlpatterns = [
...,
url(r'^oauth/', include('social_django.urls', namespace='social')),
... ]
This will map the URL pattern ‘/oauth/’ to the Python Social Auth URLs. The namespace ‘social’ is the same as the SOCIAL_AUTH_URL_NAMESPACE setting that we added to our settings.py file.
LinkedIn Authentication Keys
To obtain LinkedIn authentication keys, you will have to create a LinkedIn application. 1.
Navigate to LinkedIn’s developer portal — https://www.linkedin.com/developer/. 2.
Sign in using your LinkedIn account. 3.
Create a new application by clicking on the “Create app” button on the right-hand side of the page. 4.
Fill out the required information such as your app name and other important details. 5.
Once you have created the app, navigate to the “Auth” tab and note down your “Client ID” and “Client Secret” details as they will be required for your settings in the settings.py file.
Friendly Views
Once you have set up Python Social Auth in your Django application, you need to create some views to handle the authentication flow. One such view is a “friendly” view, which is a custom view that redirects the user to the appropriate social media login page based on the current URL.
Here’s some sample code for a “friendly” view:
# views.py
from django.shortcuts import redirect
from django.urls import reverse
from social_django.views import auth
def friendly_login(request):
if request.user.is_authenticated:
# Redirect to the user's dashboard if they are already authenticated
return redirect('dashboard')
else:
# Construct the URL to redirect to based on the current URL
next_url = reverse('social:begin', args=('linkedin-oauth2',))
redirect_url = request.build_absolute_uri(next_url)
# Redirect the user to the social media login page
return auth(request, backend='linkedin-oauth2', redirect_uri=redirect_url)
This view checks if the user is already authenticated and if not, constructs a redirect URL based on the current URL. It then uses the ‘auth’ view from Python Social Auth to handle the authentication flow and redirect the user to the appropriate social media login page.
Test!
With all these steps, you may test and see whether the authentication process is working by following these steps:
- Run the application by typing the following command in your terminal:
- Navigate to your Django application’s login page.
- Click on the LinkedIn login page to authenticate your account.
- You should now be redirected back to your Django application and logged in.
python manage.py runserver
Conclusion
In this article, we have explored how to set up Python Social Auth in your Django application. We have learned about installing Python Social Auth, configuring it in your Django application’s settings.py file, running a migration, updating your URLs, and creating a friendly view.
With this knowledge, you should be able to set up social authentication in your Django application using Python Social Auth.Django is a popular Python web framework that helps developers quickly build web applications. With its built-in templates and support for object-relational mapping, Django provides an easy and efficient way to develop web applications.
Python Social Auth is a library that can be integrated with Django applications to provide social authentication for users using their social media accounts. In this article, we have explored how to set up a Django environment, integrate Python Social Auth into our application, and create a friendly view to handle the authentication flow.
A Brief Overview of Django
Django is a complete framework for building web applications in Python. It follows the Model-View-Template (MVT) pattern.
Django takes care of most of the common tasks involved in web development, including database management, URL mapping, templating, and authentication. Django is designed to be flexible and scalable.
It is an open-source framework that has a large and active community of developers.
Django Environment Set up
The first step in creating a Django web application is to set up a development environment. This involves installing Python, creating a virtual environment, and installing Django.
Using virtual environments helps to keep Python packages organized and avoids conflicts between packages.
Python Social Auth Set up
Python Social Auth is a library that provides social authentication in Django applications. After installing Python Social Auth, it must be configured in the Django application’s settings.py file.
This involves specifying the authentication backends, setting up LinkedIn authentication keys, and setting the desired scope of access. Once Python Social Auth is configured in our Django application, we need to create a custom view to handle the authentication flow.
This view creates a unique redirect URL for each user that is based on the user’s current URL. It then redirects the user to the social media login page using the appropriate backend.
Friendly View
A “friendly” view is a custom Django view that is used to handle authentication in a more intuitive and user-friendly way. When logging in with social media credentials, the user must be redirected to the appropriate social media login page.
Once logged in, the user is returned to the Django application. The friendly view allows the user to be redirected back to the original page they were on once they have successfully authenticated.
Testing
Once everything has been set up, we can test our social authentication code. By following the steps to implement social authentication, users should be able to log in to your application using their social media credentials.
You can test this by logging into your Django application with your social media account credentials.
Conclusion
Django is a powerful Python web framework that allows developers to create web applications quickly and efficiently. Python Social Auth is a library that provides social authentication in Django applications.
By following the steps outlined in this article, you can set up social authentication in your Django application and create a “friendly” view to handle the authentication flow. Social authentication is a great way to make the registration and login process simpler for users.
With this knowledge, you can enhance the experience of users on your Django web applications. In this article, we have explored how to set up a development environment for Django web applications, and we learned how to use Python Social Auth to implement social authentication in Django.
We also discussed the creation of “friendly” views to make the authentication flow more user-friendly. By integrating social authentication in your Django application, you can provide users with a more convenient and secure way of logging in.
This approach can make the registration and login process simpler for users. By following the steps outlined in this article, you can enhance the user experience of your Django web applications.