Recently, I'm working with my Django Portfolio and after successfully deploying on Heroku I faced this error
LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post...
So, this is how complete error is looking like
Request Method: GET
Request URL: https://shubhajeet-pradhan.herokuapp.com/
Django Version: 3.0.8
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shubhajeet_portfolio',
'base.apps.BaseConfig',
'crispy_forms',
'django_filters',
'ckeditor',
'ckeditor_uploader',
'storages',
'cloudinary_storage']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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')
Template error:
In template /app/base/templates/base/index.html, error at line 171
relation "base_post" does not exist
LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post...
^
161 : </div>
162 : </section>
163 :
164 : <section >
165 : <div >
166 : <div >
167 : <h3 style="text-align: center;">Projects</h3>
168 : <div >
169 : {% include 'base/navbar_blog.html' %}
170 : <div >
171 : {% for post in posts %}
172 : <div>
173 : <div >
174 : <img src="{{post.thumbnail.url}}">
175 : <div >
176 : <h6 >{{post.headline}}</h6>
177 : <p >{{post.sub_headline}}</p>
178 : <a href="{% url 'post' post.slug %}">Read More</a>
179 : </div>
180 : </div>
181 : </div>
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
The above exception (relation "base_post" does not exist
LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post...
^
) was the direct cause of the following exception:
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/base/views.py", line 26, in home
return render(request, 'base/index.html', context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/base.py", line 171, in render
return self._render(context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/base.py", line 163, in _render
return self.nodelist.render(context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/base.py", line 936, in render
bit = node.render_annotated(context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/base.py", line 903, in render_annotated
return self.render(context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/template/defaulttags.py", line 166, in render
len_values = len(values)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 258, in __len__
self._fetch_all()
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 1261, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 57, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1152, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 81, in _execute
with self.db.wrap_database_errors:
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /
Exception Value: relation "base_post" does not exist
LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post...
and this is my views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader import render_to_string
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.forms import UserCreationForm
from .decorators import *
from .forms import PostForm, CustomUserCreationForm, ProfileForm, UserForm
from .filters import PostFilter
from .models import *
# Create your views here.
def home(request):
posts = Post.objects.filter(active=True, featured=True)[0:6]
context = {'posts': posts}
return render(request, 'base/index.html', context)
def posts(request):
posts = Post.objects.filter(active=True)
myFilter = PostFilter(request.GET, queryset=posts)
posts = myFilter.qs
page = request.GET.get('page')
paginator = Paginator(posts, 6)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {'posts': posts, 'myFilter': myFilter}
return render(request, 'base/posts.html', context)
def post(request, slug):
post = Post.objects.get(slug=slug)
if request.method == 'POST':
PostComment.objects.create(
author=request.user.profile,
post=post,
body=request.POST['comment']
)
messages.success(request, "You're comment was successfully posted!")
return redirect('post', slug=post.slug)
context = {'post': post}
return render(request, 'base/post.html', context)
def profile(request):
return render(request, 'base/profile.html')
# CRUD VIEWS
@admin_only
@login_required(login_url="home")
def createPost(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('posts')
context = {'form': form}
return render(request, 'base/post_form.html', context)
@admin_only
@login_required(login_url="home")
def updatePost(request, slug):
post = Post.objects.get(slug=slug)
form = PostForm(instance=post)
if request.method == 'POST':
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
form.save()
return redirect('posts')
context = {'form': form}
return render(request, 'base/post_form.html', context)
@admin_only
@login_required(login_url="home")
def deletePost(request, slug):
post = Post.objects.get(slug=slug)
if request.method == 'POST':
post.delete()
return redirect('posts')
context = {'item': post}
return render(request, 'base/delete.html', context)
def sendEmail(request):
if request.method == 'POST':
template = render_to_string('base/email_template.html', {
'name': request.POST['name'],
'email': request.POST['email'],
'message': request.POST['message'],
})
email = EmailMessage(
request.POST['subject'],
template,
settings.EMAIL_HOST_USER,
['[email protected]']
)
email.fail_silently = False
email.send()
return render(request, 'base/email_sent.html')
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
# Little Hack to work around re-building the usermodel
try:
user = User.objects.get(email=email)
user = authenticate(request, username=user.username, password=password)
except:
messages.error(request, 'User with this email does not exists')
return redirect('login')
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Email/Password is incorrect')
context = {}
return render(request, 'base/login.html', context)
def registerPage(request):
form = CustomUserCreationForm()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
messages.success(request, 'Account successfully created!')
user = authenticate(request, username=user.username, password=request.POST['password1'])
if user is not None:
login(request, user)
next_url = request.GET.get('next')
if next_url == '' or next_url == None:
next_url = 'home'
return redirect(next_url)
else:
messages.error(request, 'An error has occurred with registration')
context = {'form': form}
return render(request, 'base/register.html', context)
def logoutUser(request):
logout(request)
return redirect('home')
@login_required(login_url="home")
def userAccount(request):
profile = request.user.profile
context = {'profile': profile}
return render(request, 'base/account.html', context)
@login_required(login_url="home")
def updateProfile(request):
user = request.user
profile = user.profile
form = ProfileForm(instance=profile)
if request.method == 'POST':
user_form = UserForm(request.POST, instance=user)
if user_form.is_valid():
user_form.save()
form = ProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return redirect('account')
context = {'form': form}
return render(request, 'base/profile_form.html', context)
Ths is my models.py file
from django.db import models
from django.contrib.auth.models import User
from django.utils.text import slugify
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class Profile(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, blank=True, null=True)
last_name = models.CharField(max_length=200, blank=True, null=True)
email = models.CharField(max_length=200)
profile_pic = models.ImageField(null=True, blank=True, upload_to="images", default="/user.png")
bio = models.TextField(null=True, blank=True)
twitter = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
name = str(self.first_name)
if self.last_name:
name = ' ' str(self.last_name)
return name
class Tag(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Post(models.Model):
headline = models.CharField(max_length=200)
sub_headline = models.CharField(max_length=200, null=True, blank=True)
thumbnail = models.ImageField(null=True, blank=True, upload_to="images", default="/images/placeholder.png")
body = RichTextUploadingField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
featured = models.BooleanField(default=False)
tags = models.ManyToManyField(Tag, blank=True)
slug = models.SlugField(null=True, blank=True)
def __str__(self):
return self.headline
def save(self, *args, **kwargs):
if self.slug is None:
slug = slugify(self.headline)
has_slug = Post.objects.filter(slug=slug).exists()
count = 1
while has_slug:
count = 1
slug = slugify(self.headline) '-' str(count)
has_slug = Post.objects.filter(slug=slug).exists()
self.slug = slug
super().save(*args, **kwargs)
class PostComment(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
body = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
def __str__(self):
return self.body
@property
def created_dynamic(self):
now = timezone.now()
return now
Can anybody help me out from this problem ?
Any suggestions or solutions would be appreciated.
CodePudding user response:
I guess it works on your computer,but not in heroku. It may be problem with data base.
Try to makemigrations
and migrate
. Check that this base post is exist in data base in development.
You could try to add some exception in html, like:
{% if posts %}
{% for post in posts %}
<your code>
{% else %}
<p>We have not any posts</p>
{% ednif %}