Exemple #1
0
def photo_add(request, album_id):
    album = Album.objects.get(pk=album_id)
    user = request.user
    context = {}

    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():

            title = form.cleaned_data['title']
            description = form.cleaned_data['description']
            img = form.cleaned_data['img']
            photo = Photo.objects.create(
                owner=user,
                album=album,
                title=title,
                description=description,
                img=img,
            )
            return redirect('photo:album_detail', album_id=album.id)
        else:
            context['form'] = form
    else:
        form = PhotoForm()
        context['form'] = form
    return render(request, 'photo/photo_add.html', context)
Exemple #2
0
def upload(request, event_id, template='event/photo/upload_form.html'):
    event = get_object_or_404(Event.visible_objects,
            Q(artist__user_profile__user=request.user) |
            Q(creator__user=request.user),
            pk=event_id)
    user = request.user
    event_url = event.get_absolute_url()
    photo_url = reverse('list_event_photos', kwargs={'event_id':event.pk})
    if request.POST:
        form = PhotoForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            photo = form.save(content_object=event)
            _log.info('Photo uploaded: (%s) %s', photo.pk, photo.title)
            special_mesg = _('''<a href="%s">New photos</a> have been added to one of <a href="%s">your shows.</a>''' % (photo_url, event_url))
            event.notify_attendees(special_mesg, exclude=[user.pk])
            if 'Another' in request.POST.get('submit', 'Add'):
                user.message_set.create(message=_("%s Photo uploaded. You can add another photo below.") % photo.image_preview('square_thumbnail'))
                return HttpResponseRedirect(reverse('upload_event_photo', kwargs={'event_id':event.pk}))
            else:
                user.message_set.create(message=_("Photo uploaded."))
                return HttpResponseRedirect(event_url)
    else:
        form = PhotoForm()
    ctx = {'event':event, 'form':form, 'allow_another':True}
    return render_view(request, template, ctx)
Exemple #3
0
def filmPage(request,film_id):
    movie = Movie.objects.get(id=film_id)
    photoform = PhotoForm()
    if request.POST:
        if "photoform" in request.POST:
            photoform = PhotoForm(request.POST)
            if photoform.is_valid():
                photo = photoform.save()
                movie.photos.add(photo)

    return render_to_response('movies/films/viewFilm.html',context_instance=RequestContext(request,{"film":movie,
                                                                                                    "photoform":photoform}))
Exemple #4
0
def add_new_photo(request):
    user = request.user
    photo_form = PhotoForm(request.POST)
    if not photo_form.is_valid():
        return JsonResponse({'code': False, 'msg': "相册名非法"})

    try:
        photo_name = photo_form.cleaned_data['new_photo']
        Photo.objects.create(user_id=user.id, photo_name=photo_name)

        return JsonResponse({'code': True, 'msg': "新增相册成功"})
    except Exception as e:
        print(e)
Exemple #5
0
def updatePhoto(request, photoID):
    template = 'photo/updatePhoto.html'
    try:
        photo = Photo.objects.get(id=photoID)
    except Photo.DoesNotExist:
        return album(request, '')
    if request.method=='GET':
        form = PhotoForm(instance=photo)
        return render(request, template, {'form':form, 'photo':photo})
    # request.method=='POST'
    form = PhotoForm(request.POST, instance=photo)
    if not form.is_valid():
        return render(request, template, {'form':form, 'photo':photo})
    form.save()
    return redirect(reverse('photo:album', args=(photo.album.id,)))
Exemple #6
0
    def add_view(self, request, form_url='', extra_context=None):
        if (request.method == "POST"):
            form = PhotoForm(request.POST, request.FILES)
            photos = request.FILES.getlist('photo')
            if form.is_valid():
                project = form.cleaned_data['project']
                for p in photos:
                    photo_instance = Photo.objects.create(project=project,
                                                          photo=p)

            return redirect('admin:photo_photo_changelist')

        return super().add_view(request,
                                form_url=form_url,
                                extra_context=extra_context)
