本文整理汇总了Python中photos.models.Photo类的典型用法代码示例。如果您正苦于以下问题:Python Photo类的具体用法?Python Photo怎么用?Python Photo使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Photo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
def post(self, request):
"""
Crea una foto en base a la información POST
:param request: HttpRequest
:return: HttpResponse
"""
success_message = ''
photo_with_owner = Photo()
photo_with_owner.owner = request.user # asigno como propietario de la foto el usuario autenticado
form = PhotoForm(request.POST, instance=photo_with_owner)
if form.is_valid():
# Guarda el objeto del formulario en la DB y lo devuelve
new_photo = form.save()
# Inicializamos formulario, con el reverse componemos la url dinámica que mostrará con la nueva
# foto
form = PhotoForm()
success_message = 'Guardado con éxito!'
success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk]))
success_message += 'Ver foto'
success_message += '</a>'
context = {
# Pasamos en el context los datos que se mostrarán en el template
'form': form,
'success_message': success_message
}
return render(request, 'photos/new_photo.html', context)
示例2: upload
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)
示例3: post
def post(self, req):
"""
Muestra un form para crear una foto y la crea si la peticion es POST
:param req: HttpRequest
:return: HttpResponse
"""
error_messages = []
success_message = ""
# Creamos owner y se lo pasamos al form con un objeto pre-establecido
photo_with_owner = Photo()
photo_with_owner.owner = req.user
form = PhotoForm(req.POST, instance=photo_with_owner)
if form.is_valid():
new_photo = form.save()
form = PhotoForm()
success_message = "Foto guardada con éxito! "
success_message += '<a href="{0}">'.format(reverse("photos_detail", args=[new_photo.pk]))
success_message += "(ver foto)</a>"
else:
error_messages.append("Formulario incompleto.")
context = {"form": form, "success_message": success_message}
return render(req, "photos/new_photo.html", context)
示例4: index
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})
示例5: post
def post(self, request):
#Crea una instancia vacía de foto
photo_with_owner = Photo()
#Asigna los datos
photo_with_owner.owner = request.user
form = PhotoForm(request.POST, instance=photo_with_owner)
if form.is_valid():
new_photo = form.save() #Guarda el objeto que viene en el formulario y lo devuelve
#Poner todos los campos vacíos
form = PhotoForm()
success_message = 'Guardado con exito!'
#reverse sirve para generar la url
success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk]))
success_message += 'Ver Foto'
success_message += '</a>'
context = {
'form': form,
'success_message': success_message
}
return self.render(request, context)
示例6: get_default_photo
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
示例7: submit
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})
示例8: ghetto_fixtures
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)
示例9: post
def post(self, request):
"""
Muestra un formulario
:param request:
:return:
"""
sucess_message = []
# Es esto seguro? -> Que pasa si meto owner con POST
photo_with_owner = Photo()
photo_with_owner.owner = request.user
form = PhotoForm(request.POST, instance=photo_with_owner)
if form.is_valid():
photo = form.save() # Guarda el objeto y me lo devuelve
sucess_message = 'Guardado con éxito '
sucess_message += '<a href=\"{0}\">'.format(reverse('photos_detail', args=[photo.pk]))
sucess_message += 'Ver foto'
sucess_message += '</a>'
form = PhotoForm()
context = {
'form': form,
'sucess_message': sucess_message
}
return render(request, 'photos/new_photo.html', context)
示例10: post
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)
示例11: populate
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")
示例12: add_youtube_photo
def add_youtube_photo(client_upload_id, storage_id, author, album, now, youtube_id):
def get_next_album_index(album):
album_index_q = Photo.objects.filter(album=album).aggregate(Max("album_index"))
max_album_index = album_index_q["album_index__max"]
if max_album_index is None:
return 0
else:
return max_album_index + 1
success = False
while not success:
try:
with transaction.atomic():
next_album_index = get_next_album_index(album)
p, created = Photo.objects.get_or_create(
storage_id=storage_id,
defaults={
"photo_id": Photo.generate_photo_id(),
"media_type": Photo.MEDIA_TYPE_YOUTUBE,
"client_upload_id": client_upload_id,
"subdomain": Photo.choose_random_subdomain(),
"date_created": now,
"author": author,
"album": album,
"album_index": next_album_index,
"youtube_id": youtube_id,
},
)
except IntegrityError:
# This will happen if there is a collision with a duplicate
# 'album_index' from a concurrent request
success = False
else:
success = True
if created:
if not in_testing_mode():
# Update the photo servers:
for photo_server in PhotoServer.objects.filter(subdomain=p.subdomain, unreachable=False):
# TODO We should use concurrent requests for this
num_retries = 5
initial_retry_time = 4
try:
request_with_n_retries(
num_retries,
initial_retry_time,
lambda: photo_server_set_photos(photo_server.photos_update_url, photo_server.auth_key, [p]),
)
except requests.exceptions.RequestException:
# TODO Log this
photo_server.set_unreachable()
album.save_revision(now, True)
photos_added_to_album.send(sender=None, photos=[p.photo_id], by_user=author, to_album=album)
示例13: form_valid
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'))
示例14: multi_upload
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)
)
示例15: create_photo_model
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