Part 3: Creating Instagram Profile User and Post with Django and Python

Posted by

How to Create Instagram Profile User and Create Post Part 3

How to Create Instagram Profile User and Create Post Part 3

Welcome to part 3 of our tutorial on creating an Instagram profile user and creating a post using Django and Python. In this section, we will focus on creating a post for the user’s profile.

Create Post

Now that we have successfully created a user profile, we can move on to creating a post for that user. To do this, we need to create a new model for the post and set up a form for users to submit their posts.

Create Post Model

In your Django project, create a new model for the post. This model should include fields such as image, caption, and date posted. Here is an example of how you can define the post model:


from django.db import models

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='images/')
    caption = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)

Create Post Form

Next, create a form for users to submit their posts. You can use Django forms to easily create a form that allows users to upload an image and add a caption. Here is an example of how you can define the post form:


from django import forms

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['image', 'caption']

Display Post Form

In your Django project, create a view that displays the post form to users. You can use Django’s built-in views to render the form on a webpage. Here is an example of how you can create a view to display the post form:


from django.shortcuts import render
from .forms import PostForm

def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
    else:
        form = PostForm()
    
    return render(request, 'create_post.html', {'form': form})

And that’s it! Now users can create posts on their profiles. In the next part of this tutorial, we will focus on adding features such as liking and commenting on posts. Stay tuned for part 4!