2

我在基于 django 的网站中有一个文本区域,显示数据库字段的内容。我希望能够编辑此字段并将其提交给更新数据库中字段的函数。

我知道如何调用 views.py 中的函数,然后使用 render_to_response 将查询结果发送回新网页。

总而言之,我如何使用 html 表单在 django/python 脚本中处理函数而不需要引用另一个 url?

4

3 回答 3

3

通常建议使用Post/Redirect/Get模式,例如:

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(...)      
于 2012-05-03T21:06:07.323 回答
3

使用 AJAX:

1)创建一个视图来处理表单提交:

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()

然后,将视图绑定到您的 urlpatterns

2) 通过 AJAX 提交表单(使用 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.

于 2012-05-03T21:12:51.783 回答
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)
于 2012-05-04T01:39:18.467 回答