我的目标是让用户上传文档,但是我的程序会自动命名该文档。本质上,从视图中,我将名称传递到表单中,该名称放置在文档模型的“描述”字段中。谢谢!
Views.py
def testing(request):
if request.method == 'POST':
name = 'testing'
form = DocumentForm(request.POST, request.FILES, description=name)
if form.is_valid():
form.save()
return redirect('landing')
else:
form = DocumentForm()
return render(request, 'testing.html', {
'form': form
})
forms.py
class DocumentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
description = kwargs.pop('description')
super(DocumentForm,self).__init__(*args, **kwargs)
self.fields['description'].initial = description
class Meta:
model = Document
fields = ('description', 'document', )
models.py
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
答案 0 :(得分:0)
从ModelForm更新新实例仅需要修改视图中的保存。让我知道这是否不是您的意思,我应该能够进一步提供帮助。
def testing(request):
if request.method == 'POST':
name = 'testing'
form = DocumentForm(request.POST, request.FILES, description=name)
if form.is_valid():
# get instance but don't commit to database
doc = form.save(commit=False)
# do modifications to the instance here.
doc.description = name
# save the instance with all modifications
doc.save()
return redirect('landing')
else:
form = DocumentForm()
return render(request, 'testing.html', {
'form': form
})
更新1
您需要在kwargs.pop("description")
上执行以下操作。发生的是,在其他情况下,您创建的表单没有description关键字。
class DocumentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DocumentForm,self).__init__(*args, **kwargs)
if 'description' in kwargs:
description = kwargs.pop('description')
self.fields['description'].initial = description
class Meta:
model = Document
fields = ('description', 'document', )