Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Associate user to its upload (post) in Django
Next article icon

Associate user to its upload (post) in Django

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Django provides built-in facilities of ForeignKey, and ManytoManyField for associating one model to another model. To associate a user model to a post model, one can use various options. This article revolves around how to associate a user to its post (post model). This tutorial uses the concept of foreign keys in Django and at the end, one will be able to create an application of post upload and also a profile app which contains all the past uploads of the user. 

Prerequisites -

  • Creation of Django project
  • Creation of application which can register login and logout the user
  • Make migrations in application and add database

We have already created a user application for registration and so we will create a new app that can be named a user blog (blog upload from the user) .To do this create an app in the main project file by writing this code in your PowerShell or terminal

django-admin startapp userblog

Now this application is available in your project file and you should first add this application to the settings.py file in the project and add this application to INSTALLED_APPS

Now make migrations in your project and add this application to your project

python manage.py makemigrations python manage.py migrate

Now we have to use models in this application so that Django can create a table for the information which we are going to store in our database and the user can input the information. We have to create a class in the models.py file of userblog application which is named Snippet. We will use a ForeignKey class which will hold the id value of the user and it holds too many relationships and so you can use this class to associate the user to any other activities where there is user involvement. 

Python3
from django.db import models from django.conf import settings  User = settings.AUTH_USER_MODEL  # Create your models here.   class Snippet(models.Model):     user = models.ForeignKey(User,                              default=1,                              null=True,                              on_delete=models.SET_NULL                              )     blogname = models.CharField(max_length=100)     blogauth = models.CharField(max_length=100)     blogdes = models.TextField(max_length=400)     img = models.ImageField(upload_to='pics')      def __str__(self):         return self.blogname 

Also, create a Python file named forms.py and create a ModelForm for the same to input data from the user.

Python3
from django import forms from .models import Snippet   class SnippetForm(forms.ModelForm):     class Meta:         model = Snippet         fields = ['blogname',                   'img',                   'blogauth',                   'blogdes'                   ] 

We need to migrate the class model of Snippet so that Django administration creates a database for the post upload and details so makemigrations of class Snippet and you will see this in django administration - 

cool

Here User is a foreign key that will show all the users and it will store the key number of the last instance of post upload by a user by default it is set to superuser Now we will go to the views.py file of the application and add the main code which will be storing the information in a database using model form object.

  • usblog - This will display all the posts in our homepage
  • snippet_detail - This will get the data from the user in the form and it will associate blog to user
Python3
from django.shortcuts import render from django.http import HttpResponse from .forms import SnippetForm from .models import Snippet from django.contrib import messages # Create your views here.   def usblog(request):     snipps = Snippet.objects.all()     return render(request, 'indexg.html', {'snipps': snipps})   def snippet_detail(request):     form = SnippetForm(request.POST or None, request.FILES or None)     if request.method == 'POST':          if form.is_valid():              obj = form.save(commit=False)             obj.user = request.user             obj.save()             form = SnippetForm()             messages.success(request, & quot                              Successfully created & quot                              )      return render(request, 'form.html', {'form': form}) 

So by now, the Django administration has created the database of the Snippet class and you can see it by visiting Django administration. Now we have to create a simple form.html file that will contain a form from where the user can enter the queries which we have stated in the class. Here comes the beauty of Django since we have used model forms for our application Django has created an HTML code of form that will have all those queries which we needed. So simply create an HTML file in your templates file(form.html). 

html
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <meta http-equiv="X-UA-Compatible" content="ie=edge">     <title>Your Blog</title> </head>  <body>     <form method="post" enctype="multipart/form-data">         {% csrf_token %}         {{form.as_p}}         <button type="submit">Submit</button>     </form> </body>  </html> 

Now we will need a homepage where we will see all the posts of the users so create another HTML file indexg.html and import the objects of function which we have created in views.py file. (Placed image of the only body part of HTML to show the python code you can make your own indexg with features ) 

html
<body>     <h1>Post play<h4>Only for geeks</h4>     </h1>      <div class="topnav">         {% if user.is_authenticated %}         <a href="#">Hi {{user.username}}</a>         <a href="accounts/logout">Logout</a>         <a href="snippet_detail">Write post</a>         {% else %}         <a href="accounts/register">Register</a>         <a href="accounts/login">Login</a>         {% endif %}     </div>     <p>         {% for snips in snipps %}          <img src="{{snips.img.url}}" alt="Image" class="img-fluid">         <h2 class="font-size-regular"><a href="#">{{snips.blogname}}</a></h2>         <h3>{{snips.user}}</h3>         {% if user.is_authenticated %}         <p>{{snips.blogdes}}</p>         {% else %}         <p>Register/Login to know more</p>         {% endif %}           {% endfor %}      </p>     </div> </body> 

Let us go to our main urls file where we will have an accounting app and now make the userblog application as default and add the URLs of your application. Also in your userblog application add urls.py and add the links of 2 functions which are form.html and homepage(indexg.html). 

Main Urls 

Python3
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [     path('', include('userblog.urls')),      path('admin/', admin.site.urls),     path('accounts/', include('accounts.urls'))  ] 

userblog urls - 

Python3
from django.urls import path  from . import views urlpatterns = [      path(& quot           snippet_detail&quot          , views.snippet_detail),     path('', views.usblog, name='usblog') ] 

Start the application and register the user to your application and make a post

python manage.py runserver

 Your browser does not support playing video  GITHUB LINK - Github Repo


Next Article
Associate user to its upload (post) in Django

D

DhruvikD
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Web Technologies
  • Technical Scripter 2019
Practice Tags :
  • python

Similar Reads

    How to Create and Use Signals in Django ?
    In this article, we'll dive into the powerful world of Django signals, exploring how to create and use them effectively to streamline communication and event handling in your web applications. Signals in DjangoSignals are used to perform any action on modification of a model instance. The signals ar
    5 min read
    How to Create a Basic Project using MVT in Django ?
    Prerequisite - Django Project MVT Structure  Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server.  Create a basic Project:  To in
    2 min read
    How to create a form using Django Forms ?
    This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
    2 min read
    Python | Uploading images in Django
    Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, we’ll walk through a
    3 min read
    How to Upload File in Python-Flask
    File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences