我一开始就使用SQLite,但是现在我尝试切换到PostgreSQL并尝试执行makemigrations命令,现在我遇到了错误
Uri
正如其他人在答案中所建议的那样,因为我不担心丢失数据,所以我也删除了表和数据库,删除了迁移文件夹文件并在其中创建了 init .py它并尝试了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...
^
PostgreSQL的数据库设置。
./manage.py clear_cache
./manage.py clean_pyc
./manage.py reset_schema
./manage.py reset_db
已安装的应用
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'test_db',
'USER': 'postgres',
'PASSWORD': 'Test@123',
'HOST': 'localhost',
'PORT': '5432',
}
}
views.py
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'
]
signals.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})
请帮助我,对此我感到很困扰。
谢谢!
答案 0 :(得分:0)
这是一个很好的问题,我昨天遇到这种错误。我所做的只是注释一些使用models.py
中的表的代码行。例如,您的views.py
访问表中models.py
中的某些值。是不是现在,只需注释views.py
中的那些行即可。
现在,您的应用目录中没有migrations
文件。使用migrations
文件创建__init__.py
目录。然后运行python manage.py makemigrations
命令。如果您遇到任何错误,请对此答案发表评论,我会相应地对其进行更新。 migrations
之后,不要运行migrate
命令。
然后运行python manage.py showmigrations
命令,您将看到类似这样的内容。
[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
。我知道这有点令人困惑,但这应该可以解决。
现在取消评论您的评论。