Add filter Comment in Django

I have a problem with adding comments only spaces or enters. I don't know how filter that. If the user sends a normal comment it is transferred to the current page but if send only spaces or enters it is transferred to the URL comment.

This my is code: models.py

class Post(models.Model):
    """Post Model"""
    hash = models.UUIDField(default=uuid.uuid4, editable=False)
    title = models.CharField("Title", max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    author  = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name="created_by",
        on_delete=models.CASCADE,
        default=current_user.CurrentUserMiddleware.get_current_user,
    )
    category = TreeForeignKey(Category, verbose_name="Category", related_name="items", on_delete=models.CASCADE)
    tags = TaggableManager()
    image = models.ImageField("Image", upload_to=get_timestamp_path)
    content = RichTextUploadingField()
    create_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.title}"

    def get_absolute_url(self):
        return reverse("main:post_detail", args=[self.slug])

    def save(self, *args, **kwargs):
        if str(self.hash) not in self.slug:
            self.slug = f"{self.slug}-{self.hash}" 
            super().save(*args, **kwargs)

    def get_comment(self):
        return self.comment_set.all()


class Comment(models.Model):
    user = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE)
    post = models.ForeignKey(Post, verbose_name="Post", on_delete=models.CASCADE)
    text = models.TextField(verbose_name="Comment")
    create_at = models.DateTimeField("Date of creating", auto_now=True)

    class Meta:
        verbose_name = "Comment"
        verbose_name_plural = "Comments"

    def __str__(self):
        return str(self.user)

views.py

class PostDetail(DetailView, MultipleObjectMixin):
    model = Post
    context_object_name = 'post'
    paginate_by = 10
    template_name = 'main/post_detail.html'

    def get_context_data(self, **kwargs):
        comments = Comment.objects.filter(post=self.get_object())
        context = super(PostDetail, self).get_context_data(object_list=comments, **kwargs)
        return context

class AddComment(LoginRequiredMixin, CreateView):
    """Add Comment"""
    model = Post
    form_class = CommentForm

    def form_valid(self, form):

        form.instance.user = self.request.user
        form.instance.post_id = self.kwargs.get('pk')
        self.success_url = form.instance.post.get_absolute_url()
        form.save()
        return super(AddComment, self).form_valid(form)

urls.py

path('comment/<int:pk>/', AddComment.as_view(), name="add_comment"),

forms.py

class CommentForm(forms.ModelForm):
    """Post Form"""
    class Meta:
        model = Comment
        fields = ["text"]

post_detail.html

<form id="formComment" method="post" action="{% url 'main:add_comment' post.id %}">
    {% csrf_token %}
    <div class="row">
    <div class="col form-group">
        <textarea name="text" class="form-control" placeholder="Your Comment*" required></textarea>
    </div>
    </div>
    <button type="submit" class="btn btn-primary">Post Comment</button>

</form>

If I send a comment with enters to spaces get this error

TemplateDoesNotExist at /comment/1/
main/post_form.html

You have not defined the template name in AddComment view.

Since you are using CreateView to add comments, you should use a separate page to render CommentForm. and create a separate url for post detail and to create comment.

moreover if you want to strip the whitespaces and tabs you can use isspace() string method https://www.geeksforgeeks.org/python-string-isspace-method/

Back to Top