Get POST values in Django

14,195

Use an object for the data {add: {{ event.id }}} instead of encoding it as a string "add={{ event.id }}"

Then you should be able to fetch the value from request.POST with either of the following:

request.POST['add']
request.POST.get('add', 'default')  # use default if key doesn't exist

You already have event_id in the url, so you don't really need to set add={{event.id}}. It might be better to do something like"

{'action': 'add'}

Then in your view you can do something like:

if 'action' in request.POST:
    if request.POST['action'] == 'add':
        # do something
    elif request.POST['action'] == 'remove':
        # do something else
Share:
14,195
worm2d
Author by

worm2d

Updated on June 27, 2022

Comments

  • worm2d
    worm2d almost 2 years

    I had an ajax submit (GET query). But it makes change in my database, so smart people told me I should use POST instead with {% csfr_token %}.

    GET query:

    $(document).on('submit','#follow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            url:'/event/{{ event.id }}/',
            data: "add={{ event.id }}",
            success:function(){
                 $('#follow').hide();
                 $('#unfollow').show();
            }
        })
    });
    

    views.py

    ...
    event = get_object_or_404(Event, id=event_id)
    user = request.user
        if request.GET.get('add'):
            event.users.add(user)
            event.save()
        if request.GET.get('remove'):
            event.users.remove(user)
            event.save()
    ...
    

    So I added type:"post", and csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]) to data but I don't know what to use instead of if request.GET.get('add'): and if request.GET.get('add'):. I tried if request.POST.get('add'): but it doesn't work. So how to use that if with POST values?

    UPD.

    Ok, what i have now... template:

    <form id="unfollow" {% if user not in event.users.all %}style="display:none;"{% endif %}>
        <input type="hidden" value="{{ event.id }}" name="remove">
        <button type="submit" class="btn btn-warning btn-block">{% trans "Unfollow"%}</button>
    </form>
    

    ...

    $(document).on('submit','#unfollow', function(e){
        var $button = $(this).find('button');
        e.preventDefault();
        $.ajax({
            type:"post",
            url:'/event/{{ event.id }}/',
            data: {
                'action': 'remove'
            },
            success:function(){
                $('#unfollow').hide();
                $('#follow').show();
            }
        })
    });
    

    views.py:

    def show_event(request, event_id):
        event = get_object_or_404(Event, id=event_id)
        user = request.user
        if 'action' in request.POST:
            if 'action' == 'add':
                event.users.add(user)
                event.save()
            elif 'action' == 'remove':
                event.users.remove(user)
                event.save()
        return render(request, 'events/event.html', {'event':event, 'user':user}
    

    No errors, but it doesn't work. success:function() works fine but there are no changes in database. Any advice?

    I also tried if request.POST('action') == 'add': but it didn't help