I
I
Ilya Pochepko2016-05-27 17:09:11
Django
Ilya Pochepko, 2016-05-27 17:09:11

SuspiciousFileOperation when uploading a file in Django, how to fix?

Traceback:

Exception Type: SuspiciousFileOperation at /upload/
Exception Value: The joined path (/media/code.cpp) is located outside of the base path component (/home/macheta/PycharmProjects/myproject/media)

settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

models.py:
from django.db import models

class Article(models.Model):
    file_obj = models.FileField(upload_to='/media/')

views.py:
from django.shortcuts import render
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect

from .forms import ArticleForm


def Upload_file(request):
  if request.method == 'POST':
    form = ArticleForm(request.POST, request.FILES)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect('/')
  else:
    form = ArticleForm()

  return render(request, 'file_upload.html', {'form': form})

forms.py:
from django.forms import ModelForm
from .models import Article

class ArticleForm(ModelForm):
  class Meta:
    model = Article
    fields = ['file_obj']

Django Version: 1.9.6
Python Version: 3.4.3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-05-27
@Chepapka

file_obj = models.FileField(upload_to='media/')
/media - absolute path

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question