gpt4 book ai didi

python - 在 Django 应用程序中,即使迁移文件夹文件被删除,此错误也存在 'relation "blog_no_of_views“不存在”

转载 作者:行者123 更新时间:2023-11-29 12:23:24 26 4
gpt4 key购买 nike

我一开始使用的是 SQLite,但现在我尝试切换到 PostgreSQL 并尝试执行 makemigrations 命令,现在出现以下错误

 (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
self.execute(*args, **cmd_options)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\base.py", line 332, in execute
self.check()
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage
ment\base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\checks
\registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\checks
\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\checks
\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\utils\funct
ional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\urls\resolv
ers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\utils\funct
ional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\urls\resolv
ers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "E:\young_minds\heroku\youngmindsenv\lib\importlib\__init__.py", line 126
, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "E:\young_minds\heroku\youngminds\young_minds\urls.py", line 27, in <modu
le>
response = common_info()
File "E:\young_minds\heroku\youngminds\blog\views.py", line 35, in common_info

print(popular_post)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\models\q
uery.py", line 248, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\models\q
uery.py", line 272, in __iter__
self._fetch_all()
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\models\q
uery.py", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\models\q
uery.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=
self.chunk_size)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\models\s
ql\compiler.py", line 1064, in execute_sql
cursor.execute(sql, params)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 100, in execute
return super().execute(sql, params)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._e
xecute)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\utils.py
", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends
\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "blog_no_of_views" does not exist
LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o...
^

正如其他人在回答中所建议的那样,因为我不担心丢失数据,所以我也删除了表和数据库,我删除了迁移文件夹文件并在里面创建了 init.py它并尝试了 makemigrations 命令,但我仍然收到上述错误,

我很困惑从哪里得到这个错误,因为应用程序迁移文件夹中没有文件

它也会在以下所有命令中给出错误

./manage.py clear_cache
./manage.py clean_pyc
./manage.py reset_schema
./manage.py reset_db

PostgreSQL 的数据库设置。

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

已安装的应用

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',
"django_extensions",
#'sslserver'
]

View .py

from django.shortcuts import render,get_object_or_404,redirect
from .models import Post,Comment,Category,No_Of_Views,carousel_images_messages,about_page_details
from django.views.generic import ListView,DetailView,CreateView,UpdateView,DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin
from django.contrib.auth.models import User
from .forms import CommentForm
from django.template.loader import render_to_string
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import Q
from django.core.mail import send_mail
from django.contrib import messages
# Create your views here.

def home(request):

context = {"posts":Post.objects.all()}
return render(request,'blog/home.html',context)
def feedback_email(request):

if request.method == 'POST':

send_mail(('username ({}) '.format(request.user.username))+"[ "+request.POST.get('subject')+" ]",
request.POST.get('feedback_content'),'alphayoungminds@gmail.com',
['alphayoungminds@gmail.com'],fail_silently=False)
messages.success(request,f'Thank you for taking your time out! Your Feeback is very important to us!')
return redirect("about")
def common_info():

#for category with count
categories = Post.objects.values('category__category').order_by('category').annotate(the_count=Count('category'))

# for popular post with views
popular_post = No_Of_Views.objects.all().order_by('-views_count')[:5]
print(popular_post)
popular_post_list = []
for post in popular_post:
single_post = Post.objects.get(pk=post.post)
popular_post_list.append(single_post)


result = {"categories":categories,"popular_post":popular_post_list}
return result


class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 8

def get_queryset(self):

post_list = []

search = self.request.GET.get('search')

if search :

posts_all = Post.objects.filter(Q(author__username__icontains=search) |
Q(title__icontains=search) |
Q(content__icontains=search)).order_by("-date_posted")
for post in posts_all:
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)
else:
posts_all = Post.objects.all().order_by("-date_posted")
for post in posts_all: #this line is giving same error again
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)

return post_list

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
response = common_info()
context['categories'] = response["categories"]
context['popular_posts'] = response["popular_post"]
context['carousels'] = carousel_images_messages.objects.all()
context['title'] = "Young Minds"
'''print(response["categories"])
print(response["popular_post"])'''


return context

class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name = 'posts'
paginate_by = 8



def get_queryset(self):

post_list = []

search = self.request.GET.get('search')

