Writing Your First Blog App In Django-Part20

We will continue to build our blog app where we left in the post writing-your-first-blog-app-in-django-part-19.

In this post we will save that article which was created in the previous post with the help of article create form in the database,but we will have one problem till now,we are not storing which user has created the article.So we don’t know at every point who is the author,because in the Article model we have only five fields[title,body,slug,date,thumb],we are not storing the username.So we are going to look at that problem first of all.To associate user with an article we will use concept of django called foreign key.A foreign key is a way to associate a record from one model to another model.In our case the article model with the record from another model in our case the user model.

So first of all change the articles/models.py file as following to add one extra field called author.

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
# Model is always represented by class
class Article(models.Model):
    title = models.CharField(max_length=100)
    slug  = models.SlugField()
    body  = models.TextField()
    #auto_add_now field will automatically assign a current date to the post we create
    date  = models.DateTimeField(auto_now_add=True)
    #first parameter-default image
    #second parameter is saying that it is not necessary
    thumb = models.ImageField(default='default.png', blank=True)
    #add in author later
    #default=none specify that there is always one user associated with an article
    author = models.ForeignKey(User,on_delete=models.CASCADE,default=None)

    def __str__(self):
        return self.title

    #takes self as a input which is the instance of the article
    def snippet(self):
        #so we want to cut down the body.we want to make it 50 characters long.
        return self.body[:50]+'...'
    

After doing this change make a migration file by typing python manage.py makemigrations in cmd prompt,and after that apply this file to database by typing python manage.py migrate in command prompt.

Now we want to do thing like if user is logged in into the app and if he/she creates a new article then the system will be able to automatically associate that article with that user.

So to do that change the articles/views.py file as following:

from django.shortcuts import render,redirect
from .models import Article
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms

'''
Takes in the request object.
All we are going to do in this function is we will render a template
     to the user which is going to show a list of articles.
First parameter in render is always the request object and the second parameter is
     the template we want to render and third optional is the directory
'''
def articles_list(request):
    #Retrieve all articles from database and sort them according to date
    articles = Article.objects.all().order_by('date')
    return render(request, 'articles/articles_list.html',{'articles':articles})

def articles_details(request, slug):
    #return HttpResponse(slug)
    article = Article.objects.get(slug=slug)
    return render(request,'articles/article_detail.html',{'article':article})

#if the user is not already logged in than send the user to login page first
@login_required(login_url="/accounts/login/")
def article_create(request):
    #if the request is post then retrieve the data,which user has entered in the form 
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            # save article to db
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle()
    return render(request, 'articles/article_create.html', { 'form': form })

Now run the server and check,whenevar we create a new article,it will associate the user which is currently logged into the system with that article.You can check that by creating different articles with different users with cross-checking in admin section.


This is all about how to associate particular user with each article.

Leave a Comment

Your email address will not be published. Required fields are marked *