Answer the question
In order to leave comments, you need to log in
How to override the result of a POST request in Django CBV?
I'm trying to add a like system to blog posts using this form:
<form action="/article/like/{{ article.id }}/" method="post">
{% csrf_token %}
<input hidden name="like" value="+">
<input type="submit" value="-">
</form>
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect(self.get_success_url())
Answer the question
In order to leave comments, you need to log in
The answer to your question looks like this:
def post(self, request, *args, **kwargs):
...
def form_valid(self, form):
instance = form.save(commit=False)
if instance.like == '+':
instance.user = request.user
instance.save()
else:
bad_mojo()
return redirect(self.get_success_url())
class Like(Model): # Модель лайков
user = ForeignKey(User)
class Article(Model): # Твоя модель статьи
# Чтобы уменьшить количество записей в таблице Like, просто будем присваивать статьям
# один и тот же лайк через М2М связь.
likes = ManyToManyField(Like)
def like(self, user):
try:
like = Like.objects.get(user=user)
self.likes.add(like)
except Like.DoesNotExist:
self.likes.create(user=user)
class LikeArticle(SingleObjectMixin, View):
model = Article
def post(self, request, *args, **kwargs):
obj = self.get_object()
obj.like(request.user)
return redirect(obj) # Чтобы использовать такую форму, нужно определить метод get_absolute_url для Article
...
url(r'article/(?P<pk>\d+)/like$', LikeArticle.as_view(), name='like-article'),
# Заметь, article/<id>/like, а не article/like/<id>. Архитектурно так более верно.
...
<form action="{% url 'like-article' object.pk %}" method="POST">{% csrf_token %}
{# Где object - экземпляр статьи #}
<input type="submit"/>
</form>
in the view, the like value can be obtained through instance.cleaned_data.get('like')
And when you begin to understand what is happening, then the raw value can be taken fromself.request.POST.get('like')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question