if search :

posts_all = Post.objects.filter(Q(author__username__icontains=search) |
Q(title__icontains=search) |
Q(content__icontains=search),Q(author__username__iexact=self.kwargs.get('username'))).order_by("-date_posted")
for post in posts_all:
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)
else:
posts_all = Post.objects.filter(author__username__iexact=self.kwargs.get('username')).order_by("-date_posted")

for post in posts_all:
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)

return post_list


def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.kwargs.get('username')
context['title'] = user.title() +"'s Posts"
response = common_info()
context['categories'] = response["categories"]
context['popular_posts'] = response["popular_post"]
context['user_name'] = self.kwargs.get('username')
return context



class CategoryListView(ListView):
model = Post
template_name = 'blog/category_posts.html'
context_object_name = 'posts'
paginate_by = 8


def get_queryset(self):

post_list = []

search = self.request.GET.get('search')

if search :

posts_all = Post.objects.filter(Q(author__username__icontains=search) |
Q(title__icontains=search) |
Q(content__icontains=search),Q(category__category__iexact=self.kwargs.get('category'))).order_by("-date_posted")
for post in posts_all:
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)
else:
posts_all = Post.objects.filter(category__category__iexact=self.kwargs.get('category')).order_by("-date_posted")

for post in posts_all:
try:
views = No_Of_Views.objects.get(post=post.pk)
views = views.views_count
post.views = views
except:
views = 0
post_list.append(post)

return post_list
'''category = self.kwargs.get('category')
print(category)
print(Post.objects.filter(category=category).order_by("-date_posted"))
return Post.objects.filter(category=category).order_by("-date_posted")'''

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['selected_category'] = self.kwargs.get('category')
response = common_info()
context['categories'] = response["categories"]
context['popular_posts'] = response["popular_post"]
context['title'] = 'Category-'+ self.kwargs.get('category')
return context


'''class ActiveUserPostDetailView(ListView):
model = Post
template_name = 'blog/user_all_posts.html'
context_object_name = 'posts'
paginate_by = 6
def get_queryset(self):
return Post.objects.filter(author__username=self.request.user).order_by("-date_posted")

def get_context_data(self, **kwargs):
# no of views

## ends here
context = super().get_context_data(**kwargs)
response = common_info()
context['categories'] = response["categories"]
context['popular_posts'] = response["popular_post"]

return context'''


class AboutListView(ListView):
model = about_page_details
template_name = 'blog/about.html'
context_object_name = 'about_makers'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)

response = common_info()
context['categories'] = response["categories"]

context['title'] = 'About Page'
return context





class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
def get_queryset(self):
return Post.objects.filter(pk=self.kwargs.get('pk')).order_by("-date_posted")

def get_context_data(self, **kwargs):
# no of views

no_of_views = No_Of_Views.objects.filter(post=self.kwargs.get('pk')).exists()

#RealEstateListing.objects.filter(slug_url=slug).exists()
if no_of_views:

no_of_views_count = No_Of_Views.objects.get(post=self.kwargs.get('pk'))
print(no_of_views_count.username)
print(self.request.user)
print(no_of_views_count.views_count)

if no_of_views_count.username != self.request.user.username:
no_of_views_save = int(no_of_views_count.views_count) + 1
no_of_views_count.views_count = no_of_views_save
no_of_views_count.save()
else:
no_of_views_save = no_of_views_count.views_count

else:
post_title = Post.objects.get(pk=self.kwargs.get('pk'))
print(post_title.title)


no_of_views_save = 0
no_of_views_for_post = No_Of_Views(post=self.kwargs.get('pk'),post_title=post_title.title,username=post_title.author,views_count=no_of_views_save)
no_of_views_for_post.save()


## ends here
context = super().get_context_data(**kwargs)
post = Post.objects.filter(pk=self.kwargs.get('pk')).order_by("-date_posted")
context['comments'] = Comment.objects.filter(post=post[0],reply=None).order_by("-id")

context['comment_form'] = CommentForm()
is_liked = False

if post[0].likes.filter(id=self.request.user.id).exists():
is_liked = True



similar_post_pk = Post.objects.filter(pk=self.kwargs.get('pk')).order_by("-date_posted")
similar_post_pk = similar_post_pk[0]

