Image from database is not displayed in django template - django

I am trying to store images in database via form ImageField of model which gets uploaded to media folder that i have created and render the same in template.
This is my folder structure-
folder structure
This is my settings.py file-
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9q5awt($2rn+iwvku6p!r59st5a#g^%oqcc16=*v9s&-q_7=+n'
# 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',
'bootstrap3',
'userAuth',
'groups',
'posts',
]
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': [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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'
LOGIN_REDIRECT_URL = "/loggedin"
LOGOUT_REDIRECT_URL = "/loggedout"
This is my post app's urls.py file. Just to inform, I have 3 apps namely posts,groups,userAuth.
from django.conf.urls import url
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name='posts'
urlpatterns = [
url(r"^$", views.PostList.as_view(), name="all"),
url(r"new/in/(?P<pk>\d+)/$", views.CreatePost.as_view(), name="create1"),
url(r"comment/in/(?P<pk>\d+)/$", views.CreateComment.as_view(), name="create2"),
url(r"by/(?P<username>[-\w]+)/$",views.UserPosts.as_view(),name="for_user"),
url(r"by/(?P<username>[-\w]+)/(?P<pk>\d+)/$",views.PostDetail.as_view(),name="single"),
url(r"comment/delete/(?P<pk>\d+)/$",views.DeleteComment.as_view(),name="delete_comment"),
url(r"delete/(?P<pk>\d+)/$",views.DeletePost.as_view(),name="delete"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is post_detail.html, the template in which i am trying to render images(line 8) -
{% extends "posts/post_base.html" %}
{% block content %}
<div class="col-md-8">
<div class="post media ">
<div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px;font-size: large;">{{ post.question }}</h3></div>
<div class="post media list-group-item" style="margin-top: 9px;"><h3 class="title list-group-item-heading" style="color: black !important; margin-bottom: 10px !important; font-size: medium;">{{ post.description_html|safe }}</h3></div>
///line 8 <img src="{{MEDIA_URL}}/pics/{{ post.picture }}" class="img-responsive" style="width: 100%; float: left; margin-right: 10px;" alt="heyy"/>
<div class="media-body">
<h5 class="media-heading" style="margin-top: 7px;">
<span class="username">#{{ post.user.username }}</span>
<time class="time">{{ post.created_at }}</time>
</h5>
the uploading part works perfectly as i got pics/download.jpg on printing {{ post.picture }} on the template instead of line 8
This is my models.py of posts app-
from django.conf import settings
from django.urls import reverse
from django.db import models
import misaka
from groups.models import Group
from django.contrib.auth import get_user_model
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
question = models.CharField(max_length=255)
# question_html = models.TextField(editable=False)
description=models.TextField(blank=True, default='')
description_html = models.TextField(editable=False)
picture=models.ImageField(upload_to='pics',blank=True)
group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE,)
def __str__(self):
return self.question
def save(self, *args, **kwargs):
self.question_html = misaka.html(self.question)
self.description_html = misaka.html(self.description)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
"posts:single",
kwargs={
"username": self.user.username,
"pk": self.pk
}
)
class Meta:
ordering = ["-created_at"]
unique_together = ["user", "question"]
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
comment = models.TextField()
text_html = models.TextField(editable=False)
user = models.ForeignKey(User, related_name="comments",on_delete=models.CASCADE)
def save(self, *args, **kwargs):
self.text_html = misaka.html(self.comment)
super().save(*args, **kwargs)
def get_absolute_url(self):
# return reverse("posts:single" , kwargs={"slug": self.slug})
return reverse("posts:single" , kwargs={"username":self.post.user.username,"pk":self.post.pk})
def __str__(self):
return self.text
forms.py of posts app-
from django import forms
from posts import models
class PostForm(forms.ModelForm):
class Meta:
# fields = ("message", "group")
fields = ('question','description','picture')
model = models.Post
class CommentForm(forms.ModelForm):
class Meta:
# fields = ("message", "group")
fields = ('comment',)
model = models.Comment
This is m webpage on rendering, also for reference i opened the elements on inspecting which shows different url -
webpage
I am getting the broken image and alt text instead of actual image.

