SuspiciousFileOperation when the file is loaded 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
July 9th 19 at 11:02
1 answer
July 9th 19 at 11:04
Solution
file_obj = models.FileField(upload_to='media/')

/media - absolute path
So typos are forced to write on a Toaster) Thank you! - Paige.Macejkovic commented on July 9th 19 at 11:07

Find more questions by tags DjangoHTMLPyCharmPythonWeb Development