Exemple #7
0
def profile(request):
    user = request.user
    form = UserUpdateForm(instance = user) 
    photoForm = PhotoForm()
    image = None if not Photo.objects.filter(users_id = request.user.id) else Photo.objects.filter(users_id = request.user.id)[0]
    # image = Photo.objects.get(users_id = request.user.id)
    return render(request,'profile/profile.html',{'user_update_form':form, 'photo_form':photoForm, 'image':image})
Exemple #8
0
def album_detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    photos = album.photo_set.order_by('-created_date')
    form = PhotoForm()

    id_list = [photo.id for photo in photos]

    like_list = PhotoLike.objects.\
                    filter(user=request.user).filter(photo__in=id_list)
    like_ids = [like.photo.id for like in like_list]
    for photo in photos:
        if photo.id in like_ids:
            photo.like = True

    like_list = PhotoDislike.objects.\
                    filter(user=request.user).filter(photo__in=id_list)
    like_ids = [like.photo.id for like in like_list]
    for photo in photos:
        if photo.id in like_ids:
            photo.dislike = True

    context = {
        'album': album,
        'photos': photos,
        'form': form,
    }

    return render(request, 'photo/album_detail.html', context)
Exemple #9
0
def albumPage(request, album_id):
    album = Album.objects.get(id=album_id)
    photoform = PhotoForm()
    if request.POST:
        if "photoform" in request.POST:
            photoform = PhotoForm(request.POST)
            if photoform.is_valid():
                photo = photoform.save()
                album.photos.add(photo)
        elif "commentform" in request.POST:
            comment = request.POST["body"]
            index = album.comments.count()
            post = Post.objects.create(text=comment, poster=request.user, index=index)
            album.comments.add(post)
            album.save()
    page = request.GET["page"] if request.GET.get("page") else 1
    if request.GET.get("post"):
        post = album.comments.get(id=request.GET.get("post"))
        page = post.index / 10 + 1
    p = Paginator(album.comments.all(), 10)
    showpages = 9
    startpage = 0
    stoppage = p.num_pages
    if stoppage > showpages:
        startpage = int(page) - round(showpages / 2) - 1
        if startpage <= 0:
            startpage = 0
        elif startpage >= p.num_pages - showpages:
            startpage = p.num_pages - showpages
        stoppage = startpage + showpages
    pages = map(lambda x: p.page(x), p.page_range)
    showPages = dict(enumerate(pages[int(startpage) : int(stoppage)]))
    posts = p.page(page)
    return render_to_response(
        "music/albums/viewAlbum.html",
        {
            "album": album,
            "photoForm": photoform,
            "pages": pages,
            "posts": posts,
            "showPages": showPages,
            "startPage": startpage,
            "stopPage": stoppage,
        },
        context_instance=RequestContext(request),
    )
Exemple #10
0
def photo_add(request, password_hash):
    if password_hash == ADMIN_HASH:
        form = PhotoForm(request.POST or None, request.FILES or None)

        if form.is_valid():
            photo = form.save(commit=False)
            photo.slug = slugify(form.cleaned_data['titre'])
            photo.save()

            return redirect(admin, password_hash)

        return render(request, 'photo_add.html', {
            'form': form,
            'password_hash': password_hash
        })
    else:
        raise Http404
Exemple #11
0
def addPhoto(request, albumID):
    template = 'photo/addPhoto.html'
    try:
        photoAlbum = Album.objects.get(id=albumID)
    except Album.DoesNotExist:
        return album(request, albumID)
    context = {'album':photoAlbum}
    if request.method=='GET':
        context['form'] = PhotoForm()
        return render(request, template, context)
    form = PhotoForm(request.POST)
    context['form'] = form
    if not form.is_valid():
        return render(request, template, context)
    photo = form.save(commit=False)
    photo.album = photoAlbum
    photo.save()
    return redirect(reverse('photo:album', args=(albumID, )))
