Not properly render image from Django model - python

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/'

Related

Django 1.10 or later: base.html override not working

I am creating a site in Django with a custom view, and want to link to that view on the admin page. But even though I've followed the directions to override in Documentation or Youtube, but i won't show the changes in the overide file.
{% extends "admin/base.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name">Test</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
My base.html in ratonix\templates\admin
Map tree:
└─ratonix
----└── ratonix
----------└── settings.py
----------└── views.py
----------└── urls.py
--- └── templates
-----------└── admin
- ------------ └── base.html
└── manage.py
Templates folder in the same folder as manage.py
This is my current settings.py:
"""
Django settings for ratonix project.
Generated by 'django-admin startproject' using Django 4.0.6.
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 pymysql
import os
pymysql.install_as_MySQLdb()
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-SECRET SORRY!'
# 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',
'ratonix',
]
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 = 'ratonix.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',
],
},
},
]
WSGI_APPLICATION = 'ratonix.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ratonix_db',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
# 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/
STATICFILES_DIRS = (os.path.join(BASE_DIR, '/xampp/htdocs/ratonix/ratonix/static/'), )
STATIC_URL = 'static/'
MEDIA_URL = '/images/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
I've restarted the server, as well as used different browsers, and none of my changes show up.
Am I doing something wrong anywhere, or are the instructions given by the tutorial just plain incorrect?
The order of INSTALLED_APPS affects the override order.
If you have templates/admin/base.html in the ratonix app, then ratonix must come before django.contrib.admin in INSTALLED_APPS for that template to be used.
Since you also have DIRS in your TEMPLATES configuration, you could also use <PROJECT>/templates/admin/base.html, and that would be used; per the documentation,
If you have app and project templates directories that both contain overrides, the default Django template loader will try to load the template from the project-level directory first. In other words, DIRS is searched before APP_DIRS.
Note the preferred customization point for the admin is admin/base_site.html.

Python-Django-Heroku not able to locate images in heroku, images not visible

so I recently deployed my django/python website (that used sqllite as a database) to heroku which hosts websites for free, everything is functioning normally like when I used to run localhost in my browser, except that this project is using postgressql database with heroku and images aren't appearing on my website, I looked everywhere and I think it has to do with the uploads file in the database(the path of the image is still the same but the location of the image changed).
local host image link: "http://localhost:8000/image/download/uploads/products/white_shirt_MERETfT.jpg"
heroku image link: "https://supremelebanon.herokuapp.com/image/download/uploads/products/offwhite_shirt_tQWa19c.jpg"
it says image not found for when I load the website on heroku hosting.
Please anyone I'm still a newbie with heroku I dont really know how it works, if anyone can help it would be much appreciated, thanks in advance.
settings.py file:
import os
from pathlib import Path
import django_heroku
# 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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'morrr7ht4t4m)j#%ws34ntr7mdq$pui)+uy2-#%tx^iznh_##6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['supremelebanon.herokuapp.com', 'localhost', '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',
'store',
]
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',
# 'store.middlewares.auth.auth_middleware'
]
ROOT_URLCONF = 'supremelebanon.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 = 'supremelebanon.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/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, 'static')
MEDIA_URL = "/image/download/"
MEDIA_ROOT = BASE_DIR
# Activate Django-Heroku.
django_heroku.settings(locals())
image part in index.html:
{% extends 'base.html' %}
{% block content %}
{% load cart %}
{% load custom_filter %}
{{customer}}
{% if request.session.customer %}
<!-- body -->
<div class="container-fluid mt-3">
<div class="row">
<!--filter-->
<div class="col-lg-3 mx-auto">
<div class="list-group">
All Products <!-- GOTTA DO A DROPDOWN -->
{% for category in categories %}
{{category.name}}
{% endfor %}
</div>
</div>
<!-- all products -->
<div id='products' class="col-lg-9 mx-auto">
<div class="row mx-auto">
{% for product in products %}
<div class="card mx-auto mb-3" id="{{product.id}}" style="width: 18rem;">
<img class="card-img-top" src="{{product.image.url}}" alt="Card image cap">
you can try this settings.py, before to test you can compare with your code and see the diferences
import os
from pathlib import Path
import django_heroku
# 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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'morrr7ht4t4m)j#%ws34ntr7mdq$pui)+uy2-#%tx^iznh_##6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['supremelebanon.herokuapp.com', 'localhost', '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',
'store',
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
# 'store.middlewares.auth.auth_middleware'
]
ROOT_URLCONF = 'supremelebanon.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 = 'supremelebanon.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
try:
from projectname.local_settings.py import DATABASES
except:
import dj_database_url
import dotenv
DATABASES = {}
DATABASES['default'] = dj_database_url.config()
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
SECURE_SSL_REDIRECT = True # [1]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Password validation
# https://docs.djangoproject.com/en/3.1/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/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, 'static')
MEDIA_URL = "/image/download/"
MEDIA_ROOT = BASE_DIR
# Activate Django-Heroku.
#django_heroku.settings(locals())
and for your local_settings.py is:
import os
from projectname.settings import BASE_DIR
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
A brief explanation
We have to add the whitenoise that allows you to serve files in production, and also if you notice, heroku uses postgres as a DB in production, so it is better to use that for production.

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.

How to display images uploaded from django admin to heroku?

I deployed my django project on heroku. The site is all working well except for the fact that some images are broken. These images are all images which I uploaded to my site in local server via the django admin. These images were uploaded to my site on local server by providing the url in image field in django admin page. All the images which are hard coded in the html code and are static/images folder in my project are displayed. Any changes I should make to my settings.py file to dipslay these pictures? How to resolve this?
My settings.py file
"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 2.2.
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!
SECRET_KEY = 'gm1zyhprh9=9+4#vu*^8g30(pg*xq6e#0z1)h81hc2evd7n*^v'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['market-shaurya.herokuapp.com', '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',
'django_filters',
'store.apps.StoreConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'ecommerce.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 = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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/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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_URL='/images/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'static/images')
my store.html templates file
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<img class="thumbnail" src="{{product.imageURL}}">
<div class="middle">
<div class="text"><strong><strong>{{product.description}}</strong></strong></div>
</div>
<div class="box-element product">
<h6><strong>{{product.name}}</strong></h6>
<hr>
<button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float: right"><strong>₹{{product.price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
notice this src="{{product.imageURL}}. This is how I uploaded pictures to this cart.
DEBUG = True
This solves the problem.

After logging in (in my Django app) I get the 403 error

When I run my Django application (via python manage.py runserver) I get the login screen, however when I try to login it redirect me to the page that says:
Forbidden (403)
CSRF verification failed. Request aborted.
Here is my settings.py
"""
Django settings for my_app project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/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 = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cooking_book'
]
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 = 'my_app.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.static',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'my_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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/2.1/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.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/2.1/howto/static-files/
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
There are questions similar to mine here on stackoverflow but unfortunately the answers are not helpful to me...
Additional notes on what I tried:
I am allowing cookies in my browser.
My view functions pass a request to the template's render method.
In the template I am adding {% csrf_token %} inside each POST form.
I also tried setting the CSRF_COOKIE_DOMAIN = None and CSRF_COOKIE_SECURE = False but it made no difference.
It would be great if anyone could help me with this, I am really stuck...
EDIT:
If you give me thumbs down, can you please just let me know what I did wrong? I am new here, still adapting... and if this is too easy for you and that is the reason for the thumbs down, please leave an answer I will appreciate it. Thank you!
2nd EDIT: Adding the relevant parts of the template and views.py file, where the csrf token is used. It is also worth mentioning that when the user logs in he/she is supposed to go to the homepage (that contains no POST forms and consequently no csrf tokens), and chose where to go next.
views.py (relevant part)
#login_required(login_url='/login/')
def dining(request):
#request is POST when user filters the city
if request.method == 'POST':
filter_city = FilterCityForm(request.POST)
if filter_city.is_valid():
filter_city = filter_city.save(commit=False)
city = str(filter_city.name)
#...
# here I'm doing some calculations and querying depending on the chosen city
#...
filter_city = FilterCityForm(initial={'name':city})
else:
filter_city = FilterCityForm(initial={'name':'Toronto'})
return render(request, 'dining.html', {'filter_city':filter_city})
dining.html (relevant part):
<div name='dropdown'>
<form action="" method="POST">
{% csrf_token %}
City: {% for widget in filter_city %}
{% if widget.errors %}
{% for error in widget.errors %}
<span style="color: red">{{ error }}</span><br>
{% endfor %}
{% endif %}
{{ widget }}
{% endfor %}
<input type="submit" value="OK">
</form>
<br>
</div>

Categories

Resources