本文整理汇总了Python中forms.UploadForm.is_valid方法的典型用法代码示例。如果您正苦于以下问题:Python UploadForm.is_valid方法的具体用法?Python UploadForm.is_valid怎么用?Python UploadForm.is_valid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类forms.UploadForm
的用法示例。
在下文中一共展示了UploadForm.is_valid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: upload
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload(request):
if request.method == "POST":
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
subject = form.cleaned_data["subject"]
message = form.cleaned_data["message"]
attach2 = request.FILES["attach"]
sender = form.cleaned_data["sender"]
cc_myself = form.cleaned_data["cc_myself"]
recipient = ["[email protected]"]
if cc_myself:
recipient.append(sender)
try:
mail = EmailMessage(subject, message, sender, recipient, ["EMAIL_ADDRESS"])
mail.attach(attach2.name, attach2.read(), attach2.content_type)
mail.send()
except:
return "Attachment error"
return HttpResponseRedirect(reverse("feel_home"))
else:
# Dynamic initial values.
form = UploadForm(initial={"sender": "Email address"})
return render(request, "upload.html", {"form": form})
示例2: upload_img
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload_img(request):
form = UploadForm()
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
if not os.path.isdir(app_settings['DIC_UPLOAD_FULL']):
os.makedirs(app_settings['DIC_UPLOAD_FULL'])
filename = "%s.%s" % (get_file_code(), form.cleaned_data['image'].name.split('.')[-1])
filepath = os.path.join(app_settings['DIC_UPLOAD_FULL'], filename)
fileurl = '%s%s' % (app_settings['DIC_IMG_URL'], filename)
f = open(filepath, 'wb+')
for chunk in form.cleaned_data['image'].chunks():
f.write(chunk)
f.close()
image = Image.open(filepath)
if image.size[0] > app_settings['DIC_IMG_SIZE'][0] and image.size[1] > app_settings['DIC_IMG_SIZE'][1]:
image.thumbnail(app_settings['DIC_IMG_SIZE'], Image.ANTIALIAS)
print filepath
image.save(filepath)
width_b = image.size[0]
height_b = image.size[1]
width = int(request.GET.get('w'))
height = int(request.GET.get('h'))
return HttpResponseRedirect('%s?filename=%s&w=%s&h=%s&wb=%s&hb=%s' % (reverse('dic-crop-img'), filename, width, height, width_b, height_b))
return render_to_response('django_img_crop/upload-img.html', {'form': form, 'is_popup': True}, context_instance=RequestContext(request))
示例3: upload_file
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload_file(request):
resp = {}
url = str(request.get_full_path())
pid = url.split("/")[-1]
try:
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
#获取表单信息
xlsfile = form.cleaned_data['Filedata']
filename = xlsfile.name
#写入数据库
uf = Upload(Filedata = xlsfile, uptime = datetime.datetime.now())
uf.save()
filepath = uf.Filedata
uipath = unicode(str(filepath), "utf8")
uipath = os.path.join(settings.MEDIA_ROOT,uipath)
excel_table_byindex(request,file= uipath, pid = pid)
resp['success'] = True
else:
form = UploadForm()
except Exception,e:
info = "%s" % (sys.exc_info()[1])
resp['success'] = False
resp['message'] = info
示例4: judge_action
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def judge_action(request):
form = UploadForm(request.POST)
if form.is_valid():
data = form.cleaned_data
context = data['context']
if '_auth_user_id' in request.session:
user_id = request.session['_auth_user_id']
user = User.objects.get(id=user_id)
else:
user = None
if request.FILES.has_key('image'):
image = request.FILES['image']
else:
image = None
if image != None and image.size > 3 * 1024 * 1024:
return render_to_response('result.jinja', {'state':'2', 'message':u'图片最大3M', 'url':'/main/upload'}, RequestContext(request))
item = Item.objects.create(
user=user,
context=context,
time=datetime.now(),
image=image,
status=0,
agree=random.randint(100, 200),
disagree=random.randint(0, 50),
score=int(time.time() / (60 * 60) * 1000),
)
item.save()
return render_to_response('result.jinja', {'state':'1', 'message':u'上传成功', 'url':'/main/upload'}, RequestContext(request))
else:
for field in form:
if field.errors:
return render_to_response('result.jinja', {'state':'2', 'message':field.errors, 'url':'/main/upload'}, RequestContext(request))
示例5: handleImagePopAdd
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def handleImagePopAdd(request, addForm, field, template="form/popmediaadd.html"):
if not request.method == "POST":
f = UploadForm()
ctx = {'form': f, 'field': field}
return render(request, template, ctx)
f = UploadForm(request.POST, request.FILES)
if not f.is_valid() and not request.FILES['file'].name.endswith('.svg'):
ctx = {'form': f, 'field': field}
return render(request, template, ctx)
file = request.FILES['file']
store_in_s3(file.name, file.read())
p = Image(url="http://%s.s3.amazonaws.com/%s" % (bucket, file.name))
if isinstance(request.user, AnonymousUser):
p.user = User.objects.get(username="Anonymous")
else:
p.user = User.objects.get(username=request.user)
if request.POST['artist']:
p.artist = User.objects.get(pk=request.POST['artist'])
p.save()
newObject = p
# Self destruction:
if newObject:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' %\
(escape(newObject._get_pk_val()), escape(newObject)))
示例6: put
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def put(request):
"""
Se ocupa de poner un fichero en tagfs,
verificando que se cumplen todos los requisitos del form.
"""
form = UploadForm()
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
name = form.cleaned_data['name']
description = form.cleaned_data['description']
tags_cleaned = form.cleaned_data['tags']
data = form.cleaned_data['data']
replication = form.cleaned_data['replication']
tags = set()
for tag in tags_cleaned.split():
tags.add(tag)
data = data.read()
description = not description and 'Uploaded using the web client.' or description
replication = not replication and 25 or replication
save = CLIENT.put(name, description, tags, 'tagfs', 'tagfs', 775, data, replication)
form = UploadForm()
return render_to_response(PUT_TEMPLATE,
{'form_put': form.as_p(), 'save': save,
'put': True},
context_instance=RequestContext(request))
return render_to_response(PUT_TEMPLATE,
{'form_put': form.as_p(), 'put': True},
context_instance=RequestContext(request))
示例7: upload_file
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload_file(request):
msg = ''
if request.method == 'POST':
form = UploadForm(request.POST,request.FILES)
if form.is_valid():
user_capacity = User_capacity.objects.get(user=request.user)
form = form.cleaned_data
the_file = form['upload_file']
user_name = request.user.username
size = the_file.size
capacity = user_capacity.capacity
if capacity - size < 0:
msg = 'Su archivo no pudo ser subido, excede su capacidad de almacenamiento (%s)' % (str(user_capacity))
data = {'form':UploadForm(initial={'choices':'privado'}),
'msg':msg}
return render(request,'upload_file.html',data)
scale = 'B'
if size > 1048576: # mayor a 1 MB
size = size / 1048576.0
scale = 'MB'
elif size > 1024: # mayor a 1 KB
size = size / 1024.0
scale = 'KB'
filepath = os.path.join(settings.BASE_DIR,'BajarCaja','uploads',user_name+'_files',the_file.name)
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
with open(filepath, 'wb') as destination:
for chunk in the_file.chunks():
destination.write(chunk)
file_db = File(
filename=the_file.name,
upload_date=datetime.now(),
filepath=filepath,
size=size,
real_size=the_file.size,
scale_sz = scale,
public=form['choices']=='publico',
user=request.user)
file_db.save()
user_capacity.capacity = capacity - the_file.size
if user_capacity.capacity >= 1048576: # mayor a 1 MB
user_capacity.capacity_show = user_capacity.capacity / 1048576.0
user_capacity.scale_sz = 'MB'
elif user_capacity.capacity >= 1024: # mayor a 1 KB
user_capacity.capacity_show = user_capacity.capacity / 1024.0
user_capacity.scale_sz = 'KB'
else:
user_capacity.capacity_show = user_capacity.capacity / 1.0
user_capacity.scale_sz = 'B'
user_capacity.save()
msg = 'Archivo %s subido exitosamente.' % (the_file.name)
data = {'form':UploadForm(initial={'choices':'privado'}),
'msg':msg}
return render(request,'upload_file.html',data)
示例8: index
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def index(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
#print form.is_valid()
if form.is_valid():
return HttpResponseRedirect('/thanks/')
spreadsheet = request.FILES['spreadsheet']
print spreadsheet.content_type
else:
form = UploadForm()
return render(request, 'frontpage/index.html', {'form': form})
示例9: simple_upload
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def simple_upload(request):
"""
Handles uploaded files
"""
try:
if request.method == 'POST': # If the form has been submitted...
user = request.user if request.user.is_authenticated() else None
form = UploadForm(request.POST, request.FILES) # A form bound to the POST data
if form.is_valid(): # File was posted with form
c = None
kwargs = {}
kwargs['author'] = user.username.title() if user else 'Anonymous'
# Create a new Egg
e = Egg(**kwargs)
print kwargs
for filefield, tmpname in handle_uploaded_file(request):
print "HANDLING FILE:", filefield, tmpname
c = Content(**kwargs)
originalname = str(request.FILES["file"])
# c.user = request.user # Only authenticated users can use this view
c.set_file(originalname, tmpname) # Save uploaded file to filesystem
c.get_type_instance() # Create thumbnail if it is supported
c.save()
e.content = c
e.uid = c.uid
break # We save only the first file
if c:
c.user = user
c.save()
e.user = user
print "USER", user
if user:
response_status = 200 # Created
else:
response_status = 401 # Unauthorized
e.save()
# We can handle tags after egg has id (it is saved)
response = HttpResponse(status=response_status)
#response.status_code = 201
# FIXME: use reverse()
#return HttpResponseRedirect(reverse('egg api', args=[e.uid]))
response['Location'] = '/fourdnest/api/v1/egg/%s/' % e.uid
return response
else:
response = HttpResponse(status=204)
return response
else:
raise Http404
except Exception, err:
print err
raise
return HttpResponse("Server error", status=500)
示例10: upload
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
image = UploadedImage(name = form.cleaned_data['name'], file = form.cleaned_data['file'])
image.save()
return HttpResponseRedirect('/')
else:
form = UploadForm()
return render(request, 'upload.html', {
'form': form,
})
示例11: puzzle_upload
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def puzzle_upload(request, puzzle_id):
puzzle = Puzzle.objects.get(id=puzzle_id)
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
handle_puzzle_upload(puzzle, form.cleaned_data['name'], request.FILES['file'])
return redirect(reverse('puzzles.views.puzzle_info', args=[puzzle_id]))
else:
form = UploadForm()
return render_to_response('puzzles/puzzle-upload.html', puzzle_context(request, {
'form': form,
'puzzle': puzzle
}))
示例12: subir
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def subir(request):
try:
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
NewPhoto = Fotos(album=request.POST['album'], url=request.FILES['url'])
NewPhoto.save()
messages.success(request, 'Imagen subida exitosamente!!! Por favor espere que nuestros administradores la aprueben para que pueda verla publicada')
else:
messages.error(request, 'Formato de archivo no aceptado')
else:
messages.error(request, 'Error al subir imagen')
except Exception, e:
logger.debug(e)
messages.error(request, 'Error al subir imagen')
示例13: index
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def index(request):
#add to session starting_from=0
#return first 5 photos via return_next_posts
#context = RequestContext(request, )
#print settings.CONSUMER_KEY
if request.method == 'POST':
#if user is trying to submit new photo
form = UploadForm(request.POST, request.FILES)
if form.is_valid() and request.is_ajax() :
description = form.cleaned_data['description']
print description
#think about resizing to a certain size!
#it has to be a photo (jpg, npg...) not some other
#file type
photo = form.cleaned_data['photo']
#create and save post, but save with status pending !DONE!///
#Post(description=description, original_photo=photo, ).save()
logger.info("new photo sent")
#also return notification regarding the success or failure
#of post submission
return HttpResponse(json.dumps({'message':"success"}))#to return clean form
else:
#handle badly submitted forms aka
#someone putted something that isn't a photo
#when called using ajax it's being recognized as invalid
#it is required to use FormData as wrapper around form data in html
#form_object.serialize() works only for form without file fields
errors = form.errors
print errors
#print "request: ", request
return HttpResponse(json.dumps({'message':errors}))
else:
#if user is first time on the page
logger.info("came to index page")
form = UploadForm()
#get latest Posts (doing that by putting minus sign)
#negativ index slicing is not allowed while querying in Django
#take care of case when the number of posts is less then list_end
#it take cares by it self
list_end = 3
posts = Post.objects.filter(status=Post.ACCEPTED).order_by('-pub_date')[:list_end]
request.session['start_from']=list_end
#increment start_from at the end
return render(request, 'photos/index.html', {'form':form, 'posts':posts})
示例14: upload
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def upload(request, json=False):
if request.method == 'GET':
form = UploadForm()
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
data = request.FILES['file']
size = form.cleaned_data['file'].size
expire_date = form.cleaned_data['expire_date'] or one_week_later()
message = form.cleaned_data['message']
receiver = form.cleaned_data['receiver']
if form.cleaned_data['filename_overwrite']:
name = form.cleaned_data['filename_overwrite']
else:
name = form.cleaned_data['file'].name
file = File(name=name, owner=request.user,
expire_date=expire_date, message=message, size=size)
md5 = handle_uploaded_file(name, file.secret, data)
file.md5 = md5
file.save()
if receiver:
downloader = Downloader(email=receiver, file=file)
downloader.save()
url = 'http://%s/files/download/%s/%s' % \
(Site.objects.get_current().domain, file.id, file.secret)
from_ = request.user.email
mailit([receiver], from_, message, url)
if json:
response = {'status': 'ok', 'fileid': file.id}
return HttpResponse(simplejson.dumps(response))
else:
return HttpResponseRedirect('/files/list/')
if json:
response = {'status': 'error', 'message': 'form not valid'}
return HttpResponse(simplejson.dumps(response))
else:
return render_to_response('files/upload.html', {'form': form, }, context_instance=RequestContext(request))
示例15: analyse
# 需要导入模块: from forms import UploadForm [as 别名]
# 或者: from forms.UploadForm import is_valid [as 别名]
def analyse(request, request_id=None, page=None):
"""
Render view for uploading data and presenting analysis results.
"""
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
request_id = path.splitext(request.FILES['data'].name)[0]
entities = _analyse(request.FILES['data'])
paginator = Paginator(entities, ENTITIES_PER_PAGE)
entities = paginator.page(1)
message = 'Success!'
else:
entities = []
message = form.errors['data']
else:
form = UploadForm()
message = None
if request_id and page:
try:
entities = parse_results(request_id)
except IOError:
raise Http404
paginator = Paginator(entities, ENTITIES_PER_PAGE)
try:
entities = paginator.page(page)
except EmptyPage:
return redirect('results', request_id=request_id, page=1)
else:
entities = []
dictionary = {
'title': 'TrendMiner Web Services',
'commit_tag': COMMIT_TAG,
'max_upload_size': MAX_UPLOAD_SIZE / (1024**2),
'form': form,
'message': message,
'rid': request_id,
'entities': entities,
}
return render_to_response(
"analyse.html", dictionary,
context_instance=RequestContext(request))