如果您想了解在运行时确定带有upload_to的DjangoFileField和在运行时才确定的函数调用称为的知识,那么本篇文章将是您的不二之选。我们将深入剖析在运行时确定带有upload_to的Dj
如果您想了解在运行时确定带有upload_to的Django FileField和在运行时才确定的函数调用称为的知识,那么本篇文章将是您的不二之选。我们将深入剖析在运行时确定带有upload_to的Django FileField的各个方面,并为您解答在运行时才确定的函数调用称为的疑在这篇文章中,我们将为您介绍在运行时确定带有upload_to的Django FileField的相关知识,同时也会详细的解释在运行时才确定的函数调用称为的运用方法,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- 在运行时确定带有upload_to的Django FileField(在运行时才确定的函数调用称为)
- ajax – 使用Django的FileUpload
- Apache FileUpload的两种上传方式介绍及应用 --> upload file done! --> upload file done!
- Django - 带有值的 AutoCompleteSelectMultipleField
- django fileup-load
在运行时确定带有upload_to的Django FileField(在运行时才确定的函数调用称为)
我正在尝试设置我的上传文件,这样,如果用户joe上传文件,它将转到MEDIA_ROOT / joe,而不是让每个人的文件都转到MEDIA_ROOT。问题是我不知道如何在模型中定义它。这是当前的外观:
class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to=''.'')
所以我想要的不是“。” 作为upload_to,将其作为用户名。
我知道从Django 1.0开始,你可以定义自己的函数来处理upload_to,但是该函数不知道谁将成为谁,所以我有点迷路了。
谢谢你的帮助!
答案1
小编典典你可能已经阅读了文档,所以这里有一个简单的示例可以使之有意义:
def content_file_name(instance, filename): return ''/''.join([''content'', instance.user.username, filename])class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to=content_file_name)
如你所见,你甚至不需要使用给定的文件名-如果愿意,你也可以在可调用的upload_to中覆盖该文件名。
ajax – 使用Django的FileUpload
前端代码非常基本:
<div id="image_uploader">Upload More Images</div> <script type="text/javascript" charset="utf-8"> function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('image_uploader'),action: '/add/image/1',debug: true,onSubmit : function () { progress.show(); },onComplete : function () { progress.hide(); },onCancel : function () { progress.hide(); },}); }; createUploader(); </script>
后端代码(当前正在进行中)也非常基本:
def add_image(request,id): print request if request.FILES: return HttpResponse("{success:true}") else: return HttpResponse("{success:false,message:'Unable to find FILES}")
request.FILES仅用于尚未发生的情况.我正在使用ajax-upload直接与Photologue对话,我的代码看起来像这样:
def save_upload( uploaded,filename,raw_data ): """ raw_data: if True,upfile is a HttpRequest object with raw post data as the file,rather than a Django UploadedFile from request.FILES """ try: filename = os.path.normpath(os.path.join(IMAGE_UPLOAD_PATH,filename)) with BufferedWriter( FileIO( filename,"wb" ) ) as dest: # if the "advanced" upload,read directly from the HTTP request # with the Django 1.3 functionality if raw_data: (dirName,fileName) = os.path.split(filename) (fileBaseName,fileExtension)=os.path.splitext(fileName) # # right here,if fileBaseName is less than n characters,might want to slap on a date just for fun # try: i_can_has_p = Photo.objects.get(title=fileBaseName) title = fileBaseName + "_" + str(datetime.datetime.Now().strftime("%Y%m%dT%H%M%s")) except Photo.DoesNotExist: title = fileBaseName title_slug = slugify(title) p = Photo(title=title,title_slug=title_slug) p.image.save(filename,ContentFile(uploaded.read())) # if not raw,it was a form upload so read in the normal Django chunks fashion else: # Todo: figure out when this gets called,make it work to save into a Photo like above for c in uploaded.chunks( ): dest.write( c ) except IOError: # Could not open the file most likely return False return True def ajax_upload( request ): if request.method == "POST": # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload if request.is_ajax( ): # the file is stored raw in the request upload = request is_raw = True try: filename = request.GET[ 'qqfile' ] except KeyError: return HttpResponseBadRequest( "AJAX request not valid" ) # not an ajax upload,so it was the "basic" iframe version with submission via form else: is_raw = False if len( request.FILES ) == 1: # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an # ID based on a random number,so it cannot be guessed here in the code. # Rather than editing Ajax Upload to pass the ID in the querystring,note that # each upload is a separate request so FILES should only have one entry. # Thus,we can just grab the first (and only) value in the dict. upload = request.FILES.values( )[ 0 ] else: raise Http404( "Bad Upload" ) filename = upload.name # save the file success = save_upload( upload,is_raw ) # let Ajax Upload kNow whether we saved it or not ret_json = { 'success': success,} return HttpResponse( json.dumps( ret_json ) )
在我的例子中,ajax_upload是ajax的action:参数调用的函数
Apache FileUpload的两种上传方式介绍及应用 --> upload file done! --> upload file done!
本文为大家介绍下FileUpload的两种上传方式:Traditional API上传方式/Streaming API上传方式,感兴趣的朋友可以参考下哈,希望可以帮助到你
环境:
tomcat5.6
commmons-fileupload-1.3.jar
commmons-io-2.4.jar
JSP
编码:UTF-8
临时文件夹:fileupload/tmp相对于网站根目录
上传文件保存位置:fileupload
Traditional API上传方式
//fileload01.htm
复制代码 代码如下:
File to upload:
to upload the file!
//Traditionalapi.jsp
复制代码 代码如下:
request.setCharacterEncoding("UTF-8");
// file less than 10kb will be store in memory, otherwise in file system.
final int threshold = 10240;
final File tmpDir = new File(getServletContext().getRealPath("/") + "fileupload" + File.separator + "tmp");
final int maxRequestSize = 1024 * 1024 * 4; // 4MB
// Check that we have a file upload request
if(ServletFileUpload.isMultipartContent(request))
{
// Create a factory for disk-based file items.
FileItemFactory factory = new diskFileItemFactory(threshold, tmpDir);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint.
upload.setSizeMax(maxRequestSize);
List items = upload.parseRequest(request); // FileUploadException
for(FileItem item : items)
{
if(item.isFormField()) //regular form field
{
String name = item.getFieldName();
String value = item.getString();
%>
-->
}
else
{ //file upload
String fieldName = item.getFieldName();
String fileName = item.getName();
File uploadedFile = new File(getServletContext().getRealPath("/") +
"fileupload" + File.separator + fieldName + "_" + fileName);
item.write(uploadedFile);
%>
upload file done!
}
}
}
%>
Streaming API上传方式
//fileupload02.htm
复制代码 代码如下:
File to upload:
to upload the file!
//streamingapi.jsp
复制代码 代码如下:
request.setCharacterEncoding("UTF-8");
// Check that we have a file upload request
if(ServletFileUpload.isMultipartContent(request))
{
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while(iter.hasNext())
{
FileItemStream item = iter.next();
String fieldName = item.getFieldName();
InputStream is = item.openStream();
if(item.isFormField()) //regular form field
{
%>
-->
}
else
{ //file upload
String fileName = item.getName();
File uploadedFile = new File(getServletContext().getRealPath("/") +
"fileupload" + File.separator + fieldName + "_" + fileName);
OutputStream os = new FileOutputStream(uploadedFile);
// write file to disk and close outputstream.
Streams.copy(is, os, true);
%>
upload file done!
}
}
}
%>
Traditional API vs Streaming API
Streaming API上传速度相对较快。因为它是利用内存保存上传的文件,节省了传统API将文件写入临时文件带来的开销。
可参考:
http://stackoverflow.com/questions/11620432/apache-commons-fileupload-streaming-api
This page describes the Traditional API of the commons fileupload library. The Traditional API is a convenient approach. However, for ultimate performance, you might prefer the faster Streaming API.
http://commons.apache.org/proper/commons-fileupload/using.html
Django - 带有值的 AutoCompleteSelectMultipleField
如何解决Django - 带有值的 AutoCompleteSelectMultipleField?
我正在使用 AutoCompleteSelectMultipleField
中的 ajax_select.fields
并且它工作正常 - 我根据我正在编写的内容获取值,但我希望在我写一些东西之前显示所有值。有没有我遗漏的配置,或者我应该使用不同的配置吗?
此刻我有:
form.fields[''teams''] = AutoCompleteSelectMultipleField(
''master_teams'',plugin_options={
''source'': f"{reverse(''ajax_lookup'',kwargs={''channel'': ''master_teams''})}?game_slug={self.game.slug}"},required=False,help_text="Enter team name",)
在我的查找文件中,我只是过滤我的查询以获取特定数据,我想将它们显示为模板中的下拉列表。谁能给我任何提示如何解决这个问题?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
django fileup-load
##文件上传
###使用form表单类的上传
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
view处理这个form将会从request.FILES中接收file data,它是一个包含所有表单中FileField、ImageField和其他FileField的子类的字典,获取某个文件用request.FILES[''filename'']
注:上传文件的form表单必须是POST method,并且enctyoe="ultipart/form-data"。否则request.FILES将为空。
大多数情况下,您只需将文件数据从请求传递到表单,就像绑定上传文件到表单中所描述的那样。例如:
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
def upload_file(request):
if request.method == ''POST'':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES[''file''])
return HttpResponseRedirect(''/success/url/'')
else:
form = UploadFileForm()
return render(request, ''upload.html'', {''form'': form})
# 上传文件
def handle_uploaded_file(f):
with open(''some/file/name.txt'', ''wb+'') as destination:
for chunk in f.chunks():
destination.write(chunk)
注:通过UploadedFile.chunks()进行循环而不是使用read()可以确保大文件不会淹没系统的内存。
##Handling uploaded files with a model
# models.py
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
nid = models.AutoField(primary_key=True)
telephone = models.CharField(max_length=11, null=True, unique=True)
avatar = models.FileField(upload_to=''avatars/'', default="avatars/default.png")
# forms.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField
def upload_file(request):
if request.method == ''POST'':
form = ModelFormWithFileField(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect(''/success/url/'')
else:
form = ModelFormWithFileField()
return render(request, ''upload.html'', {''form'': form})
##多文件上传
forms.py
from django import forms
class FileFieldForm(forms.Form):
file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={''multiple'': True}))
重写FormView
# views.py
from django.views.generic.edit import FormView
from .forms import FileFieldForm
class FileFieldView(FormView):
form_class = FileFieldForm
template_name = ''upload.html'' # Replace with your template.
success_url = ''...'' # Replace with your URL or reverse().
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist(''file_field'')
if form.is_valid():
for f in files:
... # Do something with each file.
return self.form_valid(form)
else:
return self.form_invalid(form)
关于在运行时确定带有upload_to的Django FileField和在运行时才确定的函数调用称为的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于ajax – 使用Django的FileUpload、Apache FileUpload的两种上传方式介绍及应用 --> upload file done! --> upload file done!、Django - 带有值的 AutoCompleteSelectMultipleField、django fileup-load的相关知识,请在本站寻找。
本文标签: