Table of Contents
- Introduction
- Prerequisites
- Setting Up Django
- Creating a Django Project
- Defining Models
- Creating Views
- Adding Templates
- Handling User Authentication
- Building User Registration
- Creating User Profiles
Introduction
In this tutorial, we will build a social media site using Python and Django. By the end of this tutorial, you will have a basic understanding of how to create a web application using Django, manage user authentication, handle user registration, and create user profiles.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. You should also have Python and Django installed on your computer. If you haven’t installed Django, you can do so by running the following command:
python
pip install django
Setting Up Django
Once Django is installed, you can start by creating a new Django project. Open your terminal or command prompt and navigate to the directory where you want to create your project. Run the following command to create a new Django project:
python
django-admin startproject socialmedia
This will create a new directory named socialmedia
with the basic structure of a Django project.
Creating a Django Project
After setting up Django, navigate to the project directory:
python
cd socialmedia
Next, create a new Django app within the project:
python
python manage.py startapp socialapp
This will create a new directory named socialapp
inside the project directory. The app directory will contain the files and code for our social media application.
Defining Models
In Django, models represent the underlying data structure of our application. Open the models.py
file inside the socialapp
directory and define the necessary models for our social media site. For example, we can create a User
model to store information about each user:
```python
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(unique=True)
password = models.CharField(max_length=100)
def __str__(self):
return self.username
``` In this example, we define a `User` model with fields such as `name`, `username`, `email`, and `password`. We also define a `__str__` method to represent the user's `username` when displayed in the admin interface or other views.
Creating Views
Views in Django are responsible for handling HTTP requests and returning responses. Open the views.py
file inside the socialapp
directory and define the views for our social media site. For example, we can create a view to display the user profile page:
```python
from django.shortcuts import render
from .models import User
def profile(request, username):
user = User.objects.get(username=username)
return render(request, 'profile.html', {'user': user})
``` In this example, we define a `profile` view that takes a `username` parameter and retrieves the corresponding user from the database. We then render the `profile.html` template and pass the `user` object to the template for display.
Adding Templates
Templates in Django define the structure and presentation of our web pages. Create a new directory named templates
inside the socialapp
directory. Inside the templates
directory, create a new file named profile.html
and add the following code:
```html
<html>
<head>
<title>{{ user.name }}'s Profile</title>
</head>
<body>
<h1>{{ user.name }}'s Profile</h1>
<p>Username: {{ user.username }}</p>
<p>Email: {{ user.email }}</p>
</body>
</html>
``` This template defines the structure of the profile page for a specific user. It uses template variables such as ``, ``, and `` to display the user's information dynamically.
Handling User Authentication
User authentication is an essential part of any social media site. Django provides built-in support for user authentication. Open the settings.py
file inside the socialmedia
directory and add the following lines at the end of the file:
python
AUTH_USER_MODEL = 'socialapp.User'
LOGIN_URL = '/login/'
In this example, we set the AUTH_USER_MODEL
setting to point to our custom User
model. We also set the LOGIN_URL
setting to specify the URL where users should be redirected if they try to access a protected page without being logged in.
Building User Registration
To allow users to register on our social media site, we need to create a view and template for the registration page. Create a new view named register
in the views.py
file:
```python
from django.shortcuts import render
def register(request):
if request.method == 'POST':
# Process form data and create a new user
else:
return render(request, 'register.html')
``` In this example, we check if the request method is `POST`, which indicates that the user has submitted the registration form. We can then process the form data and create a new user. Otherwise, if the method is not `POST`, we render the `register.html` template, which will display the registration form.
Create a new file named register.html
inside the templates
directory and add the following code:
```html
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form method="post">
{% csrf_token %}
<label for="name">Name</label>
<input type="text" id="name" name="name" required><br>
<label for="username">Username</label>
<input type="text" id="username" name="username" required><br>
<label for="email">Email</label>
<input type="email" id="email" name="email" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
``` This template defines the structure of the registration page and includes a form for users to enter their details. It also includes a `csrf_token` input field, which is a security measure to protect against Cross-Site Request Forgery (CSRF) attacks.
Creating User Profiles
To allow users to create and update their profiles, we need to add additional views and templates. Create a new view named edit_profile
in the views.py
file:
```python
from django.shortcuts import render
def edit_profile(request):
user = request.user
if request.method == 'POST':
# Process form data and update the user's profile
else:
return render(request, 'edit_profile.html', {'user': user})
``` In this example, we retrieve the current user from the request object using `request.user`. If the request method is `POST`, we can process the form data and update the user's profile. Otherwise, we render the `edit_profile.html` template, passing the `user` object to pre-fill the form with the user's current details.
Create a new file named edit_profile.html
inside the templates
directory and add the following code:
```html
<html>
<head>
<title>Edit Profile</title>
</head>
<body>
<h1>Edit Profile</h1>
<form method="post">
{% csrf_token %}
<label for="name">Name</label>
<input type="text" id="name" name="name" value="{{ user.name }}" required><br>
<label for="username">Username</label>
<input type="text" id="username" name="username" value="{{ user.username }}" required><br>
<label for="email">Email</label>
<input type="email" id="email" name="email" value="{{ user.email }}" required><br>
<input type="submit" value="Save Changes">
</form>
</body>
</html>
``` This template defines the structure of the edit profile page and includes a form pre-filled with the user's current details. Users can update their information and save the changes.
Recap
In this tutorial, we have built a social media site using Python and Django. We covered the following topics:
- Setting up Django and creating a project
- Defining models to represent the underlying data structure
- Creating views to handle HTTP requests and return responses
- Adding templates to define the structure and presentation of web pages
- Handling user authentication for login and protected pages
- Building user registration and profile creation/update functionality
You can now continue to enhance the social media site by adding features such as user posts, comments, and likes. Django provides a powerful framework for web development, and with the knowledge gained from this tutorial, you can explore more advanced topics and build even more complex web applications.
Remember to regularly save your progress, test your code, and refer to the Django documentation for more information and resources. Happy coding!