Home > Mobile >  How to pass two PK through urls in Django?
How to pass two PK through urls in Django?

Time:03-01

I've created a function that adds the user to an event, that is working fine but, i'm having problems with the one that removes the users from the event, I didn`t figure out how to get the attendant so that the owner can remove it.

By now, I have this:

views.py (Function that adds the user to the event)

@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('/')

(Function that removes users from the event, handled by the event owner)

@login_required
def remove_attendant(request, pk, id):
    previous = request.META.get('HTTP_REFERER')
    try:
        post = Post.objects.get(pk=pk)
        attendant = Attending.objects.get(id=attendance_id)
        Attending.objects.filter(post=post, attendant=attendant).delete()
        messages.success(request, f'User removed!')
        return redirect(previous)
    except post.DoesNotExist:
        return redirect('/')

Urls.py

path('post/(?P<pk>[0-9] )/remove_attendant/(?P<attendance_id>[0-9] )$', views.remove_attendant, name='remove-attendant'),

Any help or comment will be very welcome! thank you!!!

CodePudding user response:

attendance_id seems to be undefined in your code.

def remove_attendant(request, pk, attendance_id): should be what you're calling.

Also in theory, you should be able to access both pk and attendance_id from request.resolver_match.kwargs anyways.

CodePudding user response:

You can simply use positional arguments in your url path, no need for regex. Your variable names can also be descriptive, if it helps (if often helps me).

path('remove-attendant-view/<post_id>/<attendance_id>/', views.remove_attendant, name='remove_attendant'),

And in views.py, something like:

def remove_attendant(request, post_id, attendance_id):

And whereever you call this view function, you must ensure your url has those ids and pks in context and in order, for example something like:

<a href="{% url 'remove_attendant' post_id=post_id, attendant_id=attendance_id %}">Remove Attendant</a>
  • Related