- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一开始使用的是 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.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
.这有点令人困惑,我知道,但这应该可行。
现在取消评论您的评论。
关于python - 在 Django 应用程序中,即使迁移文件夹文件被删除,此错误也存在 'relation "blog_no_of_views“不存在”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921960/
我已经使用 vue-cli 两个星期了,直到今天一切正常。我在本地建立这个项目。 https://drive.google.com/open?id=0BwGw1zyyKjW7S3RYWXRaX24tQ
您好,我正在尝试使用 python 库 pytesseract 从图像中提取文本。请找到代码: from PIL import Image from pytesseract import image_
我的错误 /usr/bin/ld: errno: TLS definition in /lib/libc.so.6 section .tbss mismatches non-TLS reference
我已经训练了一个模型,我正在尝试使用 predict函数但它返回以下错误。 Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]])
根据Microsoft DataConnectors的信息我想通过 this ODBC driver 创建一个从 PowerBi 到 PostgreSQL 的连接器使用直接查询。我重用了 Micros
我已经为 SoundManagement 创建了一个包,其中有一个扩展 MediaPlayer 的类。我希望全局控制这个变量。这是我的代码: package soundmanagement; impo
我在Heroku上部署了一个应用程序。我正在使用免费服务。 我经常收到以下错误消息。 PG::Error: ERROR: out of memory 如果刷新浏览器,就可以了。但是随后,它又随机发生
我正在运行 LAMP 服务器,这个 .htaccess 给我一个 500 错误。其作用是过滤关键字并重定向到相应的域名。 Options +FollowSymLinks RewriteEngine
我有两个驱动器 A 和 B。使用 python 脚本,我在“A”驱动器中创建一些文件,并运行 powerscript,该脚本以 1 秒的间隔将驱动器 A 中的所有文件复制到驱动器 B。 我在 powe
下面的函数一直返回这个错误信息。我认为可能是 double_precision 字段类型导致了这种情况,我尝试使用 CAST,但要么不是这样,要么我没有做对...帮助? 这是错误: ERROR: i
这个问题已经有答案了: Syntax error due to using a reserved word as a table or column name in MySQL (1 个回答) 已关闭
我的数据库有这个小问题。 我创建了一个表“articoli”,其中包含商品的品牌、型号和价格。 每篇文章都由一个 id (ID_ARTICOLO)` 定义,它是一个自动递增字段。 好吧,现在当我尝试插
我是新来的。我目前正在 DeVry 在线学习中级 C++ 编程。我们正在使用 C++ Primer Plus 这本书,到目前为止我一直做得很好。我的老师最近向我们扔了一个曲线球。我目前的任务是这样的:
这个问题在这里已经有了答案: What is an undefined reference/unresolved external symbol error and how do I fix it?
我的网站中有一段代码有问题;此错误仅发生在 Internet Explorer 7 中。 我没有在这里发布我所有的 HTML/CSS 标记,而是发布了网站的一个版本 here . 如您所见,我在列中有
如果尝试在 USB 设备上构建 node.js 应用程序时在我的树莓派上使用 npm 时遇到一些问题。 package.json 看起来像这样: { "name" : "node-todo",
在 Python 中,您有 None单例,在某些情况下表现得很奇怪: >>> a = None >>> type(a) >>> isinstance(a,None) Traceback (most
这是我的 build.gradle (Module:app) 文件: apply plugin: 'com.android.application' android { compileSdkV
我是 android 的新手,我的项目刚才编译和运行正常,但在我尝试实现抽屉导航后,它给了我这个错误 FAILURE: Build failed with an exception. What wen
谁能解释一下?我想我正在做一些非常愚蠢的事情,并且急切地等待着启蒙。 我得到这个输出: phpversion() == 7.2.25-1+0~20191128.32+debian8~1.gbp108
我是一名优秀的程序员,十分优秀!