Я пытаюсь добавить систему лайков к своим сообщениям в блоге в своем приложении блога. Я смотрел учебник о том, как добавить кнопку «Нравится», но он был частью курса, поэтому, например, в нем есть разные переменные и модели. Когда я пытаюсь загрузить URL-адрес «detail_post», я получаю следующую ошибку:
Вот мое сообщение об ошибке:
Internal Server Error: /blog/d-test-post/
Traceback (most recent call last):
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\dylan\myblogsite\blog\views.py", line 62, in detail_blog_view
return render(request, 'detail_blog.html', {'blog_post': blog_post,
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, in render
return self._render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 150, in render
return compiled_parent._render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render
return self.nodelist.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 62, in render
result = block.nodelist.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
bit = node.render_annotated(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
return self.render(context)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 443, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'like' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[^/]+)/like$']
Вот мой models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_delete, pre_save
from django.dispatch import receiver
from django.utils.text import slugify
from django.conf import settings
from account.models import Account
def upload_location(instance, filename):
file_path = 'blog/media/posts/{author_id}/{title}-{filename}'.format(
author_id=str(instance.author_id), title=str(instance.title), filename=filename
)
return file_path
class BlogPost(models.Model):
title = models.CharField(max_length=50, null=False, blank=False)
body = models.CharField(max_length=500, null=False, blank=False)
image = models.ImageField(upload_to=upload_location, null=False, blank=False)
date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published")
date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
likes = models.ManyToManyField(Account, related_name='likes')
def __str__(self):
return self.title
@receiver(post_delete, sender=BlogPost)
def submission_delete(sender, instance, **kwargs):
instance.image.delete(False)
def pre_save_blog_post_reciever(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = slugify(instance.author.username + "-" + instance.title)
pre_save.connect(pre_save_blog_post_reciever, sender=BlogPost)
class Comment(models.Model):
post = models.ForeignKey(BlogPost, on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
class Meta:
db_table = "myapp_comment"
Вот мой views.py, я включаю только свой пост-просмотр, потому что я считаю, что остальное неуважительно для моей проблемы:
from django.shortcuts import render, redirect, get_object_or_404
from blog.models import BlogPost
from blog.forms import CreateBlogPostForm, UpdateBlogPostForm, CommentForm
from account.models import Account
from operator import attrgetter
from django.http import HttpResponseRedirect
from django.urls import reverse, reverse_lazy
def like_view(request, slug):
blog_post = get_object_or_404(BlogPost, id=request.POST.get('post_id'))
blog_post.likes.add(request.Account.author)
return HttpResponseRedirect(reverse('detail', args=[str(slug)]))
Вот мои forms.py:
from django import forms
from blog.models import BlogPost, Comment
class CreateBlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = [
'title',
'body',
'image'
]
class UpdateBlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'body', 'image']
def save(self, commit=True):
blog_post = self.instance
blog_post.title = self.cleaned_data['title']
blog_post.body = self.cleaned_data['body']
if self.cleaned_data['image']:
blog_post.image = self.cleaned_data['image']
if commit:
blog_post.save()
return blog_post
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
Вот мой html шаблон:
{% extends 'base.html' %}
{% block content %}
<style type="text/css">
.card{
max-width: 700px;
}
.card-body{
padding: 20px;
}
</style>
<div class="container">
<div class="row">
<!-- Blog Post -->
<div class="card m-auto">
<img class="card-img-top" src="{{blog_post.image.url}}">
<div class="card-body mt-2 mb-2">
<h2 class="card-title">{{blog_post.title}}</h2>
<p class="card-text">{{blog_post.body|safe}}</p>
{% if blog_post.author == request.user %}
<a href="{% url 'blog:edit' slug=blog_post.slug %}" class="btn btn-primary">Update</a>
{% endif %}
</div>
<div class="card-footer text-muted">
Updated on {{blog_post.date_updated}} by {{blog_post.author}}
<br/><br/>
<hr>
<br/>
<form action="{% url 'blog:like' post.slug %}"
method="POST">
<button type="submit", name=post_id, value="{{ blog_post.slug }}", class="btn btn-primary btn-sm">Like</button>
</form>
</div>
<a class="card-text", href="{% url 'blog:comment' blog_post.slug %}">Comments</a>
</div>
</div>
</div>
{% endblock content %}
Наконец, вот мой urls.py:
from django.urls import path
from blog.views import (
create_blog_view,
detail_blog_view,
top_profiles_view,
edit_blog_view,
detail_comment_view,
like_view
)
app_name = 'blog'
urlpatterns = [
path('<slug>/like', like_view, name="like"),
path('<slug>/comments', detail_comment_view, name='comment' ),
path('create-post/', create_blog_view, name="create_post"),
path('top3/', top_profiles_view, name='top3'),
path('<slug>/', detail_blog_view, name="detail"),
path('<slug>/edit', edit_blog_view, name="edit")
]
Вот мой detail_blog_view:
def detail_blog_view(request, slug):
blog_post = get_object_or_404(BlogPost, slug=slug)
comments = blog_post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = blog_post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'detail_blog.html', {'blog_post': blog_post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
У меня довольно много ошибок.