ImproperlyConfigured at / - /static/ isn't a storage module - python

I am trying to upload a file.
this is my model.
def custom_path(instance, filename):
return '/'.join(['upload',instance.student.user.username,filename])
class Doc(models.Model):
uploadtime = models.DateTimeField(auto_now_add=True, blank=True)
datei = models.FileField(upload_to=custom_path,default='')
student = models.ForeignKey(Student,related_name='students_file')
title = models.TextField()
desc = models.TextField()
def __unicode__(self):
return self.title
and this is my views.py
def hochgeladen_danke(request):
if request.FILES.get('file'):
student = request.user.get_profile()
student.students_file.create(datei=request.FILES.get('file'),title='t',desc='t')
return render_to_response('upload.html',{},context_instance=RequestContext(request))
my html:
<form action="/hochgeladen_danke/" method="post" enctype="multipart/form-data">
{% csrf_token %}
File: <input type="file" name="file"/>
<button type="submit">upload</button>
</form>
my settings.py:
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"
STATIC_ROOT = os.path.join(PROJECT_PATH, "static")
STATIC_URL = '/static/'
when i try to upload a file. it is saying:
ImproperlyConfigured at /hochgeladen_danke/
/static/ isn't a storage module.
i dont know why this is happening. my custom_path seems to be right.
my urls.py:
..
url(r'^hochgeladen_danke/$','hochgeladen_danke',name='hochgeladen_danke'),
)
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns

Something is wrong with your settings.DEFAULT_FILE_STORAGE.
The exception you have provided comes from django.core.files.storage#272, which in turn comes from default_storage right below, and django.db.models.files#221. The constructor is called in your view, causing the exception to be thrown.

Related

I have problem with updating profile photo in Django

I am trying to update Profile photo with Django
According to yt tutorials I created form for updating photo:
class UserProfileForm(forms.ModelForm):
class Meta:
model = User_Model
fields = ["profile_photo"]
And this is my class to Change photo in views:
class UpdatePhoto(TemplateView):
template_name = "Messenger/update_photo.html"
profile_form = UserProfileForm
def post(self, response):
data = response.POST
file_data = response.FILES
profile_form = UserProfileForm(data, file_data, instance=response.user.profile)
if profile_form.is_valid():
profile_form.save()
return redirect("/")
print("rere")
context = self.get_context_data(profile_form=profile_form)
return self.render_to_response(context)
My Model:
class User_Model(models.Model):
user = models.OneToOneField(
User, null=True, on_delete=models.CASCADE, related_name="profile"
)
profile_photo = models.ImageField(
upload_to="images/", default="default_photo.jpg", null=True, blank=True
)
chats = models.ManyToManyField(User, related_name="chats", blank=True)
blocked_list = models.ManyToManyField(User, related_name="blocked_list", blank=True)
I was trying with and without 'response.POST', result was the same, it does not update. However when I try to print 'file_data' I get something like this:
<MultiValueDict: {'Browser': [<InMemoryUploadedFile: thumb.jpg (image/jpeg)>]}>
Main Settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
And main urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("Messenger.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
App urls:
from django.urls import path
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
path(
"",
login_required(views.Chat_list_Usernames.as_view(), login_url="/login"),
name="home",
),
path(
"change_status/",
login_required(views.change_status, login_url="/login"),
name="change_status",
),
path("login/", views.login_page, name="login_page"),
path(
"logout/", login_required(views.logout_user, login_url="/login"), name="logout"
),
path("register/", views.register_page, name="register_page"),
path(
"update_photo/",
login_required(views.UpdatePhoto.as_view(), login_url="/login"),
name="update_photo",
),
path(
"change_password/",
login_required(views.ChangePassword.as_view(), login_url="/login"),
name="change_password",
),
path(
"send_message/",
login_required(views.SendMessage.as_view(), login_url="/login"),
name="send_message",
),
]
And my template:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/update_photo.css'%}">
<div class="main-content">
<div class="heading">Change</div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="photo">
<div class="button">
<input id="files" required type="file" name="Browser"
accept="image/png, image/jpeg, image/jpg, image/webp">
</div>
<div class="buttons">
<div class="button">
<input type="button" name="Back" , value="Back">
</div>
<div class="button">
<input type="submit" name="Change" , value="Change">
</div>
</div>
</form>
</div>
Also I need to mention that I can update photo though admin panel but it's how this should work .
I Have no idea what have I done wrong and how to make it work right.
You should use UpdateView instead of TemplateView as it only renders a given template, with the context containing parameters captured in the URL.

Django Application Wont Load User Uploaded Image

I used Django Admin to upload an image and I am trying to get it to display in a template. The alt text is displayed but I keep getting a 404 error for the image and it does not display. When I uploaded the image the path that it pulls in the template media/images/mari-profile-pic.png is valid and contains the image I am trying to display.
models.py
from django.db import models
# Create your models here.
class Image(models.Model):
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Image
# Create your views here.
def index(request):
imageModel = Image.objects.get(pk=1)
return render(
request,
"SocialLinks/index.html",
{
"profile_pic_title":imageModel.title,
"profile_pic":imageModel.image
}
)
index.html template
<div id="profile">
<img id="userPhoto" src="{% get_media_prefix %}{{ profile_pic }}" alt="{{ profile_pic_title }}">
</div>
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I have tried removing and adding the {% get_media_prefix %} tag and the image still does not display.
settings.py:
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root')
your.html:
{% load static %}
To make the imgaes works add .url to be like this: {{ i.img.url }}, and go to the urls.py of the app, and add the following:
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)
Call the templates and the statics from the (PROJECTNAME/settings.py) by add the following in the TEMPLATES 'DIRS':
'DIRS': [os.path.join(BASE_DIR, 'temp')],

Image is not being accessed through port 8000(under development)

My image path is working but Idk why it's not able to display it, any help is appreciated
models.py
class movies(models.Model):
Image = models.ImageField(blank=True, null=True)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = 'media'
home.html
{% for m in movies %}
<img src="{{ m.Image.url }}" width="200px", height="300px">
{% endfor %}
class movies(models.Model):
Image = models.ImageField(upload_to='images/', blank=True, null=True)
So the problem was with the Media root, my path was fine but Django wasn't able to get it somehow, so I ran this code to automate Django to find media root by itself
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
and made a debug condition in the urls.py to run the request if viewed under development or localhost
if settings.DEBUG is True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Does not display an image! Django

Does not display an image!
image is exists, dut django didn't display any images on page, how to fix this?
this is my models.py
class All_Images_Of_The_Series(models.Model):
to_series = models.ForeignKey(Series, on_delete=models.CASCADE, blank=True, default=None)
image_of_all = models.ImageField(upload_to="previews/previews_for_series/", default=None,width_field="width_field", height_field="height_field")
is_poster = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "Active: |%s| and Poster: |%s| " % (self.is_active, self.is_poster)
class Meta:
ordering = ["-timestamp"]
verbose_name = 'All_Images_of_the_Series'
verbose_name_plural = 'All_Images_of_the_Series'
this is my views.py
def homeview(request, *args, **kwargs):
full_path = All_Images_Of_The_Series.objects.all()
context = {"full_path":full_path,}
return render(request, 'home.html', context)
this is my template
<div class="col-sm-3 right-side">
<div class="new-movies-block">
<a class="header" href="#/new/">
<div class="title">Новинки</div>
</a>
{% for one_to_one_path in full_path %}
<div class="movie-spacer" ></div>
<a class="new-movie" href="{{ one_to_one_path.to_series.get_absolute_url }}" title="{{ one_to_one_path.to_series.eng_name }}">
<div class="title-info">
{{ one_to_one_path.to_series.season_of_this_series.number_of_season }} сезон {{ one_to_one_path.to_series.number_of_series }} серия
</div>
<div class="date">{{ one_to_one_path.to_series.timestamp_rus }}</div>
<img src="{{ one_to_one_path.image_of_all.url }}" class="img-responsive">
</a>
{% endfor %}
</div>
</div>
If you look at the element code, the images, then in the line "src" there is a path to the picture, and it's working! But does not display the picture itself!
<img src="/media/previews/previews_for_series/1.png" class="img-responsive">
this is error in console(f12)
GET http://127.0.0.1:8000/media/previews/previews_for_series/1.png 404 (Not Found)
Do this !
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^series/', include("serials.urls", namespace='series')),
url(r'^', include("serials.urls", namespace='homeview')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
just a quick thoughts, you don't show me the things you might need to work. For example if this if for development on the urls you need this https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development and on your settings you may need something like that
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
I hope it helps
Best
Perhaps you haven't added the media to your urls.py
From django.conf import settings
# your stuff
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT
})
)

Django object.image.url not displaying even though path is correct

I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.

Categories