How to add a form in an html page in django

Viewed 158

I want to add comments form a specific html which has it's own views and models and I do not want to create a new html file like comment.html which will only display the form and its views. I want users to be able to comment right underneath a post, so that users don't have to click a button such as "add comment" which will take them to a new page with the "comment.form" and then they can comment. Basically want a page with all transfer news and their respective comments as well as a comment-form under the old comment. But I'm stuck. I can add comments manually from the admin page and it's working fine, but it seems that I have to create another url and html file to display the comment form and for users to be able to add comments(btw I'm trying to build a sports related website). Thanks in advance!

My models.py:

class Transfernews(models.Model):
    player_name = models.CharField(max_length=255)
    player_image = models.CharField(max_length=2083)
    player_description = models.CharField(max_length=3000)
    date_posted = models.DateTimeField(default=timezone.now)

class Comment(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    transfernews = models.ForeignKey(Transfernews, related_name="comments", on_delete=models.CASCADE)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.transfernews.player_name, self.user.username)

My forms.py :

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body', 'transfernews')

My views.py :

def addcomment(request):
    model = Comment
    form_class = CommentForm
    template_name = 'transfernews.html'



def transfer_targets(request):
    transfernews = Transfernews.objects.all()
    form = CommentForm(request.POST or None)
    if form.is_valid():
        new_comment = form.save(commit=False)
        new_comment.user = request.user
        new_comment.save()
        return redirect('transfernews/')
    return render(request, 'transfernews.html', {'transfernews': transfernews})

My urls.py:

path('transfernews/', views.transfer_targets, name='transfernews'),

My transfernews.html:

<h2>Comments...</h2>

{% if not transfernew.comments.all %}
No comments Yet...
{% else %}
{% for comment in transfernew.comments.all %}
  <strong>
    {{ comment.user.username }} - {{ comment.date_added }}
  </strong>
  <br/>
  {{ comment.body }}
  <br/><br/>
  {% endfor %}
  {% endif %}
  <hr>
  <div>Comment and let us know your thoughts</div>
  <form method="POST">
    {% csrf_token %}
    <input type="hidden" value="{{ transfernew.id}}">
    <div class="bg-alert p-2">
    <div class="d-flex flex-row align-items-start"><textarea class="form-control ml-1 shadow-none textarea"></textarea></div>
    <div class="mt-2 text-right"><button class="btn btn-primary btn-sm shadow-none" type="submit"> <a href="{% url 'comment' %}"></a>
    Post comment</button><button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button></div>
    </div>
  </div>
  </form>
1 Answers

Here's how you can do it :

First, add a field in your CommentForm :

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('body', 'transfernews')

Then in your template, you can set an hidden input in the form to link the comment to the transfernews :

{% if form.errors %}
    <p>There are errors in your form :</p>
    <ul>{{ form.errors }}</ul>
{% endif %}
<form method="POST">
  {% csrf_token %}
  {# Add this next line #}
  <input type="hidden" value="{{ transfernew.id}}">
  <div class="bg-alert p-2">
    <div class="d-flex flex-row align-items-start">
      <textarea class="form-control ml-1 shadow-none textarea" name="body"></textarea>
    </div>
    <div class="mt-2 text-right">
      <button class="btn btn-primary btn-sm shadow-none" type="submit">Post comment</button>
      <button class="btn btn-outline-primary btn-sm ml-1 shadow-none" type="button">Cancel</button>
    </div>
  </div>
</form>

Then in your view :

def transfer_targets(request):
    transfernews = Transfernews.objects.all()
    form = CommentForm(request.POST or None)
    if form.is_valid():
        new_comment = form.save(commit=False)
        new_comment.user = request.user
        new_comment.save()
        return redirect('transfernews')
    return render(request, 'transfernews.html', {
        'transfernews': transfernews,
        'form': form
    })
Related