similar_post = Post.objects.filter(category__category__iexact=similar_post_pk.category.category).exclude(pk=self.kwargs.get('pk')).order_by("-date_posted")[:3]
if len(similar_post) == 0:
similar_post = Post.objects.all().exclude(pk=self.kwargs.get('pk')).order_by("-date_posted")[:3]
context['is_liked'] = is_liked
context['similar_posts'] = similar_post

context['views'] = int(no_of_views_save)
response = common_info()
context['categories'] = response["categories"]
context['popular_posts'] = response["popular_post"]
title = (post[0]).title
context['title'] = title
#context['total_likes'] = post.total_likes()

return context
def post(self, request, *args, **kwargs):
post = Post.objects.filter(pk=self.kwargs.get('pk')).order_by("-date_posted")
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
content = comment_form.cleaned_data["content"]
reply_id = self.request.POST.get("comment_id")
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
comment_form = Comment.objects.create(post=post[0],user=self.request.user,content=content, reply=comment_qs)
comment_form.save()
return redirect("post-detail",pk=self.kwargs.get('pk'))



class PostLikeListView():
model = Post
template_name = 'blog/likes_list.html'
context_object_name = 'post'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)

response = common_info()
context['categories'] = response["categories"]

context['title'] = 'About Page'
return context

class PostCreateView(LoginRequiredMixin,CreateView):
model = Post
fields = ["title","category","content","thumbnail"]

def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)

response = common_info()
context['categories'] = response["categories"]

context['title'] = 'Create Blog'
return context

class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = Post
fields = ["title","content","image1","image2","image3"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)

def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
else:
return False

class PostDeleteView(LoginRequiredMixin,UserPassesTestMixin,DeleteView):
model = Post
success_url = "/"
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
else:
return False

def like_post(request):
#post = get_object_or_404(Post,id=request.POST.get("post_id"))
if request.method == 'POST':

print("\ninside like view\n")
print("\n in {} \n".format(request.POST.get('id')))
post = get_object_or_404(Post,id=request.POST.get("id"))

is_liked = False
if post.likes.filter(id=request.user.id).exists():
print("\ninside like\n")
post.likes.remove(request.user)
is_liked = False
else:
print("\ninside dislike\n")
post.likes.add(request.user)
is_liked = True
comments = Comment.objects.filter(post=post,reply=None).order_by("-id")
context = {
"post":post,
"is_liked":is_liked,
"comment": comments
}
#return redirect("post-detail",pk=request.POST.get("post_id"))
print("\ngetting in ajax\n")
if request.is_ajax():
print("\ninside ajax\n")
html = render_to_string('blog/likes_section.html', context, request=request)
return JsonResponse({"form":html})

信号.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from . models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
else:
pass

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()

请帮助我,我对此很困扰。

提前致谢!

最佳答案

这是个好问题,我昨天遇到了这种错误。我所做的只是评论一些使用来自 models.py 的表格的代码行.例如你的 views.pymodels.py 中的表访问一些值.不是吗?现在只需评论来自 views.py 的那些行.

现在你没有migrations文件在你的应用程序目录中。创建migrations目录 __init__.py文件。然后运行 ​​python manage.py makemigrations命令。如果您遇到任何错误,请对此答案发表评论,我会相应地对其进行更新。 migrations之后不要跑migrate命令。

然后运行python manage.py showmigrations命令,你会看到类似这样的东西。

enter image description here

那是什么 [X]意思是?它使用数据库表检查您的迁移。如果与您的迁移相关的更改已经在数据库中,它会显示 [X]迁移文件名前的图标,如果没有,将显示 [ ]这种图标。如果看到它,请运行 python manage.py migrate命令,否则运行 python manage.py migrate --fake命令。这就是我解决问题的方法。始终检查 showmigrations并在运行前了解一下 migrate命令。如果你看到 [ ] , 但它已经在数据库中,然后运行 ​​python manage.py migrate --fake <app_name> <migration_file_name> .然后运行 ​​python manage.py migrate .这有点令人困惑,我知道,但这应该可行。

现在取消评论您的评论。

关于python - 在 Django 应用程序中,即使迁移文件夹文件被删除,此错误也存在 'relation "blog_no_of_views“不存在”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com