我有一个带有两个字段的模型,一个是唯一的uuid字段,另一个是urlfield
class Image(models.Model):
url = models.URLField()
uuid = models.UUIDField(default=uuid4,unique=True)
我创建了Django模型表格
class ImageUploadForm(forms.ModelForm):
filename = forms.HiddenInput()
class Meta:
model = Image
fields = "__all__"
在formview的uuid字段中将自动使用唯一的uuid进行设置,我想使用默认设置为自动设置为uuid的相同uuid来设置文件名。我该如何实现?
答案 0 :(得分:1)
您可以通过__init__
函数“ 修补”,并为给定字段设置一个.initial
值,例如:
class ImageUploadForm(forms.ModelForm):
filename = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(ImageUploadForm, self).__init__(*args, **kwargs)
self.fields['filename'].initial = self.instance.uuid
class Meta:
model = Image
fields = "__all__"