[Answered ]-Adding a django model instance without a form -> button only

2๐Ÿ‘

Ok, all i needed was the following. It will send an empty POST request to the view, which then creates an instance with the currently logged in user. No Ajax required for my usecase, but i will look into it nonetheless.

Template:

<form method="post" action="">{% csrf_token %}
<button type="submit">Click Me!</button>

View:

@login_required
def stamper_login(request):

#form = ZeitForm(request.POST or None)
if request.method == 'POST':
    instance = Zeit(user=request.user)
    instance.save()
    print(instance)
    print(instance.user)
    print(request.POST)
context = {
}

return render(request, 'stamper_login.html', context)

0๐Ÿ‘

Barebones code:

Template. Iโ€™m not writing the HTML for this, but I have written the basic Jquery part of it

$(document).ready(function(){
    $('#button').on('click', function(){
        $.ajax({
            url: 'path/to/your/view',
            method: 'POST'
        }).done(function(){
            //Do something
        })
    })
})

Views.py

# Assuming the user is already logged in but you can write some code to handle anonymous users
def handle_ajax(request):
    # I've not written code to handle anonymous users
    user = User.objects.get(pk=request.user.id)
    zeit = Zeit(user=user) 
    zeit.save()

Leave a comment