python - Django 中的更新表单必须更新对象的所有字段吗?
问题描述
我在我的 Django 应用程序中创建了多个更新表单。
我的问题是:Django 是否需要更新对象的每个字段,或者有没有办法只更新实际更改的字段?
因此,例如,我可能有一个带有Airport Name
, Airport City
,的表单Airport Country
。我可能会使用更新表单来更新Country
. Django 是否还需要填写Name
和City
表单字段然后更新,或者有没有办法将它们留空而不更新数据库?
编辑
这是模型:
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。
解决方案
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
推荐阅读
- jenkins - 更新 。Jenkins 中的 Nuspec 文件
- firebase - Firebase/Flutter:未处理的异常:NoSuchMethodError:getter 'isNotEmpty' 在 null 上被调用
- python - 使用 python 将 CSV 从 raspberry pi3 发送到 raspberry pi 3
- c# - 如何使用实体框架核心获得每个月的总回报
- javascript - 如何在 for 循环中使用 async/await 处理单个 Promise 异常
- firebase - 带有嵌套 ForEach 或 For in 的 Swift
- regex - VBA将cmd结果设置为字符串并将其剥离
- cakephp - 解决此错误的可能方法是什么?我正在将我的项目从 cakephp 2.x 迁移到 cakephp 4.x
- ssl - Iphone 无法连接到 exim 邮件服务器
- python - 使用 2 个 for 循环列出理解行为