如何修复django.db.utils.ProgrammingError:关系“ blog_no_of_views”不存在

时间:2019-07-07 09:02:30

标签: python django postgresql

我是django的新手,我正在使用sqlite进行开发,现在当我切换到postgresql时,我遇到了错误

我试图查看关于stackoverflow和所有其他站点的所有答案,但这对我没有帮助。

我已经尝试删除迁移文件夹并运行makemigrations并进行迁移,但仍然给我有关makemigrations本身的错误。尝试运行 python manage.py migrate --run-syncdb也会在此命令上给出错误

(youngmindsenv) E:\young_minds\heroku\youngminds>python manage.py makemigrations

Traceback (most recent call last):
  File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "blog_no_of_views" does not exist
LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o...
                                                             ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\base.py", line 288, in run_from_argv

settings.py

import os


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))



SECRET_KEY = 'e-mc3z=m#6_w#lzy$eb%qik9fcdlqmzsfsdf9=5s(we74^)25q_ge5'


DEBUG = True

ALLOWED_HOSTS = ['youngminds.herokuapp.com',"localhost"]


# Application definition

INSTALLED_APPS = [
    'users.apps.UsersConfig',
    'blog.apps.BlogConfig',
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'storages',
    'django.contrib.humanize',
    'ckeditor',
    'ckeditor_uploader',
    'social_django',
    #'sslserver'
]

CKEDITOR_UPLOAD_PATH = 'uploads/'

CKEDITOR_CONFIGS = {
    'awesome_ckeditor': {
        'toolbar': 'Basic',
        'width':'auto'
    },
    'default': {
        'toolbar': 'full',
        'width':'auto'
    },
}

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',
    'social_django.middleware.SocialAuthExceptionMiddleware',  # added for social login
]

ROOT_URLCONF = 'young_minds.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',

                'social_django.context_processors.backends',  # added for social login
                'social_django.context_processors.login_redirect', # added for social login
            ],
        },
    },
]


# for social login

AUTHENTICATION_BACKENDS = (
    'social_core.backends.open_id.OpenIdAuth',  # for Google authentication
    'social_core.backends.google.GoogleOpenId',  # for Google authentication
    'social_core.backends.google.GoogleOAuth2',  # for Google authentication
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.twitter.TwitterOAuth',
    'social_core.backends.facebook.FacebookOAuth2',

    'django.contrib.auth.backends.ModelBackend',
)



WSGI_APPLICATION = 'young_minds.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

'''DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
}'''

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres_db',
        'USER': 'postgres',
        'PASSWORD': 'postgres@123',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}


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

STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATIC_URL = '/static/'





MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")


LOGIN_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'blog-home'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "gdfg@gmail.com"
EMAIL_HOST_PASSWORD = 'rtgdfg'

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
import math
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField

# Create your models here.
class Category(models.Model):

    category = models.CharField(max_length=100)

    def __str__(self):
        return self.category

    class Meta:
        verbose_name_plural = "categories"

class about_page_details(models.Model):


    user_name = models.CharField(max_length=100,default='')
    role = models.CharField(max_length=100,default='')
    image = models.ImageField(default='default_content.jpg', upload_to='about_page')
    description = models.TextField(max_length=1000,default='')

    def __str__(self):
        return self.user_name

    class Meta:
        verbose_name_plural = "about_page_details"

class carousel_images_messages(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default_content.jpg', upload_to='carousel_images')
    category = models.ForeignKey(Category, on_delete=models.CASCADE ,default='Other')
    message =  models.CharField(max_length=500)
    date_posted = models.DateTimeField(default=timezone.now)
    def __str__(self):
        return '{}'.format("images_800_534_resolution")

    class Meta:
        verbose_name_plural = "carousel_images_messages"



class No_Of_Views(models.Model):
    post = models.CharField(max_length=100)
    post_title = models.CharField(max_length=100)
    views_count = models.IntegerField(default=0)
    username = models.CharField(max_length=100)

    def __str__(self):
        return '{} counts on "{}"'.format((self.views_count),(self.post_title).title())

    class Meta:
        verbose_name_plural = "No_Of_Views"

class Post(models.Model):
    title = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE ,default='Other')
    content = RichTextUploadingField()
    summary = models.CharField(max_length=100,default="Please click to read more")
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    thumbnail = models.ImageField(default='default_content.jpg', upload_to='content_pic')
    image1 = models.ImageField(default='default_content.jpg', upload_to='content_pic')
    image2 = models.ImageField(default='default_content.jpg', upload_to='content_pic')
    image3 = models.ImageField(default='default_content.jpg', upload_to='content_pic')
    likes = models.ManyToManyField(User, related_name="likes", blank=True)

    def __str__(self):
        return self.title

    def total_likes(self):
        return self.likes.count()



    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk':self.pk})

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(max_length = 200)
    date_commented = models.DateTimeField(auto_now_add=True)
    reply = models.ForeignKey('Comment', null=True, related_name='replies', on_delete=models.CASCADE)

    def __str__(self):
        return '{} commented on blog "{}"'.format((self.user.username).title(),(self.post.title).title())

如果有人可以帮助我,我将非常感激。

谢谢!

更新

问题解决了,我在urls.py中调用一个函数犯了一个愚蠢的错误,恰好是此错误的罪魁祸首,将其删除解决了问题。

感谢大家抽出宝贵时间。感谢您的帮助!

0 个答案:

没有答案