'how to delete an specific item from a foreign key within .views? Django
Im working on a Django app where you can join events only under the approval of the owner of the event.
By now, I have the function that adds the current user to the event for approval.
.views
@login_required
def request_event(request, pk):
previous = request.META.get('HTTP_REFERER')
try:
post = Post.objects.get(pk=pk)
Attending.objects.create(post=post, attendant=request.user)
messages.success(request, f'Request sent!')
return redirect(previous)
except post.DoesNotExist:
return redirect('/')
and here is the function that deletes de user request (By now is deleting the request of the current logged user)
@login_required
def remove_attendant(request, pk):
previous = request.META.get('HTTP_REFERER')
try:
post = Post.objects.get(pk=pk)
#attendant = #post.attending_set.all
Attending.objects.filter(post=post, attendant=request.user).delete()
messages.success(request, f'User removed!')
return redirect(previous)
except post.DoesNotExist:
return redirect('/')
My situation here is that I'm a having problem to get the attendants of the event (all the users who where added as atendant), so that the owner can reject which ever request he want.
How can I change this so that the function is going to delete a specific user of the event?
Thanks!!
Additional:
models.py
class Attending(models.Model):
is_approved = models.BooleanField(default=False)
attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE, null=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True)
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
urls.py
path('post/<int:pk>/remove_attendant/', views.remove_attendant, name='remove-attendant'),
.html
{% for user in object.attending_set.all %}
<div class="d-flex mb-3 border-top pt-3">
<div class="p-2 align-self-center">
<div class="mr-1 d-inline-block" style="height:40px; width:40px;">
<img class="rounded-circle img-st-user-pro" src="{{ user.attendant.profile.image.url }}">
</div>
</div>
<div class="p-2 align-self-center">
<h6 class="font-weight-bold mb-0">{{ user.attendant.first_name }}</h6>
<h6 class="mb-0 text-secondary">24 años</h6>
</div>
<div class="ml-auto p-2 align-self-center">
<a href="#" style="font-size: 14px !important;" class="btn-pre p-2 rounded text-decoration-none text-white pl-3 pr-3"><i class="pr-2 fa-solid fa-circle-check"></i>Approve</a>
<a href=" /post/{{ object.pk }}/attendants/{{ object.pk_attendant }}/remove-attendant/" style="font-size: 14px !important;" class="bg-white p-2 rounded text-decoration-none text-dark border pl-3 pr-3 ml-2">Reject</a>
</div>
</div>
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
