Django:使用forms.py更新现有模型中的单个字段

时间:2018-02-28 12:54:40

标签: python jquery ajax django django-forms

我需要允许用户编辑字段以使用时尚的模态窗口自定义字段的名称。我一直在努力寻找AJAX的教程,但这有点过头了。

我的HTML:

<div id="editCustomParam" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form class="form-horizontal" id="chamber-form" action="" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="modal-content">
                <div class="modal-header">
                    <h3>Edit Parameter Name</h3>
                </div>
                <div class="modal-body">
                    {{ custom_param_form|crispy }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary submit_property" id="property_submit">Submit</button>
                </div>
            </div>
        </form>
    </div>
</div>

要编辑的按钮和元素:

<td><i id="edit_{{parameter.id}}" data-toggle="modal" data-target="#editCustomParam" class="far fa-edit" title="Edit Parameter Name"></i>&emsp;<span>{{parameter.parameter_name_userdef}}</span></td>

AJAX:

$(document).ready(function() {
    $('.submit_parameter').click(function(el) {
        var parameter_name = $("#id_parameter_name_userdef").val();
        var sensor_id = {{sensor.id}}
        $.post("{% url 'sensor' sensor.id %}", {
            csrfmiddlewaretoken: '{{csrf_token}}'
        }, function(data) {
            location.reload();
        }).done();
    });
});

表格:

class CustomParameterForm(ModelForm):
    parameter_name_userdef = forms.CharField(max_length=100)

    class Meta:
        model = SensorParameter
        fields = ['parameter_name_userdef']

观点:

class SensorInfoView(generic.DetailView):
    model = Sensor
    template_name = 'expert/sensor.html'

    def get(self, request, sensor_id):
        sensor = Sensor.objects.get(pk=sensor_id)
        chamber = Chamber.objects.get(sensor=sensor)
        sensor_parameters = SensorParameter.objects.filter(sensor=sensor)
        custom_param_form = CustomParameterForm()
        return render(request, self.template_name, {'sensor': sensor,
                                                    'chamber': chamber,
                                                    'custom_param_form': custom_param_form,
                                                    'sensor_parameters': sensor_parameters})

    def post(self, request, sensor_id):
        instance = get_object_or_404(Sensor, id=id)
        form = CustomParameterForm(request.POST or None, instance=instance)
        if form.is_valid():
            form.save()
            return redirect('next_view')
        return render(request, 'expert/sensor.html', {'custom_param_form': custom_param_form})

模特:

class SensorParameter(models.Model):
    sensor                  = models.ForeignKey(Sensor)
    parameter               = models.ForeignKey(Parameter)
    parameter_name_userdef  = models.CharField(max_length=100, blank=False, default=parameter)
    live_value              = models.FloatField()

现在,程序似乎很简单,这是我不太关注的执行。

  • 使用GET(完成)检索相关模型实例。
  • 制作一个编辑按钮,调出带有表格的模态(完成)。
  • 制作一个显示form.py(Done)形式的模态。
  • 写一些将相关数据发送到视图的AJAX(未完成!)
  • 在视图中处理POST请求(未完成!)

我一直在阅读一些教程,但我尝试按照这些步骤进行操作,现在我仍然确定如何处理AJAX位。我还是Django的新手,这也是我第一次使用AJAX,所以我不确定我是否犯了任何明显的新手错误。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您是否可以更好地检查它是否在模型中更新了?

class SensorParameter(models.Model):
    sensor = models.ForeignKey(Sensor)
    parameter = models.ForeignKey(Parameter)
    parameter_name_userdef = models.CharField(max_length=100, blank=False, default=parameter)
    live_value = models.FloatField()

    __sensor = None
    __parameter = None
    __parameter_name_userdef = None
    __live_value = None

    def __init__(self, *args, **kwargs):
        super(SensorParameter, self).__init__(*args, **kwargs)
        self.__sensor = self.parameter_name_userdef
        self.__parameter = self.parameter
        self.__parameter_name_userdef = self.parameter_name_userdef
        self.__live_value = self.live_value

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        if self.sensor == self.__sensor and (
                self.parameter_name_userdef != self.__parameter_name_userdef):
            super(SensorParameter, self).save(force_insert, force_update, *args, **kwargs)
            self.__parameter_name_userdef = self.parameter_name_userdef
        else:
            super(SensorParameter, self).save(force_insert, force_update, *args, **kwargs)
            self.__sensor = self.parameter_name_userdef
            self.__parameter = self.parameter
            self.__parameter_name_userdef = self.parameter_name_userdef
            self.__live_value = self.live_value

我在这里所做的基本上是当表单创建一个新的SensorParameter时,它会提交每个值,但是当那个SensorParameter已经ForeignKey时,然后它只会更新值parameter_name_userdef

虽然您还必须从ForeignKey发送sensor,因为您想检查哪些SensorParameter需要更新?我假设?但这就是你如何轻松更新模型中的单个值,如果你想要你也可以为多个值设置它。