A
A
awd102017-03-01 20:43:59
Django
awd10, 2017-03-01 20:43:59

What is the best way to solve the problem with saving ajax form fields in django?

I want to save each form field individually. In the template, I catch the active input, set a timeout and pass the data to ajax, which accesses views.py.
The problem is that I don’t know how best to save the received values ​​​​from the request in the function (views.py), if you need to save the field separately, and not the entire form.
The most intrusive option is to write for each field:

user = request.POST["user"]
...итд

Is there a more general solution. There can be 20 or 30 fields in the form.
-------------------------------
settings.html
<script>
        $(':input').on('input', function () {
            $.ajax({
                url: '/settings/',
                type: 'get',
                data: $(this).serialize(),
                success: function (data) {
                    console.log('ssss')
                },
                error: function (data) {
                    console.log('eeee')
                }
            });
        })
    </script>

view.py
def settings(request):
    if request.method == 'GET' and request.is_ajax():
        profile_form = ProfileForm(request.GET, instance=request.user.profile)
        if profile_form.is_valid():
            profile_form.save()
            return ''
        else:
            return 'none'
    else:
        csrf_token = csrf.get_token(request)
        profile_form = ProfileForm(instance=request.user.profile)
        context = {
            'profile_form': profile_form,
            'csrf_token': csrf_token
        }
        return render(request, 'settings.html', context)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question