I am currently working on a Django application and I am currently have an issue. The issue is that when the user is not logged in, and on the blog post page(In this case "post_detail") and hit the like button, the user is directed to the login page. However, once the user is signed in, the user is redirected back to the home page(In this case "blog_home" which shows a list view of all the blog posts).
Now, that is not what I wanted. I wanted the user to go back to the blog post page("post_detail" page).
After researching the problem, I realized it had to do with the LOGIN_REDIRECT_URL. However, after trying to fix the issue, I am having a hard time to redirect the user to the specific page.
Is there any ideas on how I can make it work? Any input is truly appreciated.
Settings.py:
LOGIN_REDIRECT_URL = '/redirect'
views.py(blog):
def wherenext(request):
if request.user:
return HttpResponseRedirect(reverse('post_detail'))
else:
return HttpResponseRedirect(reverse('blog_home'))
...
@login_required(redirect_field_name="post")
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('post_detail', args=[str(pk)]))
...
class BlogDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
...
def get_context_data(self, *args, **kwargs):
context = super(BlogDetailView, self).get_context_data(*args, **kwargs)
stuff =get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
context["liked"] = liked
return context
urls.py:
urlpatterns = [
path('redirect/', wherenext, name='post_detail'),
path('post/<uuid:pk>/', BlogDetailView.as_view(), name='post_detail'),
path('',BlogListView.as_view(),name='blog_home'),
]
post_detail.html:
<form action="{% url 'like_post' post.pk %}"method="POST">
{% csrf_token %}
{% if user.is_authenticated %}
{% if liked %}
<button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-danger btn-sm">Unlike</button>
{% else %}
<button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-primary btn-sm">Like</button>
{% endif %}
{% else %}
{% if liked %}
<button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-danger btn-sm">Unlike</button>
{% else %}
<button type="submit", name="post_id", value="{{ post.id }}", class="btn btn-primary btn-sm">Like</button>
{% endif %}
{% endif %}
</form>