Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the Django Project
- Creating the Models
- Creating the Views
- Creating the Templates
- Finishing Touches
- Conclusion
Introduction
In this tutorial, we will build a social media app using Python and Django. By the end of this tutorial, you will have a basic understanding of how to create a web application with Django, including creating models, views, and templates.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming language and web development concepts. It is also recommended to have Django installed on your system. If you don’t have Django installed, you can easily install it using pip
:
pip install django
Setup
To start building our social media app, we need to create a new Django project. Open your command prompt or terminal and navigate to the directory where you want to create the project. Then, run the following command:
django-admin startproject social_media_app
This will create a new directory named “social_media_app” with the basic files and folders required for a Django project.
Creating the Django Project
Now that we have our Django project set up, we can start creating the app within the project. In Django, an app is a self-contained module that represents a specific functionality of the overall project. To create the app, run the following command in the terminal:
cd social_media_app
python manage.py startapp social
This will create a new directory named “social” within the project, which will contain all the files and components of our social media app.
Creating the Models
Models in Django represent the structure of our data. In our social media app, we will have two main models: User
and Post
.
Open the social/models.py
file and define the models as follows:
```python
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
password = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.text
``` In the above code, we define two classes: `User` and `Post`. Each class inherits from the `models.Model` class provided by Django. We define the fields for each model as class attributes, such as `name`, `email`, and `password` for the `User` model.
The __str__
method is used to represent the object as a string, which is helpful when displaying the objects in the Django admin interface.
Once you have defined the models, save the file.
Creating the Views
Views in Django handle the logic of our web application. They receive requests from the user’s browser, perform necessary actions, and return responses.
Create a new file named views.py
inside the social
app directory and define the views as follows:
```python
from django.shortcuts import render
from .models import User, Post
def home(request):
posts = Post.objects.all()
return render(request, 'social/home.html', {'posts': posts})
def create_post(request):
if request.method == 'POST':
user_id = request.POST.get('user_id')
text = request.POST.get('text')
user = User.objects.get(id=user_id)
Post.objects.create(user=user, text=text)
return redirect('home')
return render(request, 'social/create_post.html')
``` In the above code, we import the necessary modules and models. The `home` view retrieves all the posts from the database and passes them to the `home.html` template. The `create_post` view handles the creation of new posts. It expects a POST request with a `user_id` and `text` parameter, creates a new `Post` object, and saves it to the database.
Creating the Templates
Templates in Django define the structure and layout of the web pages. We will create two templates: home.html
and create_post.html
.
Create a new directory named templates
inside the social
app directory. Inside the templates
directory, create a new directory named social
and create the two template files inside it.
home.html
:
```html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Posts:</h1>
{% for post in posts %}
<h3>{{ post.user }}</h3>
<p>{{ post.text }}</p>
<small>{{ post.created_at }}</small>
{% endfor %}
<h2>Create a new post:</h2>
<form method="post" action="{% url 'create_post' %}">
{% csrf_token %}
<input type="hidden" name="user_id" value="1">
<textarea name="text" rows="4" cols="50" required></textarea>
<br>
<input type="submit" value="Post">
</form>
</body>
</html>
``` `create_post.html`:
```html
<!DOCTYPE html>
<html>
<head>
<title>Create Post</title>
</head>
<body>
<h1>Create a new post:</h1>
<form method="post" action="{% url 'create_post' %}">
{% csrf_token %}
<input type="hidden" name="user_id" value="1">
<textarea name="text" rows="4" cols="50" required></textarea>
<br>
<input type="submit" value="Post">
</form>
</body>
</html>
``` The `home.html` template displays all the posts retrieved from the database and allows the user to create a new post. The `create_post.html` template provides a form to create a new post.
Finishing Touches
To make our app accessible through the browser, we need to define the URLs. Open the social_media_app/urls.py
file and update it as follows:
```python
from django.urls import path
from social import views
urlpatterns = [
path('', views.home, name='home'),
path('create-post/', views.create_post, name='create_post'),
]
``` In the above code, we import the `views` module from the `social` app and define two paths: one for the home page and one for creating a new post.
Finally, we need to apply the database migrations. In your terminal, run the following command:
python manage.py migrate
This will create the necessary database tables for our models.
Now, you can start the development server by running the following command:
python manage.py runserver
Open your browser and go to http://localhost:8000
to see your social media app in action!
Conclusion
In this tutorial, we have built a social media app using Python and Django. We learned how to create models to represent our data, views to handle the logic, and templates to define the structure of our web pages. We also learned how to define URLs and apply migrations to the database. By following the steps in this tutorial, you should now have a basic understanding of how to create a web application with Django and Python.
Feel free to explore and expand on this project. You can add more functionality, such as user registration, user authentication, or commenting on posts. Django provides a wide range of tools and features to build robust web applications. Happy coding!
In this tutorial, you learned:
- How to create a Django project and app
- How to define models to represent your data
- How to create views to handle user requests
- How to create templates to define the structure of your web pages
- How to define URLs for your app
- How to apply migrations to the database
If you have any further questions, please refer to the official Django documentation or feel free to ask in the comments below.