I cannot get the correct item id as parameter

Asked

Viewed 78 times

0

I have an app django of posts (posts) and comments from posts.

In it I can also delete one post, however while deleting a post the application only deletes the post with higher id. The same occurs when commenting. The application only adds the comment to the post higher id.

Model

from django.db import models
from authentication.models import User

TYPE_POST = (
   ('0', 'Post'),
   ('1', 'Comment')
)

class Post(models.Model):
    content = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='imagens/', blank=True, null=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    reactions = models.IntegerField(default=0)
    type_post = models.CharField(max_length=1, choices=TYPE_POST, default='0')
    pub_date = models.DateTimeField(auto_now_add=True)
    commented_post = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)

    @property
    def get_comments(self):
        comments = Post.objects.filter(type_post='1', commented_post=self)

        return comments

    class Meta:
        ordering = ['-pub_date']

Forms

from django import forms
from .models import Post


class PostForm(forms.Form):
     image = forms.ImageField(required=False)
     content = forms.CharField(widget=forms.Textarea, required=False)

    def is_valid(self):
         valid = super(PostForm, self).is_valid()
         image = self.cleaned_data.get('image')
         content = self.cleaned_data.get('content')

        if image is None and content == '':
             self.add_error('Seu post precisa de um texto e/ou uma imagem')
             valid = False

    return valid

    def add_error(self, message):
         errors = self._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.utils.ErrorList())
         errors.append(message)

class CommentForm(forms.Form):
     content = forms.CharField(widget=forms.Textarea, required=False)

def is_valid(self):
    valid = super(CommentForm, self).is_valid()
    content = self.cleaned_data.get('content')

    if content == '':
        self.add_error('Seu comentário precisa de um conteúdo')

    return valid

    def add_error(self, message):
         errors = self._errors.setdefault(forms.forms.NON_FIELD_ERRORS, 
         forms.utils.ErrorList())
         errors.append(message)

Excerpt from the Template index.html

                                          {{ profile.full_name }}
                                </a>
                        </h4>
                    </div>
                </div>
        {% endfor %}

        {% include 'add_post.html' %}
        {% include 'post_list.html' with posts=posts %}
    </div>
    <div class="col col-sm-3">Lado</div>
</div>

View index

@login_required
def index(request):
profiles = User.objects.all()
posts = Post.objects.filter(user=current_user(request), type_post='0')
paginador = Paginator(posts, 10)
page = request.GET.get('page')
posts = paginador.get_page(page)

src = {'current_user': current_user(request), 'profiles': profiles, 'form': PostForm(),
       'comment_form': CommentForm(), 'posts': posts}

return render(request, 'index.html', src)

Template post_list.html

{% for post in posts %}
<p>Publicado em {{ post.pub_date }}</p>
<p>{{ post.content }}</p>

<p>
    {% if post.image %}
        <img src="{{ post.image.url }}" style="max-width: 100%">
    {% endif %}        
</p>

<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#modal-comment-post">Comentar</button>
<div class="modal" id="modal-comment-post" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Adicionar Comentário</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>{% include 'comment_form.html' with post=post %}</p>
      </div>
    </div>
  </div>
</div>

{% if current_user == post.user %}
    <button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#modal-delete-post">Delete</button>

    <div class="modal" id="modal-delete-post" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">Excluir Postagem</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <p>Deseja excluir a postagem?</p>
            </div>
            <div class="modal-footer">
              <a class="btn btn-secondary" data-dismiss="modal">Fechar</a>
              <a href="{% url 'delete_post' post.id %}" class="btn btn-primary">Excluir</a>
            </div>
          </div>
        </div>
      </div>
<a class="btn btn-primary btn-sm" href="{% url 'report_post' post.id %}">Denunciar</a>
{% endif %}

{% for comment in post.get_comments %}
  <p>{{ comment.content }}</p>
  <p>{{ comment.pub_date }}</p>
{% endfor %}

   {% endfor %}

Template comment_form.html

{% load widget_tweaks %}

<form action="{% url 'comment_post' post.id %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}

    {% for field in comment_form %}
        <div class="form-group">
            {{field.label_tag }}
            {% render_field field class+="form-control" %}
        </div>
     {% endfor%}
     <div class="modal-footer">
          <a class="btn btn-secondary" data-dismiss="modal">Fechar</a>
          <button class="btn btn-primary" type="submit">Comentar</button>
    </div>

    {% if form.errors %}
        <div class="alert alert-danger">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            {{ form.non_field_errors }}
        </div>
   {% endif %}
 </form>

Views Delete Post and Comment Post

@login_required
def delete_post(request, post_id):
post = Post.objects.get(id=post_id)
post.delete()

return redirect('index')

@login_required
def comment_post(request, post_id):
   if request.method == 'POST':
       form = CommentForm(request.POST)
       post = Post.objects.get(id=post_id)

       if form.is_valid():
           data_form = form.cleaned_data
           Post.objects.create(content=data_form['content'], user=request.user, type_post='1', commented_post=post)

           return redirect('index')
       else:
           return redirect('index')               

       else:
          return redirect('index')

1 answer

0


I was able to solve the problem, when I started using modal for the removal and comments, now I’m using a Javascript function to get the id and move to modal:

function setPostIdDelete(postid) {
    buttonDelete = document.getElementById('delete-post');
    buttonDelete.setAttribute('href', '/posts/' + postid + '/delete/');
}


<button onclick="setPostIdDelete({{ post.id }})" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#modal-delete-post">Delete</button>

    <div class="modal" id="modal-delete-post" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">{% trans "Excluir Postagem" %}</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <p>{% trans "Deseja excluir a postagem?" %}</p>
            </div>
            <div class="modal-footer">
              <a class="btn btn-secondary" data-dismiss="modal">{% trans "Fechar" %}</a>
              <a href="" id="delete-post" class="btn btn-primary">{% trans "Excluir" %}</a>
            </div>
          </div>
        </div>
      </div>

The same, I did for the comments, so I can pass the id correctly to the modal

Browser other questions tagged

You are not signed in. Login or sign up in order to post.