django ajax doesn't save form to database

Viewed 905

I have a problem when i try to save data to database using ajax.

It always gives me success .. and that means it works fine .. But it didn't save data to database.

and also i tried to print 'message': 'form is saved' in console.log(data.message) but it always gives me undefined

Views

@login_required(login_url='login')
def PostCreateView (request):
    form = PostCreateForm()
    if request.is_ajax():
        form = PostCreateForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            data = {
                'message': 'form is saved'
            }
            return JsonResponse(data)
    context = {
        "form": form,
    }
    return render(request, "blog/new_post.html", context)

urls.py

path('new_post/', PostCreateView, name='new_post'),

new_post.html

<form method="POST" enctype="multipart/form-data" class="my-ajax-form" data-url="{% url 'new_post' %}">
    {% csrf_token %}
    {{form|crispy}}
    <input class="btn btn-secondary mt-4" type="submit" value="Add New Post">
</form>

plugins.js

$(document).ready(function () {
    var $myForm = $('.my-ajax-form'); // select form class
    $myForm.submit(function (event) {
        event.preventDefault();
        var $formData = $myForm.serialize(); // get all data from form which will be submitted to database
        var $thisURL = $myForm.attr('data-url') || window.location.href; // data-url is attribute in form
        $.ajax({
            method:'POST',
            url: $thisURL,
            data: $formData,
            success: handleSuccess,
            error: handleError,
        });
        function handleSuccess(data) {
            console.log('success');
            console.log(data.message);
            $myForm[0].reset();
        }
        function handleError(ThrowError) {
            console.log('error');
            console.log(ThrowError);
        }
    });
});

I tried tonnage of questions and answers here .. without a result for two days.

any body can help please ?

Thanks in-advance

3 Answers

Here's my take on this, PostCreateForm() is an object you're instantiating. But you're passing a comparison of variables.

In the end you only get True, False or None as the argument being passed to PostCreateForm() The python interpreter might be evaluating them as comparisons. Which means You might possibly end up with a function call like this PostCreateForm(True,None).

form = PostCreateForm(request.POST, request.FILES)

Related