Exemple #12
0
def photo_save(request: HttpRequest, auction_id: int):
    if not request.user.is_authenticated:
        return JsonResponse({'result': 0, 'msg': 'Вы не авторизованы'})
    try:
        auction = Auction.objects.get(pk=auction_id)
    except Auction.DoesNotExist:
        return JsonResponse({'result': 0, 'msg': 'Аукцион не существует'})
    if auction.user.id != request.user.id:
        return JsonResponse({'result': 0, 'msg': 'Ошибка загрузки файла'})

    photo = Photo(auction_id=auction_id)
    form = PhotoForm(request.POST, request.FILES, instance=photo)
    if form.is_valid():
        try:
            form.save()
        except IntegrityError:
            return JsonResponse({'result': 0, 'msg': 'Ошибка загрузки файла'})
    else:
        return JsonResponse({'result': 0, 'msg': 'Ошибка загрузки файла'})
    request.session['open_gallery_tab'] = True
    return JsonResponse({'result': 1})
Exemple #13
0
def photo_edit(request, id, password_hash):
    if password_hash == ADMIN_HASH:
        photo = get_object_or_404(Photo, id=id)
        form = PhotoForm(request.POST or None,
                         request.FILES or None,
                         instance=photo)

        if form.is_valid():
            photo = form.save(commit=False)
            photo.slug = slugify(form.cleaned_data['titre'])
            photo.save()

            return redirect(admin, password_hash)

        return render(request, 'photo_edit.html', {
            'form': form,
            'photo': photo,
            'password_hash': password_hash
        })
    else:
        raise Http404
Exemple #14
0
def artistPage(request, artist_id):
    artist = Artist.objects.annotate(
        torrent__count=Count("album__releases__torrents")).annotate(
            snatches=Sum("album__releases__torrents__downloaded")).annotate(
                seeders=Sum("album__releases__torrents__seeders")).annotate(
                    leechers=Sum("album__releases__torrents__leechers")).get(
                        id=artist_id)
    albums = dict()
    photoform = PhotoForm()
    if request.POST:
        photoform = PhotoForm(request.POST)
        if photoform.is_valid():
            photo = photoform.save()
            artist.photo.add(photo)
    for release_type in RELEASE_TYPE:
        catAlbums = Album.objects.filter(
            releaseType=release_type[0],
            artists=artist,
        ).order_by("-released")
        albums[release_type[1]] = catAlbums
    return render_to_response('music/artists/viewArtist.html',
                              context_instance=RequestContext(
                                  request, {
                                      "artist": artist,
                                      "albums": albums,
                                      "photoForm": photoform
                                  }))
Exemple #15
0
def upload(request, event_id, template='event/photo/upload_form.html'):
    event = get_object_or_404(Event.visible_objects,
                              Q(artist__user_profile__user=request.user)
                              | Q(creator__user=request.user),
                              pk=event_id)
    user = request.user
    event_url = event.get_absolute_url()
    photo_url = reverse('list_event_photos', kwargs={'event_id': event.pk})
    if request.POST:
        form = PhotoForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            photo = form.save(content_object=event)
            _log.info('Photo uploaded: (%s) %s', photo.pk, photo.title)
            special_mesg = _(
                '''<a href="%s">New photos</a> have been added to one of <a href="%s">your shows.</a>'''
                % (photo_url, event_url))
            event.notify_attendees(special_mesg, exclude=[user.pk])
            if 'Another' in request.POST.get('submit', 'Add'):
                user.message_set.create(message=_(
                    "%s Photo uploaded. You can add another photo below.") %
                                        photo.image_preview('square_thumbnail')
                                        )
                return HttpResponseRedirect(
                    reverse('upload_event_photo',
                            kwargs={'event_id': event.pk}))
            else:
                user.message_set.create(message=_("Photo uploaded."))
                return HttpResponseRedirect(event_url)
    else:
        form = PhotoForm()
    ctx = {'event': event, 'form': form, 'allow_another': True}
    return render_view(request, template, ctx)
Exemple #16
0
def artistPage(request, artist_id):
    artist = (
        Artist.objects.annotate(torrent__count=Count("album__releases__torrents"))
        .annotate(snatches=Sum("album__releases__torrents__downloaded"))
        .annotate(seeders=Sum("album__releases__torrents__seeders"))
        .annotate(leechers=Sum("album__releases__torrents__leechers"))
        .get(id=artist_id)
    )
    albums = dict()
    photoform = PhotoForm()
    if request.POST:
        photoform = PhotoForm(request.POST)
        if photoform.is_valid():
            photo = photoform.save()
            artist.photo.add(photo)
    for release_type in RELEASE_TYPE:
        catAlbums = Album.objects.filter(releaseType=release_type[0], artists=artist).order_by("-released")
        albums[release_type[1]] = catAlbums
    return render_to_response(
        "music/artists/viewArtist.html",
        context_instance=RequestContext(request, {"artist": artist, "albums": albums, "photoForm": photoform}),
    )
