可能的话,用Jquery更新Django对象

Update Django Object with Jquery, possible?

本文关键字:Jquery 更新 Django 对象      更新时间:2023-09-26

我正在尝试使用jQuery更新表中已经存在的Django对象(Company(。

我的代码执行得很好,公司对象没有更新。

以下是我的模板摘录:

{% if companies %}
        <tr class="gradeX">
            {% for company in companies %}
                <td>{{ company.name }}</td>
                <td>{{ company.user.first_name }}</td>
                <td>{{ company.created_on }}</td>
                <td>Edit | Delete</td>
                </tr>
            {% endfor %}
    {% else %}
        <strong>There are no companies yet.  <a data-toggle="modal" href="#addCompanyModal"> Do you want to create one?</a></strong>
    {% endif %}

我尝试过的JavaScript是:

 <script type="text/javascript">
    function save_company()
    {
        $form=$('#addCompanyForm');
        var datastring = $form.serialize();
        $.ajax({
            type: "POST",
            url: $form.attr('action'),
            dataType: 'json',
            data: datastring,
            success: function(result)
            {
                $('#result').html('<div class="alert alert-success"> <strong>Well done!</strong> New company added.</div>');
                $('#addCompanyModal').modal('hide');
                list_companies();
            },
            error: function(result){
                alert("failure:"+result.error);
                }
        });
        //don't submit the form
        return false;
    }
function list_companies()
    {
        $.get('/panel/company/list/json/', function(data) {
                $('#dynamic-table').html(data);
            }
        );
    }
</script>

最后,这是我尝试过的观点:

def list_companies_json(request):
    if request.is_ajax():
        companies_list = Company.objects.filter(user=request.user).order_by('-name')
        context_dict = {'companies': companies_list, 'form': form, 'errors': errors, 'success': success}
    #context_dict = serializers.serialize('json', list(companies_list))
    return render(request, 'panel/company/list_companies.html', context_dict)

这当然是可能的,而且有很多方法可以做到这一点。抽象地说,您所需要做的就是通过某种方式将前端传递给您的对象,以便jQuery(或您想要使用的任何库/框架(可以告诉Django哪些对象需要更新。为了清楚起见,我假设您想要更新单个对象,但请注意,只需使用标识符/引用的array,而不是我们将要使用的一个,同一管道就可以扩展到多个对象。

一种方法是将Django对象的id传递到HTML中(免责声明:有更安全的方法可以做到这一点,但为了清晰的概念化,这就足够了(。例如,要传递每个company对象的id,可以使用:

{% for company in companies %}
  ...
<td class="companyID">{{ company.id }}</td>
  ...
{% endfor %}

假设您将每个company封装在某个包装器中,那么您只需使用一个jQuery:就可以获取您想要的id

var theCompany = ... // Maybe grabbed from a click? Really, it's up to you.
var theCompanyID = $(theCompany).find(".companyID").html();

然后,当您想对该对象执行一些"更新"时,只需将其包含在发送回视图的data中即可。

var data = {"theCompanyID":theCompanyID, ... }
$.post("/myURL/", data, someCallback);

之后,您可以使用MyObject.get(id=theObjectID)获取相应的Django对象,并根据需要进行更新。

def myUpdateView(request):
  # We'll wrap the "update" portion in a Try-Except in case the user passes us
  # data that will break our update function. We should obviously check for
  # this BEFORE we attempt to perform the update -- but always best to be safe.
  try:
    theCompanyID = request.POST["theCompanyID"]
    theCompany = Company.objects.get(id=theCompanyID)
    # ... Now do the updates you want.
    theCompany.save()
    return HttpResponse("Update successful!")
  except:
    return HttpResponse("Oh... Update failed...")

如果你想更多地探索这一点,这里有一个更深入的教程。