Related

super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'label'

I tried a multi-select-field project in Django. Based on my knowledge everything is correct. But, try to make migrations it shows TypeError. How to fix it?
Error
File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 4, in <module>
class EnquiryForm(forms.Form):
File "D:\My Django Projects\multiselectproject\multiselectapp\forms.py", line 30, in EnquiryForm
course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\multiselectfield\db\fields.py", line 70, in __init__
super(MultiSelectField, self).__init__(*args, **kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 986, in __init__
super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'label'
settings.py
"""
Django settings for multiselectproject 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/
"""
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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n&*##g^b-%-$-yd1^!iwzhfnttd4s^zf+&$*5!i0_ves1v8s4&'
# 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',
'multiselectapp.apps.MultiselectappConfig',
]
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 = 'multiselectproject.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 = 'multiselectproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'multiselectdb',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root',
}
}
# 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/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
models.py
from django.db import models
from multiselectfield import MultiSelectField
# Create your models here.
class EnquiryData(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
mobile = models.IntegerField()
Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
course = MultiSelectField(max_length=200, choices='Courses_Choices')
Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
locations = MultiSelectField(max_length=200, choices='Locations_Choices')
Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
trainers = MultiSelectField(max_length=200, choices='Trainers_Choices')
gender = models.CharField(max_length=20)
start_date = models.DateField(max_length=50)
forms.py
from django import forms
from multiselectfield import MultiSelectField
class EnquiryForm(forms.Form):
name = forms.CharField( label = 'Enter your name:', widget = forms.TextInput(
attrs = {
'class':'form-control',
'placeholder':'Your name'
}
)
)
email = forms.EmailField( label = 'Enter your email:', widget = forms.EmailInput(
attrs = {
'class':'form-control',
'placeholder':'Your email'
}
)
)
mobile = forms.IntegerField( label = 'Enter your contact number:', widget = forms.NumberInput(
attrs = {
'class':'form-control',
'placeholder':'Your contact number'
}
)
)
Courses_Choices = (('Python', 'Python'), ('Django', 'Django'), ('Flask', 'Flask'), ('Rest API', 'Rest API'), ('UI', 'UI'))
course = MultiSelectField(label='Select Required Courses:', choices='Courses_Choices')
Locations_Choices = (('Hyd', 'Hyderabad'), ('Bang', 'Banglore'), ('Che', 'Chennai'), ('Mum', 'Mumbai'))
locations = MultiSelectField(label='Select Required Locations', choices='Locations_Choices')
Trainers_Choices = (('Govardhan', 'Govardhan'), ('Manikanta', 'Manikanta'), ('Kartheek', 'Kartheek'))
trainers = MultiSelectField(label='Select Required Trainers', choices='Trainers_Choices')
Gender_Choices = (('Male', 'Male'), ('Female', 'Female'))
gender = forms.ChoiceField(widget=forms.RadioSelect, choices='Gender_Choices', label='Select your gender')
start_date = forms.DateField(widget=forms.SelectDateWidget(), label='Select your timings')
views.py
from django.shortcuts import render
from .models import EnquiryData
from .forms import EnquiryForm
# Create your views here.
def enquiry_view(request):
if request.method == 'POST':
pass
else:
form = EnquiryForm()
context = {'form':form}
return render(request, 'enquiry.html', context)
enquiry.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="container">
<div class="row">
<div class="offset-md-3 col-md-6">
<form>
{% csrf_token %}
{{ form }}
<input type="submit" name="submit" value="Save">
<input type="reset" name="reset" value="Cancel">
</form>
</div>
</div>
</div>
</body>
</html>
urls.py-multiselectapp
from django.urls import path
from multiselectapp import views
urlpatterns = [
path('', views.enquiry_view, name=''),
]
urls.py
"""multiselectproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('multiselectapp.urls')),
]
For a form field, you use the MultiSelectFormField, not a MultiSelectField:
from django import forms
from multiselectfield.forms.fields import MultiSelectFormField
class EnquiryForm(forms.Form):
# …
Courses_Choices = (
('Python', 'Python')
, ('Django', 'Django')
, ('Flask', 'Flask')
, ('Rest API', 'Rest API')
, ('UI', 'UI')
)
course = MultiSelectFormField(label='Select Required Courses:', choices='Courses_Choices')
Locations_Choices = (
('Hyd', 'Hyderabad')
, ('Bang', 'Banglore')
, ('Che', 'Chennai')
, ('Mum', 'Mumbai')
)
locations = MultiSelectFormField(label='Select Required Locations', choices='Locations_Choices')
Trainers_Choices = (
('Govardhan', 'Govardhan')
, ('Manikanta', 'Manikanta')
, ('Kartheek', 'Kartheek')
)
trainers = MultiSelectFormField(label='Select Required Trainers', choices='Trainers_Choices')
That being said, if you work with a ModelForm, Django can already do most of the work for you.

Django: TypeError: 'ModelSignal' object is not callable

I have a piece of code throwing an error:
TypeError: 'ModelSignal' object is not callable.
While I'm gonna add signals in my project, this error is occuring.
Why this type of error is occured? What you need to know to give my answer?
Please help me someone. I'm a newbie to Django. Thanks in advance.
Here is my views.py file:
def registerPage(request):
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
user =form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account successfully created for ' + username)
return redirect ('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
My models.py file:
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.name)
My signals.py file:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save(student_profile, sender= User)
My apps.py file:
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'accounts'
def ready(self):
import accounts.signals
And my settings.py file:
from pathlib import Path
import os
# 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 = '1dcgsc#63l$2w_%+90xqra#z=&(q!8sdxf*dg7k6=ptxi&k8o*'
# 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',
'accounts.apps.AccountsConfig',
'django_filters',
]
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 = 'cmp.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 = 'cmp.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 = 'Asia/Dhaka'
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/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
You are calling the post_save object which is not callable. Try post_save.connect().
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from .models import Student
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
)
post_save.connect(student_profile, sender= User)
Or you can also try using receiver decorator:
from django.db.models.signals import post_save
from django.contrib.auth.models import Group, User
from django.dispatch import receiver
from .models import Student
#receiver(post_save, sender=User)
def student_profile(sender, instance, created, **kwargs):
if created:
group = Group.objects.get(name = 'Student')
instance.groups.add(group)
Student.objects.create(
user = instance,
name = instance.username
).save()

How to Encrypt the data of djanog.ckeditor Richtextfield?

Hi There actually i am creating a notes taking app using django. For better ux i have used django ckeditor for providing a good editor to write beautiful and informative notes. I have used django.ckeditor richtextfield for this purpose. Now i want to encrypt the data of this text field so it can be stored safefly. I have used djanog-cryptography package and used encrypt method.
Problem -: When i am retreiving the note_contents in my template its showing nothing.
I am attaching my views and models and settings.py
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . models import UserCreatedNote
from . forms import AddNoteForm
# Create your views here.
#login_required
def notes(request):
if request.method=='POST':
form = AddNoteForm(request.POST)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
form_data.save()
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
notes = UserCreatedNote.objects.filter(user=request.user)
form = AddNoteForm()
context = {'notes': notes,'add_note_form':form}
return render(request,'usernotes.html',context)
#login_required
def edit(request,id):
note = get_object_or_404(UserCreatedNote, pk=id)
if request.method == 'POST':
form = AddNoteForm(request.POST, instance=note)
if form.is_valid():
form_data = form.save(commit=False)
form_data.user = request.user
print(form_data.id)
form_data.save()
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
form = AddNoteForm(instance=note)
context={'note':note,'u_form':form}
return render(request,'edit_note.html',context)
#login_required
def delete(request,id):
note = UserCreatedNote(id=id,user=request.user)
note.delete()
return redirect('/user/notes/')
settings.py
"""
Django settings for keepsafe project.
Generated by 'django-admin startproject' using Django 3.1.3.
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
import django_heroku
import dj_database_url
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG')
SECRET_KEY = config('SECRET_KEY')
# 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!
# SECURITY WARNING: don't run with debug turned on in production!
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ALLOWED_HOSTS = ['*']
AUTH_USER_MODEL = "useraccounts.keepsafeusermodel"
AUTHENTICATION_BACKENDS = (
'useraccounts.backends.CaseInsensitiveModelBackend',
)
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'crispy_forms',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'useraccounts.apps.UseraccountsConfig',
'notes.apps.NotesConfig',
'django_cleanup.apps.CleanupConfig',
'ckeditor',
]
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 = 'keepsafe.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['notes/templates/notes','useraccounts/templates/useraccounts','keepsafe/templates/keepsafe'],
'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 = 'keepsafe.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '',
'USER':'',
'PASSWORD':'',
'HOST':''
}
}
# 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 = 'Asia/Calcutta'
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/'
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/'
CRISPY_TEMPLATE_PACK = "bootstrap4"
LOGIN_REDIRECT_URL = 'user_profile'
LOGIN_URL = 'user_login'
if not DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST ='smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = ''
CKEDITOR_CONFIGS = {
'default': {
# 'toolbar': None, You can change this based on your requirements.
'width': 'auto',
},
}
# CRYPTOGRAPHY_BACKEND = 'cryptography.hazmat.backends.default_backend()'
# CRYPTOGRAPHY_DIGEST = 'cryptography.hazmat.primitives.hashes.SHA256'
# CRYPTOGRAPHY_KEY = None
# CRYPTOGRAPHY_SALT = 'django-cryptography'
# SIGNING_BACKEND = 'django_cryptography.core.signing.TimestampSigner'
django_heroku.settings(locals())
https://django-cryptography.readthedocs.io/en/latest/settings.html
when i use this in my settings it throws an error that 'str has no object digest_size' something.
Models.py
from django.db import models
from django.contrib.auth import get_user_model
from ckeditor.fields import RichTextField
from django_cryptography.fields import encrypt
# Create your models here.
class UserCreatedNote(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
note_title = models.CharField(default='',max_length=100,blank=True,null=True)
note_tags = encrypt(models.CharField(default='',max_length=20,blank=True,null=True))
note_contents = RichTextField(default='',max_length=1000,blank=True,null=True)
creation_time = models.DateTimeField(auto_now_add=True)
last_modified_time = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-creation_time',]
def __str__(self):
return str(self.user)
class UserQueries(models.Model):
email = models.TextField(default="",primary_key=True,max_length=80)
name = models.CharField(default="",max_length=80)
subject = models.CharField(default="",max_length=100)
message= models.CharField(default="",max_length=5000)
def __str__(self):
return self.name

Not able see the image after uploading on admin panel

I am learning django but i am stuck at Imagefield. I am trying to rename the file and save the image to my media directory where exactly i am going wrong i am not able to understand. It was working fine till worked with filefield. after changing the filefield to imagefield i am getting an page not found.
Not Found: /media/products/926045120/926045120.jpg
above is the error
from django.db import models
import random
import os
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
# print(instance)
#print(filename)
new_filename = random.randint(1,3910209312)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
return "products/{new_filename}/{final_filename}".format(
new_filename=new_filename,
final_filename=final_filename
)
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
model.py of product
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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z45+z23#cgk-fem6x&6i9_n#tz8p3)f^l+f1#8$e^n7(hv&dgz'
# 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',
'products',
]
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 = 'ecommerce.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 = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/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/3.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/3.0/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.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_my_proj"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")
products/views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
# Create your views here.
from .models import Product
class ProductListView(ListView):
queryset = Product.objects.all()
template_name = "products/list.html"
# def get_context_data(self, *args, **kwargs):
# context = super(ProductListView, self).get_context_data(*args, **kwargs)
# print(context)
# return context
def product_list_view(request):
queryset = Product.objects.all()
context = {
'object_list': queryset
}
return render(request, "products/list.html", context)
class ProductDetailView(DetailView):
queryset = Product.objects.all()
template_name = "products/detail.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
#context['abc'] = 123
return context
def product_detail_view(request, pk=None, *args, **kwargs):
#instance = Product.objects.get(pk=pk)
instance = get_object_or_404(Product, pk=pk)
context = {
'object': instance
}
return render(request, "products/detail.html", context)
details.html
{{ object.title }}<br/>
{{ object.description }}<br/>
<img src="{{ object.image.url }}" class="img-fluid"/>
I am able see my images in media directory but it is not able view on page

