I get an error regarding Media directory on Django.
forms.py
from django.forms import ModelForm
from .models import Mots
from django import forms
class CreeMot(ModelForm):
mot = forms.CharField(max_length=50)
level = forms.IntegerField(max_value=10)
image = forms.FileField()
class Meta:
model = Mots
fields = ["mot", "level", "image"]
views.py
def cree_mot(request):
if request.method == "POST":
form = CreeMot(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = CreeMot()
return render(request, "cp/cree_mot.html", {'form': form})
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# Add these new lines
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
When the form is submitted I get this error:
[Errno 30] Read-only file system: '/media'
Actually my /media/ directory is at the same level of /static/:
cp
/views.py
/forms.py
main_app
/settings.py
/...
media
static
manage.py
I put my /media/ in 777 chmod.
You should erase and leave just basics staff to understand what is going on in your app. In your case firstly, remove
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
and leave just path to your path to media like :
MEDIA_ROOT = 'path/to/media'
Hope it will help for you
Related
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description.
I wonder why when I set up my media files
So I make my news in this view:
class NewsCreate(views.CreateView):
template_name = 'web/create_news.html'
model = News
fields = ('title', 'image', 'description')
success_url = reverse_lazy('home')
Here is the model:
class News(models.Model):
TITLE_MAX_LENGTH = 30
title = models.CharField(
max_length=TITLE_MAX_LENGTH
)
image = models.ImageField(
upload_to='news/',
blank=True
)
description = models.TextField()
Here is the set-up in settings.py:
MEDIA_ROOT = BASE_DIR / 'mediafiles'
MEDIA_URL = '/media/'
Here is the urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('University_Faculty.web.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one
This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder
You need to correct
MEDIA_ROOT = BASE_DIR / 'media'
Hope this will work for you.
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I'm trying to upload a file (any file) to my rest framework.
At the current time, I'm able to upload the file but unable to click on the generated link for some reason.
This is my settings.py:
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "site_static")]
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
This is my model.py:
...
class FileUpload(models.Model):
created = models.DateTimeField(auto_now_add=True)
user_profile = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
datafile = models.FileField(blank=False, null=False)
This is my views.py:
...
class FileUploadViewSet(viewsets.ModelViewSet):
"""Handles uploading a file"""
authentication_classes = (TokenAuthentication,)
serializer_class = (serializers.FileUploadSerializer)
queryset = models.FileUpload.objects.all()
parser_classes = (MultiPartParser, FormParser,)
permission_classes = (
permissions.UpdateOwnStatus,
IsAuthenticated
)
def perform_create(self, serializer):
"""Sets the user profile"""
serializer.save(user_profile=self.request.user,
datafile=self.request.data.get('datafile'))
This is my serializer.py:
...
class FileUploadSerializer(serializers.HyperlinkedModelSerializer):
user_profile = serializers.SlugRelatedField(
read_only=True,
slug_field='id'
)
class Meta:
model = models.FileUpload
fields = ('id', 'user_profile', 'created', 'datafile')
extra_kwargs = {'user_profile': {'read_only': True},
'created': {'read_only': True}}
This is my complete urls.py:
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, basename='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('feed', views.UserProfileFeedViewSet)
router.register('upload', views.FileUploadViewSet)
urlpatterns = [
path('hello-view/', views.HelloApiView.as_view()),
path('login/', views.UserLoginApiView.as_view()),
path('', include(router.urls)),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When I upload a file, the datafile field becomes populated with the file location, such as:
{
"id": 2,
"user_profile": 4,
"created": "2020-04-27T21:08:16.269058Z",
"datafile": "http://127.0.0.1:8000/media/test.png"
},
I look at the project files and I can find the file at /media/, however, the link does not work.
How can I make the link work.
quoted from the docs here
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My problem, as it turns out, is that I was editing the wrong urls.py.
Both the api folder and the project folder has urls.py.
When adding that urlpattern to the correct project urls.py, it works fine!
I have a django-admin panel and a Windows Virtual Private Server.
What i want to do is upload files from django admin panel to a directory like this :
C:\site\media
and i dont want to upload files to django app folder .
This is my settings.py file :
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT)
and This is my model :
class Pictures(models.Model):
product = models.ForeignKey('Products', models.DO_NOTHING)
picurl = models.ImageField()
def __unicode__(self):
return self.title
class Meta:
managed = False
db_table = 'pictures'
verbose_name_plural = "ProductPicturess"
def __str__(self):
return '%s------- (%s)' % (self.product.title,self.picurl)
How should i change it's values ?
Thank you .
After Searching alot and triying different values finally i found the solutin .
Simply I changed MEDIA_ROOT to this :
MEDIA_ROOT = os.path.join(BASE_DIR, '../../../realwamp/wamp64/www/myproject/pictures/')
And volla , My Problem is solved .
With three pairs of dots like ../../../ I back to the C:\ directory and then go to my www folder .
I have a form with a ImageField() in it I've already set the media URL and directory and such in setting.py and url.py and on submit everything works perfectly, but suddenly now every time I try submit my form it fails and says in python terminal :
[17/Feb/2018 14:40:08] "POST /form/ HTTP/1.1" 200 37885
Not Found: /media/
I didn't modify either setting.py or the url.py (see code below):
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
url.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
model.py
class Model_A(models.Model):
name = models.CharField(max_length=200, verbose_name="Name (as in NRIC)")
def upload_photo_dir(self, filename):
path = 'hiring/employees/photo/{}'.format(filename)
return path
photo = models.ImageField(upload_to=upload_photo_dir)
view.py
def application_form_view(request):
form = Model_AForm(request.POST or None, request.FILES or None)
if form.is_valid():
inst = form.save(commit=False)
inst.save()
context = {'form': form}
return render(request, 'form.html', context=context)
html
<form method="POST" enctype="multipart/form-data" id="application_form" name="application_form">
<label>name :</label>
{{ form.name}}
<label>Photo:</label>
{{ form.photo }}
</form>
Change below constants in Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
Ensure that DEBUG is True if you running on port and not at server. Keep False at web server (nginix,apache etc).
Verify below statements in urls.py
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
As you have mentioned hiring/employees/photo/ path in your model file field this must be present in your root folder.
`hiring/employees/photo/` #Must be created at root of your project with permissions of 755.
And yes as denis said, media folder is also need to be there at root. with this path.
FIXED
This was my solution, in the main programs urls.py I had to add these lines.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have an model called Item within there I have an image field. I added an new item with an image to the database and tried loading it inside of my index template. However I dont get an image when I look at the console it says ("WEBSITENAME/site_media/items/image.jpg 404 (Not Found)")
I think the problem lies within the settings.py file but I cant figure out what exactly I did wrong here.
index.html template
{% load static %}
<div class="item" style="background-image: url('{{ item.img.url }}')">`
Model.py
class Item(models.Model):
name = models.CharField(max_length=200)
img = models.ImageField(upload_to='items', default='', blank=True, null=True)
def __str__(self):
return "%s" % (self.name)
Views.py
def index(request):
latestItems = Item.objects.all().order_by('-id')[:3][::-1]
return render(request, 'webshop/index.html', {'latestItems' :latestItems})
settings.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'site_media/')
MEDIA_URL = 'site_media/'
In your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
and read this document
With the directory root structure that you have shown, I think the above setting should work. Have not tested it though. Let me know if it works.
you have:
upload_to='items'
but:
{{ item.img.url }}
should that be?
{{ items.img.url }}
in settings.py:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__ file __))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, "static"),
)