我如何拥有一个带有FileField的表单,其中上传的文件将不会被保存,而是其文本内容将被提取和显示?
我有一个带有FileField的模型:
class DocumentUpload(models.Model):
document_name = models.CharField(max_length=100, blank=True)
document_path = models.FileField(upload_to='uploads')
Run Code Online (Sandbox Code Playgroud)
以及使用此模型的表单
class DocumentUploadForm(forms.ModelForm):
class Meta:
model = DocumentUpload
Run Code Online (Sandbox Code Playgroud)
当我使用表单创建新的上传时,一切正常.
if request.method == 'POST':
form = DocumentUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试更新/编辑条目时,它会更新除上载文档之外的所有字段.这与原始上传保持一致.
d = get_object_or_404(DocumentUpload, pk=id)
if request.method == 'POST':
form = DocumentUploadForm(data=request.POST, files=request.FILES, instance=d)
if form.is_valid():
u = form.save()
Run Code Online (Sandbox Code Playgroud)
如何在编辑实例时更改上传文件?
谢谢
我有一个这样的模型:
class Talk(BaseModel):
title = models.CharField(max_length=200)
mp3 = models.FileField(upload_to = u'talks/', max_length=200)
seconds = models.IntegerField(blank = True, null = True)
Run Code Online (Sandbox Code Playgroud)
我想在保存之前验证上传的文件是MP3,如下所示:
def is_mp3(path_to_file):
from mutagen.mp3 import MP3
audio = MP3(path_to_file)
return not audio.info.sketchy
Run Code Online (Sandbox Code Playgroud)
一旦我确定我有一个MP3,我想在seconds属性中保存通话的长度,如下所示:
audio = MP3(path_to_file)
self.seconds = audio.info.length
Run Code Online (Sandbox Code Playgroud)
问题是,在保存之前,上传的文件没有路径(请参阅此票证,关闭为wontfix),因此我无法处理MP3.
我想提出一个很好的验证错误,以便ModelForms可以显示一个有用的错误("你这个白痴,你没有上传MP3"或其他东西).
知道如何在保存文件之前访问该文件吗?
ps如果有人知道验证文件的更好方法是MP3,我会全神贯注 - 我也希望能够搞乱ID3数据(设置艺术家,专辑,标题和专辑艺术,所以我需要它可以处理通过mutagen).
我已经尝试过django-filer在单个文件字段中选择多个文件,我尝试使用我的简单模型,我面临着这个模板错误.我刚刚在django admin中使用了一个简单的模型.请你帮助我好吗?
class MyFile(models.Model):
title = models.CharField(max_length=200)
cover = FilerFileField(null=True,blank=True)
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/filer/folder/?t=id&pop=1
Django Version: 1.3.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'filer',
'intelligence_centre']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template error:
In template /usr/local/lib/python2.6/dist-packages/filer/templates/admin/filer/tools/clipboard/clipboard.html, error at line 1
'thumbnail' is not a valid tag library: Template library thumbnail not found, tried django.templatetags.thumbnail,django.contrib.admin.templatetags.thumbnail,filer.templatetags.thumbnail
1 : {% load thumbnail i18n %}
2 : {% for clipboard in user.filer_clipboards.all %}
3 …Run Code Online (Sandbox Code Playgroud) 我已经在Django中使用FileField编写了一个电子邮件表单类。我想通过检查其mimetype来检查上传文件的类型。随后,我想将文件类型限制为pdf,word和开放式Office文档。
为此,我已经安装了python-magic,并希望按照python-magic的规范检查文件类型,如下所示:
mime = magic.Magic(mime=True)
file_mime_type = mime.from_file('address/of/file.txt')
Run Code Online (Sandbox Code Playgroud)
但是,最近上传的文件在我的服务器上缺少地址。我还不知道任何类似于“ from_file_content”的mime对象的方法,该方法可以检查给定文件内容的mime类型。
使用魔术验证Django表单中上传文件的文件类型的有效方法是什么?
我正在尝试测试一个自编写的FormField AudioFileFormField,它在存储之前检查文件是否是一个audiofile.为此我已经覆盖了to_python方法.试图测试这个FormField我遇到了一些困难.
到目前为止这是我的TestCase:
from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
class TestAudioFileFormField(TestCase):
""" test the formfield to use for AudioFile Uploads """
class TestForm(forms.Form):
audiofilefield = AudioFileFormField()
def setUp(self):
self.AUDIOFILE_TEST_ROOT = os.path.dirname(__file__) + '/data/'
self.files = audiofile_files
def test_to_python(self):
""" assign some files to a form and validate the form """
f = file(self.AUDIOFILE_TEST_ROOT + self.files[0])
file_data = {'audiofilefield':SimpleUploadedFile( self.files[0],f.read() )}
data = {}
form = self.TestForm(data,f)
form.is_valid()
Run Code Online (Sandbox Code Playgroud)
form.is_valid()行引发了一个AttributeError:'file'对象没有属性'get'
当我在form.is_valid()之前插入调试跟踪时,这是我在该交互式会话中得到的:
ipdb> form.is_valid()
AttributeError: 'file' object …Run Code Online (Sandbox Code Playgroud) 问题如上所述。虽然有很多关于使用 django Rest 框架上传文件的教程。没有人提到它的可恢复版本。我需要在一个项目中实现它。有人可以向我指出一些资源或提供示例代码吗?非常感谢您的帮助。
更新
这是我到目前为止所得到的。
视图.py
class FileUploadView(views.APIView):
parser_classes = (FormParser, MultiPartParser)
def put(self, request, format=None):
file_obj = request.data['file']
self.handle_uploaded_file(file_obj)
return Response(status=204)
def handle_uploaded_file(self, ufile):
filename = "{0}/{1}".format(settings.MEDIA_ROOT, ufile)
with open(filename, "wb+") as target:
for chunk in ufile.chunks():
target.write(chunk)
Run Code Online (Sandbox Code Playgroud)
卷曲命令
curl -H "Content-Disposition: attachment; filename=try.py" -X PUT -F "file=@try.py" http://localhost:8000/api/fileupload/?filename=testing
Run Code Online (Sandbox Code Playgroud)
尝试.py
from django.test import TestCase
# Create your tests here.
Run Code Online (Sandbox Code Playgroud)
下一部分是如何使其可恢复。
我正在使用 boto3 将文件上传到 S3 并将其路径保存在 FileField 中。
class SomeFile(models.Model):
file = models.FileField(upload_to='some_folder', max_length=400, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
对于上述模型,以下代码可用于创建记录。
ff = SomeFile(file='file path in S3')
ff.full_clean()
ff.save()
Run Code Online (Sandbox Code Playgroud)
现在,当我使用 ModelSerializer 执行相同操作时。
class SomeFileSerializer(serializers.ModelSerializer):
class Meta:
model = SomeFile
fields = ('file')
Run Code Online (Sandbox Code Playgroud)
运行下面的代码后出现此错误
rest_framework.exceptions.ValidationError: {'file': [ErrorDetail(string='提交的数据不是文件。请检查表单上的编码类型。', code='invalid')]}
serializer = SomeFileSerializer(data={'file': 'file path to S3'})
serializer.is_valid(raise_exception=True)
Run Code Online (Sandbox Code Playgroud)
我需要帮助来设置序列化器以接受文件路径,而无需实际拥有该文件。
django django-models django-file-upload django-serializer django-rest-framework
我创建了一个带字段的ModelForm title,file和content.这file是一个FileField().但save()由于某些原因,我无法调用此表单的方法.所以我必须手动创建一个模型对象并将清理后的值分配给该对象.FileField的所有功能都让人感到震惊.该文件未保存.我怎样才能解决这个问题?它是提取FileField的正确方法吗?
形成
class TestForm(forms.ModelForm):
class Meta:
model = Test
fields = ('title','file', 'content',)
Run Code Online (Sandbox Code Playgroud)
Views.py
form = TestForm(request.POST,request.FILES)
if form.is_valid():
content = form.cleaned_data['content']
file = form.cleaned_data['file']
title = form.cleaned_data['title']
fax = Fax()
fax.title = title
fax.file = file
fax.content = content
fax.save()
Run Code Online (Sandbox Code Playgroud)
这里的文件没有保存.我怎样才能解决这个问题?任何帮助将不胜感激!
我是一名学习 django rest 框架的学生
我尝试使用表单数据上传多个文件
当我在邮递员中发送这样的请求时
发生错误,这是错误消息
images_data = self.context.get('request').request.FILES
AttributeError: 'NoneType' 对象没有属性 'request'
这是模型
class Post(models.Model):
text = models.CharField(max_length=5000)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Image(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
image = models.FileField(blank=True)
Run Code Online (Sandbox Code Playgroud)
和意见
class AddPost(APIView):
serializer_class = PostSerializer
def post(self, request, format=None):
serializer = PostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return JsonResponse({'status':status.HTTP_200_OK, 'message':"sucess", 'data':""})
Run Code Online (Sandbox Code Playgroud)
序列化程序
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
class PostSerializer(serializers.ModelSerializer):
images = FileSerializer(source='image_set', many=True, read_only=True)
class Meta:
model = Post
fields …Run Code Online (Sandbox Code Playgroud) django django-file-upload django-serializer django-rest-framework