1

我试图弄清楚如何使用 django 表单和淘汰赛将编辑后的数据保存回数据库。edit.html 文件已更改为使用敲除在编辑页面上显示和编辑信息。我需要弄清楚如何更改 views.py 文件以保存信息。该页面似乎表现得像我想要的那样(我认为......),但我不知道如何在编辑发生后将信息更新回数据库,因为我没有使用 .html 文件中的 django 字段.

我已经阅读了这个帖子:using knockout.js with django forms? ,但这是使用 html 文件中的字段而不是淘汰代码。如果那是一种更好的方法,我不反对走那条路,但是当我尝试它时,我在实现这个想法时有点挣扎。

views.py 文件中的相关信息:

@render_to('phones/edit.html')
def EditPhone(request, number):
    p_number = PhoneTable.objects.get(number=number)
    customer_list = list(Customer.objects.values('customer_id'))
    JSON_customer_list = json.dumps(customer_list)

    if not request.POST:
        return dict(
            form=PhoneForm(instance=p_number),
            CallType=p_number.call_type,
            number=number,
            Customer=p_number.customer_id,
            extension=p_number.profile.extension,
            department=p_number.profile.department,
            JSON_customer_list=JSON_customer_list
        )

    form = PhoneForm(request.POST, instance=p_number)

    if not form.is_valid():
        return dict(form=form)

    form.save()

    messages.success(request, 'Phone Number updated')

    return redirect('phones:available_phones', number=p_number.number)

class PhoneForm(ModelForm):

    class Meta:
        model = PhoneTable

这是html文件:

{% block pagetitle %}Edit Phone Number: {{ number }}{% endblock %}
{% block content %}
        <div class="row">
            <div class="span2">
                <div class="pull-right">Call Type:</div>
            </div>
            <div class="span6">
                <select data-bind="options: callTypes, value: callType"></select>
            </div>
        </div>
        <div class="row">
            <!-- ko if: callType() === "Direct" -->
                <div class="span2">
                    <div class="pull-right">Extension:</div>
                </div>
                <div class="span6">
                    <input type="text" data-bind="value: editExtension" />
                </div>
            <!-- /ko -->
        </div>
        <div class="row">
            <!-- ko if: callType() === "Sales" -->
                <div class="span2">
                    <div class="pull-right">Customer:</div>
                </div>
                <div class="span6">
                    <select data-bind="options: customerDisplays, value: selectedCustomer"></select>
                </div>
            <!-- /ko -->
        </div>
        <div class="row">
            <!-- ko if: callType() === "Service" -->
                <div class="span2">
                    <div class="pull-right">Service Profile:</div>
                </div>
                <div class="span6">
                    <select data-bind="options: servProfiles, value: servProfile"></select>
                </div>
            <!-- /ko -->
        </div>

        <div class="form-actions">
            <input type="submit" class='btn btn-primary' value="Update" />
            <a class="btn" href="{% url phones:available_phones %}">Cancel</a>
        </div>
{% endblock %}

{% block javascript_compress %}
<script type='text/javascript' src="{% static 'js/knockout/knockout.js' %}"></script>
<script type="text/javascript">
    $(function(){
        customerListFromServer = {{ JSON_customer_list|safe }};

        var PhoneViewModel = function() {
            var self = this;

            customerList = [];
            for (var key in customerListFromServer) {
                customerList.push(customerListFromServer[key].customer_id);
            }

            self.callTypes = ko.observableArray(['Free', 'Direct', 'Sales', 'Service']);
            self.callType = ko.observable("{{ CallType }}");
            self.editExtension = ko.observable("");
            self.servProfiles = ko.observableArray(["{{ extension }}", "{{ department }}"]);
            self.servProfile = ko.observable();
            self.customerDisplays = ko.observableArray(customerList);
            self.selectedCustomer = ko.observable();

        }

        ko.applyBindings(new PhoneViewModel());

    });

</script>
{% endblock %}

有什么建议么?如果我遗漏了什么,请告诉我。谢谢你。

4

2 回答 2

1

我想通了,所以我会发布它是否可以帮助其他人。

我在 html 文件中添加了一个表单 ID 和发布方法以及一个隐藏字段。正如 Kevin 建议的那样,我在提交按钮上使用了数据绑定,并向 ko viewModel 添加了提交功能。然后我更改了 views.py 文件以获取 json 数据并保存编辑后的值。

