首页 > 解决方案 > Django 中的更新表单必须更新对象的所有字段吗?

问题描述

我在我的 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。

标签: pythondjangodjango-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


推荐阅读