user3684314 user3684314 - 1 year ago 85
Python Question

Update Database Using AJAX in Django

So I have an AJAX command, which passes information to a method (I have verified that the passing works from the HTML->>, so that's all good), but once I have it in "", I have no idea how to get it to update in the database itself.

I have tried to avoid using a file if possible, but if that is the only option I'll bend to it.

The AJAX function is as follows:

url : '/perform/acts/update/{{ }}/',
type : "POST",
data : {
'csrfmiddlewaretoken' : "{{ csrf_token }}",
furtherData : furtherData
success : function(result) {}

The function far, lacking, to say the least, but this is where I'm sort of lost:

def update_act(request, furtherData_id):
if request.method == 'POST':
return HttpResponse(?)

A big reason for doing this this way was performing updates without reloading and without having to add another module. I have been using Django for only a couple weeks, so it could be something easy that I'm missing...

Any help much appreciated!

Answer Source

Your view function:

def my_view_action(request, any_pk_id):
    from django.http import JsonResponse
    if request.method=='POST' and request.is_ajax():
            obj = MyModel.objects.get(pk=any_pk_id)
            obj.data_attr = request.POST['attr_name']
            return JsonResponse({'result': 'save successfully'})
         except MyModel.DoesNotExist:
            return JsonResponse({'error': 'Object does not exist'})
         return JsonResponse({'result':'Not a valid request'}

For more info

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download