gpt4 book ai didi

python - Django 1.1 表单、模型和隐藏字段

转载 作者:太空宇宙 更新时间:2023-11-03 15:29:12 25 4
gpt4 key购买 nike

考虑以下 Django 模型:

class Host(models.Model):
# This is the hostname only
name = models.CharField(max_length=255)

class Url(models.Model):
# The complete url
url = models.CharField(max_length=255, db_index=True, unique=True)
# A foreign key identifying the host of this url
# (e.g. for http://www.example.com/index.html it will
# point to a record in Host containing 'www.example.com'
host = models.ForeignKey(Host, db_index=True)

我也有这个表格:

class UrlForm(forms.ModelForm):
class Meta:
model = Urls

问题如下:我想自动计算主机字段的值,所以我不希望它出现在网页中显示的 HTML 表单中。

如果我使用'exclude'从表单中省略这个字段,那么我该如何使用表单来保存信息在数据库中(这需要主机字段存在)?

最佳答案

使用commit=False:

result = form.save(commit=False)
result.host = calculate_the_host_from(result)
result.save()

关于python - Django 1.1 表单、模型和隐藏字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com