Exemple #1
0
def form(request):
    if request.method == 'POST':
        file = File()
        file.user = request.user

        form = FileForm(request.POST, request.FILES, instance=file)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = FileForm()

    ctx = {
        'form': form,
        }

    return render_to_response('uploads/form.html', ctx)
def upload_file(request):
    form = FileForm(request.POST, request.FILES)
    if form.is_valid():
        image = form.cleaned_data['file']
        name, ext = os.path.splitext(image.name)
        name = slugify(name)

        today = datetime.date.today()
        target_name = 'uploads/%(year)d/%(month)d/%(name)s%(ext)s' % {
            'year': today.year,
            'month': today.month,
            'name': name,
            'ext': ext,
        }

        image_path = default_storage.save(target_name, image)
        url = default_storage.url(image_path)

        return JsonResponse({  # TODO: использовать JsonResponse
            'filelink': url,
            'filename': os.path.basename(image_path),
        })

    return HttpResponseForbidden()