0

我在我的 Django 应用程序中创建了多个更新表单。

我的问题是:Django 是否需要更新对象的每个字段,或者有没有办法只更新实际更改的字段?

因此,例如,我可能有一个带有Airport Name, Airport City,的表单Airport Country。我可能会使用更新表单来更新Country. Django 是否还需要填写NameCity表单字段然后更新,或者有没有办法将它们留空而不更新数据库?

编辑

这是模型:

class Airport(models.Model):
    airport_name = models.CharField(max_length=200, verbose_name="Aeroporto")
    airport_city = models.CharField(max_length=200, verbose_name="Cidade")
    airport_country = models.CharField(max_length=200, verbose_name="País")

和形式:

class UpdateAirport(ModelForm):

    def __init__(self, *args, **kwargs):
        super(UpdateAirport, self).__init__(*args, **kwargs)
        self.fields['airport_name'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['airport_city'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['airport_country'].widget = TextInput(attrs={'class': 'form-control'})


    class Meta:
        model = Airport
        fields = ('airport_name', 'airport_city', 'airport_country' )

而我的观点:

@login_required(login_url='../accounts/login/')
def airport_upd(request, id):
    ts = Airport.objects.get(id=id)
    if request.method == 'POST':
        form = UpdateAirport(request.POST, instance=ts)
        if form.is_valid():
            form.save()
            return redirect('flights')
    else:
        form = UpdateAirport(initial={'airport_name': ts.airport_name, 'airport_city': ts.airport_city, 'airport_country': ts.airport_country})
    return render(request, 'backend/aiport_update.html', {'form': form, 'ts': ts})

我正在使用 Postgresql。

4

3 回答 3

0

When you create a new row in Airport table, fields cannot be null or blank because are required, but when you update that row you don`t need to fill all fields if they already have a value

于 2020-03-10T10:10:36.687 回答
0

您可以通过覆盖现有的来编写自己的表单验证

def form_valid(self, form):
    clean = form.cleaned_data
    airport_name = clean.get('airport_name')
    airport_city = clean.get('airport_city')
    if airport_name:
        form.instance.airport_name = airport_name
    if airport_city:
        form.instance.airport_city = airport_city

    return super(UpdateAirport, self).form_valid(form)

确保这些字段不是必需的

于 2020-03-10T10:14:12.160 回答
0

使用UpdateView子类,可以替换form_valid方法。

def form_valid(self, form):
    self.object = form.save( commit = False)
    self.object.save( update_fields=['name', ... ])  # save only the specified fields
    return HttpResponseRedirect(self.get_success_url())

宝贵的参考资料:Classy CBV

于 2020-03-10T10:57:21.210 回答