Home > Back-end >  Django comment form
Django comment form

Time:01-02

I am following the guide to create comment given by Django central, https://djangocentral.com/creating-comments-system-with-django/ and it is working. However I am using the {{ form.as_p }} Which will give 3 fields, as the form say, with name, email and the body. But i wanted to have predefined name, which would be your username you are logged inn with and the email attached to that account. How would i go ahead to create that?

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'email', 'body']

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    email = models.EmailField()
    body = models.TextField()

    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-date_added']

    def __str__(self):
        return self.name
    

views.py

def post_detail(request, category_slug, slug, status=Post.ACTIVE):
    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.save()

           return redirect('post_detail',  category_slug=category_slug, slug=slug)
    else:
        form = CommentForm()

    return render(request, 'blog/post_detail.html', {'post': post, 'form': form})

in the html template

{% if user.is_authenticated %}
    <h2 >Comments</h2>
<form method="post" >
    {% csrf_token %}
    {{ form.as_p }}
    <div >
        <div >
            <button >Submit comment</button>
         </div>
    </div>
</form>
{% endif %}

CodePudding user response:

If you want to pre-set the username and email fields, you can use the initial form parameters like this:

views.py

def post_detail(request, category_slug, slug, status=Post.ACTIVE):
    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.save()

           return redirect('post_detail',  category_slug=category_slug, slug=slug)
    else:
        user = request.user
        form = CommentForm(initial={"name": user.username, "email": user.email})

        return render(request, 'blog/post_detail.html', {'post': post, 'form': form})

forms.py

class CommentForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].disabled = True
        self.fields['email'].disabled = True 
        
       # OR set readonly widget attribute.
       # self.fields['name'].widget.attrs['readonly'] = True
       # self.fields['email'].widget.attrs['readonly'] = True

    class Meta:
        model = Comment
        fields = ['name', 'email', 'body']

  • Related