【发布时间】:2018-04-07 20:55:26
【问题描述】:
我发现这个示例使用 FileField 上传文件,效果很好。
https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html
问题是它保存了正在上传的文件的原始文件名。我不想要那个。我可以通过覆盖保存函数来更改 models.py 中的文件名(见下文)。在我的一生中,当我从 views.py 执行 form.save() 时,我无法弄清楚如何传递文件名。我需要知道另一个进程的文件名。我什至考虑过从 models.py 保存函数中返回一个文件名。我有点菜鸟,所以请原谅任何遗漏的细节。我已经搜索了这个站点并阅读了大量文档,但我遗漏了一些东西。任何建议将不胜感激。
Forms.py
class DocumentForm(forms.ModelForm):
message = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 50}))
class Meta:
model = Document
fields = ('description', 'document', )
模型.py
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='atlasapp/documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
randomNum = random.randint(10000,90000)
new_name = str(randomNum) + ".txt"
self.document.name = new_name
super(Document, self).save(*args, **kwargs)
Views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('model_form_upload')
else:
form = DocumentForm()
return render(request, 'model_form_upload.html', {'form': form})
【问题讨论】:
标签: django python-2.7