Django

Blog App in Django Part IV
In this part of this series we will learn how to add few restrictions.
Table of Contents
- Remove “Create New Blog Post” option if user is not logged in
- Remove option of edit and delete if one’s not the author of the post.
- Only the Logged in user can see the post details
- The author of the post is logged in user.
- One Can only update and delete one’s own posts.
- Link for previous posts
Remove “Create New Blog Post” option if user is not logged in
Edit the base.html as follow.
<body>
<header>
<div class="nav-left">
<h1><a href="{% url 'home' %}">Django Blog</a></h1>
</div>
{% if user.is_authenticated %}
<div class="nav-right">
<a href="{% url "post_new" %}">+ Create New Blog Post</a>
</div>
{% endif %}
..........................................................................
Remove option of edit and delete if one’s not the author of the post.
Edit post_detail.html as follows.
{% extends "base.html" %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
<small>{{post.author}}</small>
</div>
{% if post.author == request.user %}
<a href="{% url 'post_edit' post.pk %}">+ Edit this post</a>
<br>
<a href="{% url "post_delete" post.pk %}">+ Delete Blog Post</a>
{% endif %}
{% endblock content %}
Only the Logged in user can see the post details
Add the following lines of codes to views.py of our application.
from django.contrib.auth.mixins import LoginRequiredMixin
.........................................................
class BlogDetailView(LoginRequiredMixin,DetailView):
model = Post
template_name = "post_detail.html"
........................................................
The author of the post is logged in user.
class BlogCreateView(LoginRequiredMixin,CreateView):
model = Post
template_name = "post_new.html"
fields = ["title","body"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
One Can only update and delete one’s own posts.
class BlogUpdateView(UpdateView):
model = Post
template_name = "post_edit.html"
fields = ["title","body"]
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(author=self.request.user)
class BlogDeleteView(DeleteView):
model = Post
template_name = "post_delete.html"
success_url = reverse_lazy("home")
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(author=self.request.user)
Link for previous post
pontu
0
Tags :