How to render image in my Django Blog Template?

Hi Guys I have a blog setup and I want to add the ability for an image or thumbnail to be included in every blog post. I'm having trouble getting the location of the file and the blog template to match up and show the image. I'm also having difficulties integrating the ImageWithThumbnail model to the Entry model.
post.html
{% include 'head.html' %}
{% include 'navbar.html' %}
{% load staticfiles %}
{% load django_markdown %}
<div class="container">
<div class="post">
<h2>{{ object.title }}</h2>
<p class="meta">
{{ object.created }} |
Tagged under {{ object.tags.all|join:", " }} <p> Created by
{{ object.author }} </p>
</p>
{{ object.body|markdown }}
<img src="{% static "{{ STATIC_ROOT }}/media/tableau_public.jpg" %}" alt="My image"/>
{{ object.file }}
</div>
{% include 'footer.html' %}
Settings.py
"""
Django settings for vizualytic project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#ic_*)dw$fxp+p_c=3e=91ujzivxurqf7y7572z9&sfs19aek%'
# 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',
'django_markdown',
'website',
'blog',
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'vizualytic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(BASE_DIR), "static", "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 = 'vizualytic.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
view.py
from django.views import generic
from . import models
class BlogIndex(generic.ListView):
queryset = models.Entry.objects.published()
template_name = "blog.html"
paginate_by = 3
class BlogDetail(generic.DetailView):
model = models.Entry
template_name = "post.html"
models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
class Tag(models.Model):
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Entry(models.Model):
title = models.CharField(max_length=200)
name = models.CharField(max_length = 255)
file = models.ImageField()
thumbnail = models.ImageField(upload_to=settings.MEDIA_ROOT+"/%Y/%m/%d",max_length=500,blank=True,null=True)
author = models.CharField(max_length=200, null=True)
body = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def filename(self):
return os.path.basename(self.file.name)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
class ImageWithThumbnail(models.Model):
name = models.CharField(max_length = 255)
image = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
thumbnail = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
def create_thumbnail(self):
# original code for this method came from
# http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/
# If there is no image associated with this.
# do not create thumbnail
if not self.image:
return
from PIL import Image
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
import os
# Set our max thumbnail size in a tuple (max width, max height)
THUMBNAIL_SIZE = (200,200)
DJANGO_TYPE = self.image.file.content_type
if DJANGO_TYPE == 'image/jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpg'
elif DJANGO_TYPE == 'image/png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
# Open original photo which we want to thumbnail using PIL's Image
image = Image.open(StringIO(self.image.read()))
# Convert to RGB if necessary
# Thanks to Limodou on DjangoSnippets.org
# http://www.djangosnippets.org/snippets/20/
#
# I commented this part since it messes up my png files
#
#if image.mode not in ('L', 'RGB'):
# image = image.convert('RGB')
# We use our PIL Image object to create the thumbnail, which already
# has a thumbnail() convenience method that contrains proportions.
# Additionally, we use Image.ANTIALIAS to make the image look better.
# Without antialiasing the image pattern artifacts may result.
image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
# Save the thumbnail
temp_handle = StringIO()
image.save(temp_handle, PIL_TYPE)
temp_handle.seek(0)
# Save image to a SimpleUploadedFile which can be saved into
# ImageField
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
temp_handle.read(), content_type=DJANGO_TYPE)
# Save SimpleUploadedFile into image field
self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)
def save(self):
# create a thumbnail
self.create_thumbnail()
super(ImageWithThumbnail, self).save()
Any help would be greatly appreciated.
Thanks
you just need:
<img src="{{ object.thumbnail.url }}" alt="My image"/>
note that the {% static 'file.extension' %} is used only to render static files.
I would suggest to use Django Filer with Easy Thumbnails.
You will only need one image field in your model and leave making the thumbnail to Easy Thumbnails on rendering of the template.