OperationalError at /admin/app/question/ no such table: app_question (django) - django

Im new to this and Im tryna make a q&a type of app, I was just starting then when I went to admin/ to try it out I got
OperationalError at /admin/app/question/
no such table: app_question
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/app/question/
Django Version: 4.0.1
Python Version: 3.10.1
Installed Applications:
['app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'crispy_forms',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users']
Installed 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']
Exception Type: OperationalError at /admin/app/question/
Exception Value: no such table: app_question
here is the models.py
from django.db import models
from django.contrib.auth.backends import ModelBackend
from users.models import CustomUser
# This is the question model
class Question(models.Model):
user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
title = models.CharField(max_length=30)
detail = models.TextField()
add_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
# This is the answer model
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
detail = models.TextField()
add_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.detail
I'd appreciate if its explained in a beginner friendly manner, thank you!

Here is the documentation. You should
run migrate again to create those model tables in your database:

Related

Reset Heroku DB now some of my schemas aren't migrating

New to heroku - I had some major problems with a migration from my local django app to Heroku prod so decided to destroy my heroku db with heroku pg:reset - this all seemed to go to plan, I then ran heroku run python manage.py migrate to attempt to recreate my schemas.
The following were migrated:
Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount
But none of my models.py tables went up - eg the following crucial schema was not migrated:
class mapCafes(models.Model):
id = models.BigAutoField(primary_key=True)
cafe_name = models.CharField(max_length=200)
cafe_address = models.CharField(max_length=200)
cafe_long = models.FloatField()
cafe_lat = models.FloatField()
geolocation = models.PointField(geography=True, blank=True, null=True)
venue_type = models.CharField(max_length=200)
source = models.CharField(max_length=200)
cafe_image_url = models.CharField(max_length=200, null=False)
# class Meta:
# # managed = False
def __str__(self):
return self.cafe_name
Installed Apps:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'testingland',
'rest_framework',
'bootstrap_modal_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'widget_tweaks',
]
Any advice?

Django can't load ckeditor in the admin page

This is my settings.py file
INSTALLED_APPS = [
'search.apps.SearchConfig',
'user.apps.UserConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django_node_assets',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_BASEPATH = "./search/static/ckeditor/ckeditor/"
CKEDITOR_UPLOAD_PATH = "/media/"
This is the models.py file
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class Content(models.Model):
heading = models.ForeignKey(SubTopics, on_delete=models.CASCADE)
content = RichTextField()
def __str__(self):
return self.heading.heading
This rich text editor is not showing on the admin page. Even no text field is shown on the page, just blank space.
I got the solution.
remove CKEDITOR_BASEPATH and it will work
you need to collect the static files. Use the command below in the terminal
python manage.py collectstatic

Django messages framework - lack of i18n by default

By default django messages framework does not localize it's messages correctly.
For example in admin interface
As you can see all other things in admin panel are localized. The translation file exists. Here is my settings.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
...
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'django.middleware.locale.LocaleMiddleware',
]
LANGUAGE_CODE = 'ru' # I've tried 'ru-RU'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
How to fix this? Thanks in advance. I have django version 3.0.6. This error also is absent in django 1.8
It was a breaking change from django/django#42b9a23 (Django 3.0+) that only updated the French translations.
You can patch DjangoTranslation.gettext to handle the smart quotes.
def _patch_gettext():
from django.utils.translation.trans_real import DjangoTranslation
_gettext = DjangoTranslation.gettext
def gettext(self, message):
text = _gettext(self, message)
if text is message and '“' in message:
new_message = message.replace('“', '"').replace('”', '"')
new_text = _gettext(self, new_message)
if new_text is not new_message:
return new_text
return text
DjangoTranslation.gettext = gettext
About patching
Subclass AppConfig in mysite/apps.py:
from django.apps import AppConfig
class MySiteAppConfig(AppConfig):
name = 'mysite'
def ready(self):
_patch_gettext()
Put the dotted path to that subclass in INSTALLED_APPS in mysite/settings.py:
INSTALLED_APPS = [
...
'mysite.apps.MySiteAppConfig',
]
Reference: https://docs.djangoproject.com/en/3.0/ref/applications/#configuring-applications

unable to import rest_framework

I have Anaconda installed in my system but clearly I have set up a new and clean environment for a django API project. I also have all the necessary requirements installed for the API. But when I try to import rest_framework it gives me an error saying "Unable to import 'rest_framework' " even when I have done the following:
#settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api',
]
#serializers.py
from rest_framework import serializers #<---- this line is giving me error
from .models import Plans
class PlansSerializer(serializers.ModelSerializer):
"""Serializer to map the Model instance into JSON format."""
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Plans
fields = ('id', 'name', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
requirements.txt
certifi==2018.11.29
Django==2.1.7
django-crispy-forms==1.7.2
django-filter==2.1.0
django-markdown==0.8.4
django-markdown2==0.3.1
django-pagedown==1.0.6
djangorestframework==3.9.2
djangorestframework-simplejwt==4.1.0
Markdown==3.0.1
markdown2==2.3.7
olefile==0.46
Pillow==5.4.1
Pygments==2.3.1
PyJWT==1.7.1
pytz==2018.9
I also always deactivate the conda's base environment and only activate the required environment.

Resubmitting File in FileField after Validation Error in Django [duplicate]

This question already has answers here:
How to make a Django form retain a file after failing validation
(5 answers)
Closed 6 years ago.
In Django project forms with FileField, ImageField. Everything works great, but when ValidationError is raised, I have to reselect all files and images again. I want to avoid this one by caches concept in django
but I am not getting currect output please correct this code and add if any required
-models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from django.db import models
from django.db.models import ImageField
# or if you use sorl-thumbnail
# from sorl.thumbnail.fields import ImageField
import os
def resume_path(instance, filename):
fn, ext = os.path.splitext(filename)
return "resumes/{id}{ext}".format(id=instance.title, ext=ext)
class Page(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
image = ImageField(upload_to=resume_path)
-admin.py
from django.contrib import admin
# Register your models here.
from django.contrib import admin
from file_resubmit.admin import AdminResubmitMixin
from .models import Page
from django.forms import ModelForm
from file_resubmit.admin import AdminResubmitImageWidget,
AdminResubmitFileWidget
from .models import Page
class PageModelForm(ModelForm):
class Meta:
model = Page
widgets = {
'picture': AdminResubmitImageWidget,
'file': AdminResubmitFileWidget,
}
fields = '__all__'
class PageAdmin(admin.ModelAdmin,AdminResubmitMixin):
form = PageModelForm
admin.site.register(Page, PageAdmin)
-settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
"file_resubmit": {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
"LOCATION": '/home/xxxxxx/Downloads/Python/Projects_Python/pleasecome/tmp/file_resubmit',
# "LOCATION": os.path.join(BASE_DIR,'tmp/file_resubmit/'),
},
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sub',
'file_resubmit',
]
MIDDLEWARE_CLASSES = [
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.gzip.GZipMiddleware',
'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.cache.FetchFromCacheMiddleware',
]
The problem might be with the class PageAdmin
class PageAdmin(admin.ModelAdmin,AdminResubmitMixin):
form = PageModelForm
According to the documentation for django-form-resubmit the ModelAdmin should be be created in one of these ways:
class PageAdmin(admin.ModelAdmin):
form = PageModelForm
class PageAdmin(AdminResubmitMixin, admin.ModelAdmin):
pass
The order you declare parent classes is significant, so you should follow the official example. And since you have a custom form, you don't need to use the AdminResubmitMixin at all.