Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
Django add comment section on posts feed

I want to share a project that currently can create user and each user can create N posts
The source is available on github

and I has two models users and post
enter image description here

and the template layers

enter image description here

Currently the feed for each post has a button that send an commenting the post I want to change that to put the comments of the post and not send and email each user should be able to comment a post and the comment should remain

{% block container %}
<body id="bg" img style="zoom: 85%; background-position: center center; background-attachment: fixed;background-repeat:no-repeat;padding:5px; background-image: url('{% static "/back.png"%}') ";>
<div style="background-image: url({% static 'static/img/back.png' %});">

    <div class="row" style="align:center">
        {% for post in posts %}
        <div class="col-sm-12 col-md-8 offset-md-4 mt-5 p-0 post-container,width:50%;">
            <div class="card" style="width: 32rem;width:50%;">
                <div class="card-body">
                    <div class="media pt-3 pl-3 pb-1">
                        <a href="{% url " users:detail" post.user.username%}">
                        <img alt="{{ post.user.username }}" class="mr-3 rounded-circle" height="35"
                             src="{{ post.profile.picture.url }}">
                        </a>
                        <h3 class="card-title">{{ post.title }}</h3>
                    </div>

                    <p class="card-text">{{ post.desc }}</p>

                </div>
            </div>
            <img alt="{{ post.title }}" src="{{ post.photo.url }}" style="width: 50%; heigth:60%">

            <div class="media-body">
                <b><p style="margin-top: 5px;">@{{ post.user.username }} - <small>{{ post.created }}</small>
                    &nbsp;&nbsp;
                    <a href="" style="color: #000; font-size: 20px;">
                        <i class="far fa-heart"></i>
                    </a>
                    <br>
                </p></b>


            </div>
            <!-- COMENT SECTION THAT I WANT TO IMPLEMENT MY FEATURE-->
            <form action="{% url 'posts:comment_new' %}" enctype="multipart/form-data" method="POST">
                {% csrf_token %}

                <input
                        class="form-control {% if form.title.errors %}is-invalid{% endif %}"
                        name="title"
                        size="16"
                        type="hidden"
                        value="{{post.title}}"
                >

                <input
                        class="form-control {% if form.title.errors %}is-invalid{% endif %}"
                        name="first_name "
                        size="16"
                        type="hidden"
                        value="{{user.first_name}}"
                >
                <input
                        class="form-control {% if form.title.errors %}is-invalid{% endif %}"
                        name="last_name "
                        size="16"
                        type="hidden"
                        value="{{user.last_name}}"
                >
                <textarea class="form-control" cols="50" name="comment" rows="5"
                          style="width:50%;" value="{{ comments.comment }}"></textarea>
                <button class="btn btn-outline-info btn-lg" style="width:35%; display:block;margin:auto;" type="submit">
                    Publish
                </button>

            </form>
        </div>
        <br>
        {% endfor %}
    </div>
</div>

{% endblock %}

As I said I want to replace this form function call to create a comment section instead sending a email with the comment

< form action = "{% url 'posts:comment_new' %}">


def comment_new(request):
    if request.method == 'POST':
        message = request.POST['comment']
        subject = request.POST['title']
        user = request.POST['first_name']
        last_name = request.POST['last_name']
        # lastname = request.POST['lastname']

        send_mail("[MAIL] " + subject, user + " " + last_name + " said  " + message + " on http://url.com:8000",
                  'guillermo.varelli@gmail.com',
                  ['guillermo.varelli@gmail.com'], fail_silently=False)
    posts = Post.objects.all().order_by('-created')
    return render(request, os.path.join(BASE_DIR, 'templates', 'posts', 'feed.html'), {'posts': posts})

I think this maybe create a comment with user and post id with the comment detail

def comment_new(request):
    if request.method == 'POST':   
        message = request.POST['comment']
        subject = request.POST['title']
        user = request.POST['first_name']
        last_name = request.POST['last_name']

        #lastname = request.POST['lastname']
        form = PostForm(request.POST, request.FILES)
        form.save()

One options its create a comment

class Comment(models.Model):
    """
    #id= models.AutoField(max_length=1000, blank=True)

    # post = models.ForeignKey(Post, related_name='',on_delete=models.CASCADE,default=0)
    """

    #comment = models.ForeignKey('posts.Post', related_name='posts_rel', to_field="comments", db_column="comments",
     #                           on_delete=models.CASCADE, null=True, default=1, blank=True)
    post = models.IntegerField(blank=True,null=True,unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)
    username = models.CharField(blank=True, null=True, unique=True ,max_length=200)
    comment = models.CharField(max_length=254, blank=True, null=True)

and then the form

class CommentForm(forms.ModelForm):

    class Meta:
        """form settings"""
        model = Comment
        fields = ('user','username','post','comment',)

finally with the function I'm able to persist but not able to render

form = CommentForm(request.POST, request.FILES)

# print formset.errors

if form.is_valid():
   form.save()

but I can't find the way to render the object on the html file

please feel free to suggest any solution or better create a pull request on the public git hub repo
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda