Can not get images to be displayed in Django template - python

The title is pretty much self explanatory. I did put some images in the static/rakunai folder and added the dirs etc, the whole shebang. I still can't get to display it. I am using docker. Python 3.8 was used and the newest django version was used.
The settings.py:
```
"""
Django settings for rakunai project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'rakunai.urls'
STYLESHEETS='/stylesheets/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'rakunai.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = ['rakunai']
```
templates/aboutus.html:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--todo:fix this-->
<link rel="stylesheet" href="{% static 'styles.css' %}" type="text/css">
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<title>Index page</title>
...
<div class="row rowteams align-tems-center">
<div class="col-xs-12 col-sm-6 padding-0">
<img class="teamimages" src="{% static 'rakunai/img.jpg' %}">
</div>
<div class="col-sm-6 padding-0 skobeloff-bg linen-text">
<h2>
Simonas Bansevičius
</h2>
<h5>
CEO
</h5>
</div>
</div>
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def about(request):
return render(request, 'about.html')
def css(request):
return render(request, 'styles.css')
Urlpaterls:
from rakunai.views import index as home
from rakunai.views import about as details
from rakunai.views import css
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
path('about', details),
]
Any type of feedback is highly appreciated.

BASE_DIR = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'rakunai')]
MEDIA_URL = '/media/'
in settings.py
<img class="teamimages" src="/static/media/img.jpg" %}">
in html file
put images in rakunai/media/
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
add this in urls.py

You have not included the static urls and media urls in your urls.py.
Including them would look something like this:-
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from rakunai.views import index as home
from rakunai.views import about as details
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
path('about', details),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

No Django settings specified. Unknown command: 'createsuperuser' Type 'manage.py help' for usage

I am trying to create a superuser through createsuperuser command in manage.py console is throwing an error "No Django settings specified. Also tried in python console by runninf python manage.py createsuperuser
Unknown command: 'createsuperuser'
Type 'manage.py help' for usage."
I AM USING PYCHARM
settings.py
"""
Django settings for MovieFlix project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-#*8cdy*ul906(s4ei#g7h17)vv%)#0s5b##weupzn-&ct#ylez'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['192.168.2.12', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Core.apps.CoreConfig',
'movie.apps.MovieConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'MovieFlix.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'Core/templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'MovieFlix.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
# 'default': {
# 'ENGINE': 'djongo',
# 'NAME': 'MovieFlix',
# 'ENFORCE_SCHEMA': False,
# 'CLIENT': {
# 'host': 'mongodb+srv://movieflix:movieflix%401234#cluster0.fm15x.mongodb.net/MovieFlix?retryWrites=true&w=majority'
# }
# }
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MovieFlix.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
In views.py
# Create your views here
def create_super_user(request):
form = UserCreationForm()
context = {"form": form}
# When method is POST
if request.method == "POST":
# Populate form with data posted
form = UserCreationForm(request.POST)
if form.is_valid():
try:
user = form.save(commit=False)
# Make the user as superuser
user.is_superuser = 1
# Make the user as staff
user.is_staff = 1
# Save the user to db
user.save()
except IntegrityError:
return render(request, "register.djt", context)
# Login the user after registration
login(request, user)
return HttpResponseRedirect(reverse("home"))
# When form is not valid
return render(request, "register.djt", context)
# When method is not POST
return render(request, "app2/register.djt", context)
In urls.py
from django.urls import path
from .views import create_super_user
urlpatterns = [
path('register/', create_super_user, name="register"),
]
In register.djt
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create Super User</title>
</head>
<body>
<h2 class="text-center">Create Super User</h2>
<div class="container-fluid">
<form method="POST" action="" class="row g-1">
{% csrf_token %}
{{ form }}
<input type="submit" value="Register" class="btn btn-primary">
</form>
</div>
</body>
</html>
after having all of the above code then visit the url register/ to create a super user.

Page not found error on django when try to upload image

In my Django project, I am trying to register a student. When I submit the registration form on the live server I got a Page not found (404) error. But it working perfectly on my local server. I think I got this problem for upload image because when I try to submit another form without any image it saves on the database perfectly.
This is the exact error I got.
Page not found (404)
Request Method: POST
Request URL: https://xxxxx.com/accounts/registration/student/
Raised by: accounts.views.register_student
Using the URLconf defined in coaching.urls, Django tried these URL patterns, in this order:
ad/
accounts/
students/
teachers/
admin/
vedios/
[name='landingpage']
error [name='error_page']
^media\/(?P<path>.*)$
The current path, registration/student/, didn't match any of these.
This is the URL patterns related to this problem
from django.urls import path,include
from accounts import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('registration/student/', views.register_student, name='student_registration'),
path('registration/teacher/', views.register_teacher, name='teacher_registration'),
path('login/', views.login_view, name='login'),
path('logout/',views.logout_view,name="logout")
]
And this the view's method for that I got this error.
def register_student(request):
context={}
if request.POST:
form = RegistrationForm(request.POST,request.FILES)
if form.is_valid():
user = form.save(commit=False)
user.is_student = True
user.save()
# login(self.request, user)
return redirect('login')
else:
context['form'] = form
else:
form = RegistrationForm()
context['form'] = form
return render(request, 'accounts/student_register.html',context)
And finally, this is the RegistrationForm() method
class RegistrationForm(UserCreationForm):
"""docstring for ."""
image = forms.ImageField(label="Upload Your Image",widget = forms.FileInput(attrs={'class':'form-control','placeholder':"Your Image"}))
name = forms.CharField(label="Full Name",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Full Name'}))
email = forms.EmailField(label="Email Address",help_text="We'll never share your email with anyone else.", widget= forms.EmailInput(attrs={'class': 'form-control','aria-describedby':'emailHelp','placeholder':'Enter email'}))
phone_number = forms.CharField(label="Phone Number",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Phone Number'}))
address = forms.CharField(label="Current Address",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Current Address'}))
password1 = forms.CharField(label="Password",help_text="Don't share your password with others",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Enter Password'}))
password2 = forms.CharField(label="Confirm Password",help_text="",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Re-Enter Password'}))
class Meta:
"""docstring for ."""
model = get_user_model()
fields = ('image','name','email','phone_number','address','password1','password2')
This is the html form page I used
<form method="post" enctype="multipart/form-data" action="{%url 'student_registration' %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small id="{{field.id_for_label}}" class="form-text text-muted">{{ field.help_text|safe }}</small>
{% endif %}
</div>
{% endfor %}
<div class="text-center">
<input type="submit" class="btn btn-success" value="Register as student"><a class="btn btn-secondary ml-1" href="{% url 'teacher_registration' %}">Register as teacher</a>
</div>
</form>
This is my settings.py file if you need this.
"""
Django settings for coaching project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'og3h%0!(#zaxic7ap%o5)#pc8%-2a4(+wq0n!8it^0dssbst+('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['xxx.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'mainadmin',
'student',
'teacher',
'accounts',
'vedios',
'classlinks',
'frontend',
'notices',
'notification'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'coaching.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'coaching.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'accejakr_coaching',
'USER': 'accejakr_coaching',
'PASSWORD': 'a3w~$Zk%H_TP',
'HOST': 'localhost',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'accounts.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = 'media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
This is the global URLs patterns of my project
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('ad/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('students/', include('student.urls')),
path('teachers/', include('teacher.urls')),
path('admin/', include('mainadmin.urls')),
# path('class/', include('classlinks.urls')),
path('vedios/', include('vedios.urls')),
path('', include('frontend.urls')),
# path('notifications/', include('notify.urls', 'notifications')),
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT)
The problem is in the settings.py.
You have to change this code
MEDIA_URL = 'media/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
to this code
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
This should work OK now.

Cannot save an image to database using django

I project is supposed to be able to upload an image with a name then display the uploaded image and name. I have tried looking online for an answer to my problem but have found none. The problem basically is my django webapp is not saving a name(CharField)an and image(ImageField) to the database. I tried to do everything necessary for it to work but it's still not working. The following is my project. Thanks for your time.
My projectl directories:
Image shows project structure
views.py
from django.shortcuts import render
from ImgApp.forms import ImageForm
from ImgApp.models import ImageModel
from django.http import HttpResponseRedirect
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
con = {"var_form": form}
return render(request, 'upload.html', con)
models.py
from django.db import models
class ImageModel(models.Model):
name = models.CharField(max_length=44)
image = models.ImageField(upload_to='media/',null=True)
def __str__(self):
return self.name
forms.py
from django import forms
from ImgApp.models import ImageModel
class ImageForm(forms.ModelForm):
class Meta:
model = ImageModel
fields = "__all__"
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e3d)3&+&3!xkh_zz_l#uc9ly8uh#wio1g+zh59_mt&v-0xyubp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'ImgApp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'ImgProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'ImgProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = "/media/"
INTERNAL_IPS = ['127.0.0.1']
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from ImgApp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^app/',include('ImgApp.urls')),
url(r'^$',views.home),
url(r'^upload/$',views.upload),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
upload.html
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:index' %}">
{% csrf_token %}
{{var_form.as_p}}
<input type="submit" value="upload" class="btn btn-primary">
</form>
index.html
<!DOCTYPE html>
{% load static %}
........
{% if var_db %}
{% for img in var_db %}
<b>Name:</b>{{img.name}}
<br>
<img src="{{MEDIA_URL}}/{{img.image}}" alt="Image here" height="200" width="300">
{% endfor %}
{% else %}
<p>No Images uploaded yet</p>
<p>Fill this lonely area with happiness</p>
{% endif %}
It looks as if you are posting the form to the index. You should post it to the upload view.
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:upload' %}">
You need to add a name to the URL pattern for this to work.
url(r'^upload/$',views.upload, name='upload'),
In your view, you need to move the context line out of the else block so that it runs for GET and POST request. That means that if the form is invalid, you'll see the errors on the template.
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
context = {"form": form}
return render(request, 'upload.html', context)
I've renamed a couple of variables to match the usual Django style (con to context, var_form to form). If you rename var_form, remember to update your template as well.

Not properly render image from Django model

I am making a simple app(Django version 1.11+python3.5+). I want to show images on my homepage(web app) from Django models. I can upload successfully from Django admin panel. But image cant renders properly. The image does not show in the homepage. This is my HTML file.
{% extends "shop/base.html" %}
{% block content_area %}
{% for name in products %}
<div class="col-lg-3 col-md-3">
<div class="main_content_sidebar">
<div class="content_title">
<h2>{{name.product_name}}</h2>
</div>
<div class="image_space">
<img src="{{name.product_image.url}}" class="img-thumbnail" alt="">
</div>
<div class="content_p">
<p>Retail Price:{{name.product_retail_price}}</p>
<p>Quantity: {{name.product_quantity}}</p>
<p>Date: {{name.product_sell_date}}</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
this is mysite(project)>>urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^shop/',include('shop.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is my models.py file.
class ProductsName(models.Model):
product_name=models.CharField('name', max_length=50)
product_retail_price=models.IntegerField('retail price TAKA')
product_quantity = models.IntegerField('quantity')
product_sell_date=models.DateTimeField('buy date', auto_now_add=True)
product_image = models.ImageField(upload_to='upload/', blank=True, null=True)
def __str__(self):
return self.product_name
setting.py file
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'shop/images/')
MEDIA_URL = '/media/'
When I visit my homepage, I can't see any image. But I see image link If I open my browser dev tools.
chrome dev tool
if I click that image link from chrome dev tool. I got andjango doesn/t found that image url error.
Also my folder structure is:
mysite
shop
manage.py
path_to
db.sqlite3
The issue is that the your MEDIA_ROOT is not being served and Django cannot append the correct url. In your project urls.py add the following at the end:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in the setttings.py add the correct paths for:
MEDIA_ROOT = os.path.join(BASE_DIR,'path_to_/media_folder')
MEDIA_URL = '/media/'

Django | joined path is located outside of the base path component {% static img.thumbnail.url %}, Error 400 with whitenoise

I've finish my first app in Django and works perfectly, but still have pre-deployment problems since I set DEGUG=False ...
Here is just to display an image in a template... T_T
I was using this, but now it does'nt work when I use whitenoise to serve my image localy... And it return a Bad Request(400) error...
Models.py
class GalleryItem(models.Model):
thumbnail = models.ImageField(blank=True,upload_to='gallery/thumb')
img_wide = models.ImageField(blank=True,upload_to='gallery')
template.py
{% load staticfiles %}
{% for img in img_to_display %}
<a href="{{ img.img_wide.url}}" class="swipebox" title="">
<img src="{% static img.thumbnail.url %}" alt="{{ img.alt}}">
</a>
{% endfor %}
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
import os
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^gallery/', include('gallery.urls')),
url(r'^shop/', include('shop.urls')),
url(r'^events/', include('events.urls')),
url(r'^page/', include('paginator.urls')),
url(r'^news/', include('blog.urls')),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print("BASE_DIR = ",BASE_DIR)
MEDIA_ROOT = os.path.join(BASE_DIR, 'wt/static/media/')
MEDIA_URL = '/media/'
SECRET_KEY = 'SECRET_KEY'
DEBUG = False
INSTALLED_APPS = [
'ckeditor',
'ckeditor_uploader',
'team.apps.TeamConfig',
'gallery.apps.GalleryConfig',
'shop.apps.ShopConfig',
'events.apps.EventsConfig',
'blog.apps.BlogConfig',
'paginator.apps.paginatorConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'wt.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.request",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = 'wt.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'wt_db',
'USER': 'postgres',
'PASSWORD': 'PASSWORD',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'fr-fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
ALLOWED_HOSTS = ['localhost', '127.0.0.1',]
STATIC_ROOT = os.path.join(BASE_DIR, 'wt/staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'wt/static'),
os.path.join(BASE_DIR, 'wt/staticfiles'),
]
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
CKEDITOR_UPLOAD_PATH = 'uploads'
CKEDITOR_IMAGE_BACKEND = 'pillow'
CKEDITOR_BROWSE_SHOW_DIRS = True
Here my error log :
The joined path (E:\media\gallery\thumb\lost-thumb.jpg) is located outside of the base path component (E:\dev\wt\wt\wt\staticfiles)
[15/May/2016 20:01:41] "GET /page/gallery HTTP/1.1" 400 26
Thanks a lot for helping ! :)
EDIT :
principal structure
project folder
Bro, you cant load staticfile when you use images on models, there is 2 different ways to work with images in django.
Statics files is for files that are static(images files like logo of your company, banners, javascript files, css files)
Media Files is for dinamic files like user photo, user gallery, product images
Static Files - This way you use your staticfiles save at your static folder where you place it in static root at your settings.py and then you use {% load staticfiles %} and {% static '' %}
Media Files - This files is that one you save with your models, ImageField, FileField and etc... that one you do not load as static, cuz they are not a static file (you can edit it from your models), that do not means you will save it on your database, this will generate a copy of your file with hashed name on it at you media folder where you place it in media root at your settings.py and media files you use like that {{ ..url }} so in your case gallery.thumbnail.url (btw, remind to call your gallery object at your views and send it to template to allow your to use it)
So the other anwers was right, you need to decide what you want to use, keep in mind that your path localy is different where you deploy, remember to use environment variables with the right path to set up in your settings
Django Docs: https://docs.djangoproject.com/en/1.11/topics/files/
I guess it was a security issue. Even if "whitenoise" is good to serve true static files in production, it can't serve media files.
I was making a structure error :
# Don't place your 'media' files IN your 'static' file like this :
MEDIA_ROOT = os.path.join(BASE_DIR, 'wt/static/media/')
MEDIA_ROOT never have to be in the "static" file of your project (even if you can make it works in some ways, it's not a good practice I think).
'MEDIA' files (in production), have to serve out of the Django project. I've read somewhere that we have to use a CDN. And firstly I choose CloudFlare (because it's free), but it wasn't working, cause you need a subdomain/hostname to point your MEDIA_ROOT, and Cloudflare doesn't give that. Finally, I choose Amazon S3.
So, in conclusion, write something like {% static img.thumbnail.url %} makes no sense. Because everything uploaded via admin/user haven't to be in "static".
Use {{ img.thumbnail.url }} instead.
paste the below code in settings.py file
STATIC_URL = '/static/'
# 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, 'media/')
MEDIA_URL = "/media/"
and 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)
Try <img src="{{ img.thumbnail.image.url }}" alt="{{ img.alt}}">

Categories

Resources