Issue
I am trying to submit comments on my blog posts but I get faced with this traceback every time. When it succeeds the comment will then be subjected to moderation before showing on the website. If I could get any help it would be greatly appriciated!
Here is the traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/blog/cubs/post/should-be-the-final-test-lmao/
Django Version: 4.1.2
Python Version: 3.10.6
Installed Applications:
['beavers.apps.BeaversConfig',
'cubs.apps.CubsConfig',
'scouts.apps.ScoutsConfig',
'accounts.apps.AccountsConfig',
'executive.apps.ExecutiveConfig',
'main_website.apps.MainWebsiteConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sitemaps',
'django.contrib.staticfiles',
'django_summernote',
'crispy_bootstrap5',
'taggit_helpers',
'taggit_labels',
'debug_toolbar',
'admin_reorder',
'crispy_forms',
'storages',
'taggit']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'admin_reorder.middleware.ModelAdminReorder')
Traceback (most recent call last):
File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/kiza054/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/home/kiza054/.local/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 73, in dispatch
return super().dispatch(request, *args, **kwargs)
File "/home/kiza054/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch
return handler(request, *args, **kwargs)
Exception Type: TypeError at /blog/cubs/post/should-be-the-final-test-lmao/
Exception Value: PostDetail.post() got multiple values for argument 'slug'
PostDetail (views.py)
class PostDetail(LoginRequiredMixin, DetailView):
model = Post
form_class = CommentForm
template_name = "cubs/post_detail.html"
def get_form(self):
form = self.form_class(instance=self.object)
return form
def post(self, slug, *args, **kwargs):
new_comment = None
pk = self.kwargs.get('pk')
post = get_object_or_404(Post, pk=pk)
form = CommentForm(request.POST)
if form.is_valid():
# Create new_comment object but don't save to the database yet
new_comment = form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
messages.warning(request, "Your comment is awaiting moderation, once moderated it will be published")
return redirect('cubs_blog_post_detail', slug=slug)
else:
return render(request, self.template_name, {'form': form})
def get_context_data(self, *args, **kwargs):
slug = self.kwargs.get('slug')
context = super().get_context_data(**kwargs)
post = get_object_or_404(Post, slug=slug)
comments = post.cubs_blog_comments.filter(active=True).order_by('-date_posted')
articles = Article.objects.filter(status=1).order_by('-date_posted')[:2]
post_likes = get_object_or_404(Post, slug=self.kwargs['slug'])
total_likes = post_likes.total_likes()
if post_likes.likes.filter(id=self.request.user.id).exists():
liked = True
else:
liked = False
context['liked'] = liked
context['articles'] = articles
context['comments'] = comments
context['total_likes'] = total_likes
context['title'] = 'Post Details'
context.update({
'comment_form': self.get_form(),
})
return context
Comment Model (models.py)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='cubs_blog_comments')
name = models.CharField(max_length=80)
email = models.EmailField()
comment = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['date_posted']
def __str__(self):
return 'Comment {} by {}'.format(self.comment, self.name)
Post Model (models.py)
class Post(models.Model):
class Status(models.IntegerChoices):
Draft = 0
Published = 1
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cubs_blog_posts')
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
date_posted = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=Status.choices, default=Status.Draft)
likes = models.ManyToManyField(User, related_name="cubs_blog_posts_likes")
class Meta:
ordering = ['-date_posted']
def __str__(self):
return self.title
def total_likes(self):
return self.likes.count()
def get_absolute_url(self):
return reverse("cubs_blog_post_detail", kwargs={"slug": str(self.slug)})
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
Solution
You are using slug
instead of request
in post method so:
def post(self, request, *args, **kwargs):
...
Also, you have to fix your redirect
kwargs:
return redirect('cubs_blog_post_detail', slug=post.slug)
Answered By - Mike Jones
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.