Exemple #17
0
def add_photo(request):
    if request.POST:
        form = PhotoForm(request.POST, request.FILES or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.photo_user = auth.get_user(request)
            form.save()
    return redirect('/photos/%s/' % (auth.get_user(request).id))
Exemple #18
0
    def post(self, request):
        form = PhotoForm(request.POST, request.FILES)
        instance_list = []
        if form.is_valid():
            # 检验成功,都为图片类型
            uploader = request.user.username
            img_files = request.FILES.getlist("img")
            # 因为不是Model, 没有save方法, 要手动遍历保存为实例
            for index, img_file in enumerate(img_files, 1):
                # 因为模型里自定义了路径, 所以这里直接保存实例就可以了
                album = form.cleaned_data.get("album")
                name = ''.join(
                    reversed(list(''.join(reversed(list(
                        img_file.name)))[:30])))
                photo = models.Photo(name=name,
                                     img=img_file,
                                     album=album,
                                     uploader=uploader)
                photo.save()
                instance_list.append(photo)
        else:
            # 检验不成功, 即有非图片文件
            pass

        # 3个一组, 根据组数组装二维数组
        group_nums = len(instance_list) // 3 if len(
            instance_list) % 3 == 0 else len(instance_list) // 3 + 1
        ret_list = [[] for _ in range(group_nums)]
        # 开始分组
        for i, instance in enumerate(instance_list, start=0):
            ret_list[i // 3].append(instance)

        context = {
            "form": form,
            "instance_list": instance_list,
            "ret_list": ret_list
        }
        return render(request, "photo/photo_upload.html", context=context)
Exemple #19
0
def uploadPhoto(request):
    result = False

    token = request.POST['Token']
    title = request.POST['title']
    content = request.POST['content']

    photoForm = PhotoForm(request.POST)

    if not tokenCheck(token):
        return HttpResponse('Unauthorized', status=401)

    if photoForm.is_valid():
        photo_obj = photoForm.save(commit=False)
        photo_obj.save()

        print("Post - Photo upload request : Upload success")
        result = True

    else:
        print("Post - Photo upload request : Upload error")

    return HttpResponse(result)
Exemple #20
0
def upload(request, campaign_id, template='campaign/photo/upload_form.html'):
    campaign = get_object_or_404(Campaign.visible_objects, pk=campaign_id, artist__user_profile__user=request.user)
    user = request.user
    campaign_url = campaign.get_absolute_url()
    photo_url = reverse('list_campaign_photos', kwargs={'campaign_id':campaign.pk})
    if request.POST:
        form = PhotoForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.content_object = campaign
            photo.save()
            _log.info('Photo uploaded: (%s) %s', photo.pk, photo.title)
            special_mesg = _('''<a href="%s">New photos</a> have been added to one of <a href="%s">your campaigns.</a>''' % (photo_url, campaign_url))
            campaign.notify_contributors(special_mesg, exclude=[user.pk])
            if 'Another' in request.POST.get('submit', 'Add'):
                request.user.message_set.create(message=_("%s Photo uploaded. You can add another photo below.") % photo.image_preview('square_thumbnail'))
                return HttpResponseRedirect(reverse('upload_campaign_photo', kwargs={'campaign_id':campaign.pk}))
            else:
                request.user.message_set.create(message=_("Photo uploaded."))
                return HttpResponseRedirect(reverse('view_campaign', kwargs={'campaign_id':campaign.pk}))
    else:
        form = PhotoForm()
    ctx = {'campaign':campaign, 'form':form}
    return render_view(request, template, ctx)
Exemple #21
0
def photo_view(request):
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.poster = request.user
            post.save()
            # return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            return redirect(reverse('homepage'))
    else:
        form = PhotoForm()
        photo = Photo.objects.all().filter(poster=request.user)
    return render(request, 'photo.html', {'form': form, 'photo': photo})
Exemple #22
0
def upload(request):
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save()
            photo.generate_and_save_preview()

            return HttpResponseRedirect('/')

    else:
        form = PhotoForm()

    return render(request, 'photo/upload.html', {
        'form': form,
    })
Exemple #23
0
def filmPage(request, film_id):
    movie = Movie.objects.get(id=film_id)
    photoform = PhotoForm()
    if request.POST:
        if "photoform" in request.POST:
            photoform = PhotoForm(request.POST)
            if photoform.is_valid():
                photo = photoform.save()
                movie.photos.add(photo)

    return render_to_response('movies/films/viewFilm.html',
                              context_instance=RequestContext(
                                  request, {
                                      "film": movie,
                                      "photoform": photoform
                                  }))
Exemple #24
0
def albumPage(request, album_id):
    album = Album.objects.get(id=album_id)
    photoform = PhotoForm()
    if request.POST:
        if "photoform" in request.POST:
            photoform = PhotoForm(request.POST)
            if photoform.is_valid():
                photo = photoform.save()
                album.photos.add(photo)
        elif "commentform" in request.POST:
            comment = request.POST['body']
            index = album.comments.count()
            post = Post.objects.create(text=comment,
                                       poster=request.user,
                                       index=index)
            album.comments.add(post)
            album.save()
    page = request.GET['page'] if request.GET.get('page') else 1
    if request.GET.get('post'):
        post = album.comments.get(id=request.GET.get('post'))
        page = post.index / 10 + 1
    p = Paginator(album.comments.all(), 10)
    showpages = 9
    startpage = 0
    stoppage = p.num_pages
    if stoppage > showpages:
        startpage = int(page) - round(showpages / 2) - 1
        if startpage <= 0:
            startpage = 0
        elif startpage >= p.num_pages - showpages:
            startpage = p.num_pages - showpages
        stoppage = startpage + showpages
    pages = map(lambda x: p.page(x), p.page_range)
    showPages = dict(enumerate(pages[int(startpage):int(stoppage)]))
    posts = p.page(page)
    return render_to_response('music/albums/viewAlbum.html', {
        "album": album,
        "photoForm": photoform,
        "pages": pages,
        "posts": posts,
        "showPages": showPages,
        "startPage": startpage,
        "stopPage": stoppage
    },
                              context_instance=RequestContext(request))
Exemple #25
0
def photoCreate(request):
    if not request.user.is_authenticated():
        context = {'form': AuthenticationForm}
        return render(request, 'registration/login.html', context)
    else:
        if request.method == "POST":
            form = PhotoForm(request.POST, request.FILES)
            if form.is_valid():
                photo = form.save(commit=False)
                photo.owner = request.user
                photo.title = form.instance.title
                photo.description = form.instance.description
                photo.image_content = form.instance.image_content
                photo.image_style = form.instance.image_style
                result_url = ""
                photo.save()
                z = photo.image_content.path.split('/')[:-2]
                z.extend([
                    'result_img',
                    photo.image_content.url.split('/')[-1].split('.')[0] +
                    photo.image_style.url.split('/')[-1]
                ])
                result_url_1 = "/" + "/".join(z[-2:])
                temp = photo.image_content.path.split('/')[:-2]
                result_url = "/".join(temp) + result_url_1
                Photo.objects.filter(id=photo.id).update(result_url=result_url)
                t = StyleTransfer(photo.image_content.path[:],
                                  photo.image_style.path[:],
                                  Photo.objects.get(id=photo.id).result_url[:])
                t.transfer()
                #queue.append(StyleTransfer(photo.image_content.path[:], photo.image_style.path[:], Photo.objects.get(id = photo.id).result_url[:]))
                return HttpResponseRedirect(reverse('photo:photo_Mylist'))
        else:
            form = PhotoForm()
        context = {'form': form}
        return render(request, 'photo/photo_form.html', context)
Exemple #26
0
 def get(self, request):
     context = {"form": PhotoForm()}
     return render(request, "photo/photo_upload.html", context=context)