2

I have a text area in a django based website that displays the content of a database field. I'd like to be able to edit this field and submit it to a function which updates the field in the database.

I know how I can call a function in a views.py which then send back the result of the query using render_to_response to a new webpage.

So in summary, how do I adress a function in a django/python script using a html form without the need to refer to another url?

3 Answers 3

4

It's usually recommended to use Post/Redirect/Get pattern, for example:

def myview(request, **kwargs):

    if request.POST:
        # validate the post data

        if valid:
            # save and redirect to another url
            return HttpResponseRedirect(...)
        else:
            # render the view with partial data/error message


    if request.GET:
        # render the view

        return render_to_response(...)      
Sign up to request clarification or add additional context in comments.

1 Comment

Right -- though if the POST is invalid, you want to make sure to re-render the view with the partial data.
3

Use AJAX:

1) Create a view to handle form submission:

def my_ajax_form_submission_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
           # save data or whatever other action you want to take
           resp = {'success': True}
        else:
           resp = {'success': False}

        return HttpResponse(simplejson.dumps(resp), mimetype='application/json')

    else:
        return HttpResponseBadRequest()

Then, tie the view into your urlpatterns

2) Submit form via AJAX (uses jQuery):

$('#my-form-id').submit(function(){
    var $form = $(this);
    $.post('/url/to/ajax/view/', $form.serialize(), function(data, jqXHR){
        if (data.success) {
            alert('Form submitted!');
        } else {
            alert('Form not valid');
        }
    });
    return false;
});

That's the basics. You can and should provide more detailed return responses, error handling, form validation/checking, etc.

Comments

1

This is the standard views code pattern that I've been using.

def payment_details(request, obj_id):
    yourobj = get_object_or_404(Obj, pk=obj_id)
    form = TheForm(instance=yourobj)

    if request.method == 'POST':
        form = TheForm(request.POST, instance=yourobj)
        if form.is_valid():
            yourobj = form.save()
            messages.success(request, 'Yourobj is saved!')
            url = reverse('SOMEURL')
            return redirect(url)

    template = 'SOMETEMPLATE'
    template_vars = {'TEMPLATEVARS': TEMPLATEVARS}
    return render(request, template, template_vars)

Having watched the Advanced Forms talk at DjangoCon, one could re-write the above view like this:

def payment_details(request, obj_id):
    yourobj = get_object_or_404(Obj, pk=obj_id)
    form = TheForm(request.POST or NONE, instance=yourobj)

    if request.method == 'POST' and form.is_valid():
        yourobj = form.save()
        messages.success(request, 'Yourobj is saved!')
        url = reverse('SOMEURL')
        return redirect(url)

    template = 'SOMETEMPLATE'
    template_vars = {'TEMPLATEVARS': TEMPLATEVARS}
    return render(request, template, template_vars)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.