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

问题描述 投票:0回答:1

我需要允许用户编辑字段以使用时尚的模态窗口自定义字段的名称。我一直在努力寻找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(完成)检索相关模型实例。
  • 制作一个编辑按钮,调出带有表格的模态(完成)。
  • 创建一个模式,显示forms.py(Done)中的表单。
  • 写一些将相关数据发送到视图的AJAX(未完成!)
  • 在视图中处理POST请求(未完成!)

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

谢谢你的帮助!

python jquery ajax django django-forms
1个回答
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,然后它将提交每个值,但是当已经有SensorParameterForeignKey,那么它将只更新值parameter_name_userdef

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

© www.soinside.com 2019 - 2024. All rights reserved.