@render_to('phones/edit.html')
def EditPhone(request, number):
    p_number = PhoneTable.objects.get(number=number)
    customer_list = list(Customer.objects.values('customer_id'))
    JSON_customer_list = json.dumps(customer_list)

    if not request.POST:
        return dict(
            form=PhoneForm(instance=p_number),
            CallType=p_number.call_type,
            number=number,
            Customer=p_number.customer_id,
            extension=p_number.profile.extension,
            department=p_number.profile.department,
            JSON_customer_list=JSON_customer_list
        )

    json_data = request.POST.get('json_blob')
    obj = loads(json_data)

    p_number.call_type = obj.get("callType")
    p_number.customer_id = obj.get("selectedCustomer")
    p_number.profile.extension = obj.get("editExtension")
    p_number.profile.department = obj.get("servProfile")

    p_number.save()

    messages.success(request, 'Phone Number updated')

    return redirect('phones:available_phones')

class PhoneForm(ModelForm):

    class Meta:
        model = PhoneTable

html文件:

{% block pagetitle %}Edit Phone Number: {{ number }}{% endblock %}
{% block content %}
    <form id="phone_form" method="post">
    {% csrf_token %}
    <input type="hidden" id="json_blob" value="" />
    <fieldset>
        <div class="row">
            <div class="span2">
                <div class="pull-right">Call Type:</div>
            </div>
            <div class="span6">
                <select data-bind="options: callTypes, value: callType"></select>
            </div>
        </div>
        <div class="row">
            <!-- ko if: callType() === "Direct" -->
                <div class="span2">
                    <div class="pull-right">Extension:</div>
                </div>
                <div class="span6">
                    <input type="text" data-bind="value: editExtension" />
                </div>
            <!-- /ko -->
        </div>
        <div class="row">
            <!-- ko if: callType() === "Sales" -->
                <div class="span2">
                    <div class="pull-right">Customer:</div>
                </div>
                <div class="span6">
                    <select data-bind="options: customerDisplays, value: selectedCustomer"></select>
                </div>
            <!-- /ko -->
        </div>
        <div class="row">
            <!-- ko if: callType() === "Service" -->
                <div class="span2">
                    <div class="pull-right">Service Profile:</div>
                </div>
                <div class="span6">
                    <select data-bind="options: servProfiles, value: servProfile"></select>
                </div>
            <!-- /ko -->
        </div>

        <div class="form-actions">
            <input type="submit" class='btn btn-primary' value="Update" data-bind="click: submitForm" />
            <a class="btn" href="{% url phones:available_phones %}">Cancel</a>
        </div>
{% endblock %}

{% block javascript_compress %}
<script type='text/javascript' src="{% static 'js/knockout/knockout.js' %}"></script>
<script type="text/javascript">
    $(function(){
        customerListFromServer = {{ JSON_customer_list|safe }};

        var PhoneViewModel = function() {
            var self = this;

            customerList = [];
            for (var key in customerListFromServer) {
                customerList.push(customerListFromServer[key].customer_id);
            }

            self.callTypes = ko.observableArray(['Free', 'Direct', 'Sales', 'Service']);
            self.callType = ko.observable("{{ CallType }}");
            self.editExtension = ko.observable("");
            self.servProfiles = ko.observableArray(["{{ extension }}", "{{ department }}"]);
            self.servProfile = ko.observable();
            self.customerDisplays = ko.observableArray(customerList);
            self.selectedCustomer = ko.observable();

            self.submitForm = function() {
                $("#json_blob").val(ko.toJSON(self));
                $("#phone_form").submit();
            }
        }

        ko.applyBindings(new PhoneViewModel());
    });

</script>
{% endblock %}
于 2013-07-09T15:28:18.143 回答
0

对于淘汰赛,我通常喜欢通过视图模型进行尽可能多的控制,包括将信息保存回服务器。在您的情况下,我会让提交按钮在视图模型中执行保存功能,如下所示:

html:

<input type="submit" class='btn btn-primary' value="Update" data-bind="click: submitForm" />

在您的淘汰视图模型中,有几种方法可以保存数据:

self.submitForm = function () {
    // save via postback
    ko.utils.postJson('/EditPhone', ko.toJSON(self));


    // save via ajax
    $.ajax({
        type: 'POST',
        data: ko.toJSON(self),
        url: '/EditPhone',
        success: function () {
            alert("saved");
        },
        error: function () {
            alert("no worky");
        }
    })
}

不幸的是,我没有使用 django 的经验,所以我不确定你需要如何设置它才能接受返回服务器的 json 数据

于 2013-07-05T18:17:29.657 回答