Привет Djangonauts Я новичок в Django, пожалуйста, прости меня, если у меня есть глупые ошибки в моем коде, и в настоящее время я пытаюсь добавить комментарии к моей модели поста
ниже мои models.py
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
title = models.CharField(max_length=250, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
message = models.TextField()
def get_absolute_url(self):
return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug})
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
author = models.ForeignKey(User, related_name='comments')
text = models.TextField()
def get_absolute_url(self):
return reverse('posts:single', kwargs={'username': self.post.user.username,
'slug': self.post.slug})
views.py 1-я попытка
@login_required
def add_comment_to_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('posts:single', username=comment.author.username, slug=post.slug)
else:
form = CommentForm()
return render(request, 'posts/comment_form.html', {'form': form})
@login_required
def remove_comment(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.author = request.user
post_slug = comment.post.slug
comment.delete()
return redirect('posts:single', username=request.user.username, slug=post_slug)
urls.py
url(r'^(?P<slug>[-\w]+)/add_comment/$', views.CommentCreate.as_view(), name='add_comment'),
Также у меня есть URL для FBV ниже, они оба дают мне ту же ошибку
url(r'^(?P<slug>[-\w]+)/add_comment/$', views.add_comment_to_post, name='add_comment'),
url(r'^(?P<pk>\d+)/remove_comment/$', views.remove_comment, name='remove_comment'),
Views.py 2-я попытка
class CommentCreate(LoginRequiredMixin, CreateView):
model = Comment
fields = ('text',)
form_class = 'posts/comment_form.html'
def form_valid(self, form, *args, **kwargs):
self.object = form.save(commit=False)
self.object.user = self.request.user
slug = self.kwargs('slug')
print(slug)
self.object.post = get_object_or_404(Post, slug=slug)
self.object.save()
return super().form_valid(form)
views.py 3-я попытка
@login_required
def add_comment_to_post(request, slug):
print(slug)
post = get_object_or_404(Post, slug=slug)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('posts:single', username=comment.author.username, slug=post.slug)
else:
form = CommentForm()
return render(request, 'posts/comment_form.html', {'form': form})
также изменил URL-адреса на
url(r'^add_comment/(?P<slug>[\w-]+)/$', views.add_comment_to_post, name='add_comment'),
ниже - вид PostDetail и URL , они отлично работают
class PostDetail(SelectRelatedMixin, DetailView):
model = Post
select_related = ('user', 'group')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user__username__iexact=self.kwargs.get('username'))
#below is the url
url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/$', views.PostDetail.as_view(), name='single'),
Я получаю такое же сообщение об ошибке , как показано ниже, во всех 3 видах, а также с измененным URL
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/posts/...
Raised by: posts.views.PostDetail