本文整理汇总了Python中photos.models.Photo.save方法的典型用法代码示例。如果您正苦于以下问题:Python Photo.save方法的具体用法?Python Photo.save怎么用?Python Photo.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类photos.models.Photo
的用法示例。
在下文中一共展示了Photo.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_default_photo
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def get_default_photo(self):
try:
return Photo.objects.filter(user_default=True)[0]
except IndexError:
user_fallback = "%s/photos/%s" % (settings.MEDIA_ROOT, "img_user_fallback.png")
try:
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
photo = Photo(user_default=True)
photo.save()
Photo.objects.filter(pk=photo.pk).update(image="photos/img_user_fallback.png")
photo = Photo.objects.get(pk=photo.pk)
fp.close()
return photo
except:
user_fallback = "%s/images/%s" % (settings.GLOBALS_STATIC_ROOT, "img_user_fallback.png")
fp = open(user_fallback, "r")
image = Image.open(fp)
image.verify()
fp2 = open(user_fallback, "r")
target_file = File(fp2)
name = "img_user_fallback.png"
photo = Photo(user_default=True)
photo.image.save(name, target_file, save=True)
fp.close()
fp2.close()
return photo
示例2: ghetto_fixtures
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def ghetto_fixtures(self):
from os.path import abspath, dirname, join
from django.contrib.auth.models import User
from django.core.files import File
from photos.models import Photo, PhotoSet
fixtures_dir = join(abspath(dirname(__file__)), "fixtures")
self.admin = User.objects.create_user('admin', '[email protected]', 's3cure!1')
self.set = PhotoSet.objects.create(name="default")
self.__photos = []
for i in range(1, 5):
name = "photo_{0}.jpg".format(i)
with open(join(fixtures_dir, name)) as f:
p = Photo(
title="Photo {0}".format(i),
photo_set=self.set)
p.image.save(name, File(f))
self.__photos.append(p)
p.save()
setattr(self, "photo_%d" % i, p)
示例3: index
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def index(request):
'''
the index view is responsible for managing user image uploads and
outputing a list of all uploaded images ordered by ratings to the
index.html template
'''
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
photo_name = form.cleaned_data['image_path']
new_img = Photo(
image = photo_name,
image_thumb = photo_name,
name = photo_name,
description = form.cleaned_data['image_desc']
)
new_img.save()
return HttpResponseRedirect(reverse('photos:index'))
else:
form = ImageForm()
photos_list = Photo.objects.all().order_by('-avg_rating', '-id')
return render(request, 'photos:index',
{'photos_list': photos_list, 'form': form})
示例4: submit
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def submit(request):
PhotoFormSet = formset_factory(PhotoForm, extra=1)
if request.method == 'POST':
storyform = StoryForm(request.POST, request.FILES)
photoformset = PhotoFormSet(request.POST, request.FILES)
if storyform.is_valid() and photoformset.is_valid():
s = Story(
title = storyform.cleaned_data['title'],
moderator = request.user
)
s.save();
for form in photoformset.cleaned_data:
image = form['image']
p = Photo(
name=s.title,
story=s,
image=image
)
p.save()
else:
storyform = StoryForm()
photoformset = PhotoFormSet()
return render(request, 'stories/submit.html', {'storyfrom': storyform, 'photoformset': photoformset})
示例5: post
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def post(self, request, *args, **kwargs):
# Ajax POST for file uploads
if request.is_ajax():
custom_post = QueryDict('temp_hash=%s' % request.POST.get('temp_hash'))
file_form = PhotoUploadForm(request.POST, request.FILES)
print(request.POST)
print(request.FILES)
if file_form.is_valid():
# file_form.save()
response = {'file': []}
for photo in request.FILES.getlist('file'):
# Create a new entry in our database
new_image = Photo(image=photo,
temp_hash=request.POST.get('temp_hash'))
# Save the image using the model's ImageField settings
new_image.save()
response['file'].append({
'name': '%s' % new_image.id,
'size': '%d' % request.FILES.__sizeof__(),
'url': '%s' % new_image.image.url,
'thumbnailUrl': '%s' % new_image.image.url,
'deleteUrl': '\/image\/delete\/%s' % new_image.id,
"deleteType": 'DELETE'
})
# return HttpResponse('{"status":"success"}', content_type='application/json')
return JsonResponse(response)
# return HttpResponse('{"status":"error: %s"}' % file_form.errors, content_type='application/json')
return JsonResponse({'response': file_form.errors, })
return super(MultiAttachmentMixin, self).post(request, *args, **kwargs)
示例6: upload
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def upload(request):
if request.method == 'POST':
response = {'files': []}
# Create a new entry in our database
new_image = Photo(image_field=request.FILES['image_field'])
# Save the image using the model's ImageField settings
new_image.save()
# Save output for return as JSON
response['files'].append({
'name': '%s' % new_image.id,
'size': '%d' % request.FILES.__sizeof__(),
'url': '%s' % new_image.image_field.url,
'thumbnailUrl': '%s' % new_image.image_field.url,
'deleteUrl': '\/image\/delete\/%s' % new_image.id,
"deleteType": 'DELETE'
})
print(response)
return JsonResponse(response)
form = PhotoUploadForm()
context = {
'form': form,
"class_name": form.__class__.__name__
}
return render(request, "photos/upload.html", context)
示例7: populate
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def populate(request):
for i in (1,2,3):
p = Photo(name="test image #%s" % i, original_image="apps/photos/tests/test%s.jpg" % i)
p.save()
return HttpResponseRedirect("/photos")
示例8: form_valid
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def form_valid(self, form):
photo_name = form.cleaned_data['image_path']
new_img = Photo(
image = photo_name,
image_thumb = photo_name,
name = photo_name,
description = form.cleaned_data['image_desc']
)
new_img.save()
return HttpResponseRedirect(reverse('photos:index'))
示例9: multi_upload
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def multi_upload(request, album_id):
if request.method == 'POST':
owner = request.user
print album_id
gallery = get_object_or_404(Gallery, id=album_id)
file = request.FILES[u'files[]']
error = False
#文件是否合法
if file.size > MAX_FILE_SIZE:
error = "maxFileSize"
if file.size < MIN_FILE_SIZE:
error = "minFileSize"
if file.content_type not in ACCEPTED_FORMATS:
error = "acceptFileTypes"
if request.session["is_allow_upload"] == 0:
error = "maxNumberOfFiles"
else:
request.session["is_allow_upload"] -= 1
response_data = {
"name": file.name,
"size": file.size,
"type": file.content_type,
}
if error:
response_data["error"] = error
response_data = simplejson.dumps([response_data])
return HttpResponse(response_data, mimetype=response_mimetype(request))
#保存文件
image = Photo(
title=file.name, description='description',
image=file, owner=owner, gallery=gallery,
)
image.save()
response_data["url"] = image.image.url
response_data['thumbnail_url'] = image.image['thumbnail'].url
print 'url:',image.image['thumbnail'].url
#删除链接
response_data["delete_url"] = "/photos/del/" + str(image.id)
response_data["delete_type"] = "GET"
response_data = simplejson.dumps({"files":[response_data]})
return HttpResponse(response_data, mimetype=response_mimetype(request))
else:
request.session["is_allow_upload"] = MAXNUMBEROFFILES
print request.session["is_allow_upload"]
return render_to_response('photos/multi_upload.html',{
"open_tv":u'{%',"close_tv": u'%}',"maxfilesize": MAX_FILE_SIZE,
"minfilesize": MIN_FILE_SIZE,"maxnumberoffiles":MAXNUMBEROFFILES,
}, context_instance=RequestContext(request)
)
示例10: create_photo_model
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def create_photo_model(self, name='testname', border_color="#FFFFFF",
created_at=None):
photo = Photo(
owner=self.user,
photo=self.create_image_file(),
name=name,
border_color=border_color,
)
photo.save()
if created_at is not None:
Photo.objects.filter(pk=photo.pk).update(created_at=created_at)
return photo
示例11: form_valid
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def form_valid(self, form):
# I load these uploaded files into django-filer objects.
files = Photo.objects.filter(temp_hash=self.request.POST.get('temp_hash'))
# folder = Folder.objects.get(name='Customer Service')
for f in files:
new_file = Photo(image=f)
# Save the image using the model's ImageField settings
new_file.save()
# Attach the new Filer files to the original form object.
self.object.attachments.add(new_file)
files.delete()
return super(MultiAttachmentMixin, self).form_valid(form)
示例12: save_latest_flickr_image
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def save_latest_flickr_image():
"""
We get the lastest image and save it to our Photo Model in the Database
"""
flickr_image = get_latest_flickr_image()
# lets make sure we don't save the same image more than once
# we are assuming each Flickr image has a unique Link
if not Photo.objects.filter(link=flickr_image['link']).exists():
photo = Photo(
title=flickr_image['title'],
link=flickr_image['link'],
image_url=flickr_image['media']['m'],
description=flickr_image['description']
)
photo.save()
示例13: handle
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def handle(self, *args, **options):
if not args:
raise CommandError("The <photo_target_dir> argument is required")
img_dir = os.path.join(settings.DJANGO_PROJECT_ROOT, args[0])
for fn in os.listdir(img_dir):
if re.match(r'.+\.(png|jpg|gif)', fn) is not None:
fp = os.path.join(img_dir, fn)
self.stdout.write('Loading the photo "%s" ...' % fn)
photo = Photo()
photo.photo = photo.get_photo_path(fn)
photo.photo.storage.save(photo.photo.name, File(open(fp)))
photo.save()
self.stdout.write('All photos loaded succesfully.')
示例14: save
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def save(self, commit=True, **kwargs):
instance = super(GrowingPlaceForm, self).save(commit=False, **kwargs)
instance.centroid = Point(self.cleaned_data['longitude'],
self.cleaned_data['latitude'])
# Intentionally ignoring commit keyword to save Photo
instance.save()
if self.cleaned_data['photo']:
photo = Photo(
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.pk,
original_image=self.cleaned_data['photo']
)
photo.save()
return instance
示例15: upload
# 需要导入模块: from photos.models import Photo [as 别名]
# 或者: from photos.models.Photo import save [as 别名]
def upload( request ):
# The assumption here is that jQuery File Upload
# has been configured to send files one at a time.
# If multiple files can be uploaded simulatenously,
# 'file' may be a list of files.
file = upload_receive( request )
instance = Photo( file = file )
instance.save()
basename = os.path.basename( instance.file.path )
file_dict = {
'name' : basename,
'size' : file.size,
'url': settings.MEDIA_URL + basename,
'thumbnailUrl': settings.MEDIA_URL + basename,
'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
'deleteType': 'POST',
}
return UploadResponse( request, file_dict )