我的项目有 ImproperlyConfigured 错误。请帮助我。
错误主体:
Internal Server Error: /en/admin/posts/post/
Traceback (most recent call last):
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner
return view(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\contrib\admin\options.py", line 1693, in changelist_view
cl = self.get_changelist_instance(request)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\contrib\admin\options.py", line 735, in get_changelist_instance
return ChangeList(
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\django\contrib\admin\views\main.py", line 57, in __init__
self.root_queryset = model_admin.get_queryset(request)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\parler\admin.py", line 279, in get_queryset
qs = super().get_queryset(request)
File "C:\Users\User\.virtualenvs\news-Jjvbi-2o\lib\site-packages\parler\admin.py", line 150, in get_queryset
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: QuerySet class does not inherit from TranslatableQuerySet
[26/Jan/2022 11:06:32] "GET /en/admin/posts/post/ HTTP/1.1" 500 108753
我的设置.py:
"""
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# tashqi app
'rest_framework',
"corsheaders",
'rosetta',
'taggit',
'hitcount',
'parler',
# ichki app
'posts',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.AllowAny'
]
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://localhost:8000",
# 'http://127.0.0.1:8000/',
# 'http://127.0.0.1:3000/',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [str(BASE_DIR.joinpath('templates'))],
'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',
],
'libraries' : {
'staticfiles': 'django.templatetags.static',
}
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/
LANGUAGES = (
('uz', _('Uzbek')),
('ru', _('Russian')),
('en', _('English')),
('tr', _('Turkish')),
)
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Asia/Tashkent'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = (
BASE_DIR, 'locale/',
)
PARLER_LANGUAGES = {
None: (
{'code': 'uz'},
{'code': 'ru'},
{'code': 'en'},
{'code': 'tr'},
),
'default': {
'fallback': 'en',
'hide_untranslated': False,
}
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
# STATIC_URL = '/static/'
# STATIC_DIR = BASE_DIR / 'static/'
# # STATIC_ROOT = BASE_DIR / 'static/'
# # STATICFILES_DIRS = (
# # #This lets Django collectstatic store our bundles
# # os.path.join(BASE_DIR, 'assets'),
# # os.path.join(BASE_DIR, 'resources'),
# # )
# STATICFILES_DIRS = [STATIC_DIR]
STATIC_URL = '/static/'
STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),) # new
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) # new
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
# MEDIA
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
我的模型.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from hitcount.models import HitCountMixin, HitCount
from django.contrib.contenttypes.fields import GenericRelation
from django.urls import reverse
from taggit.managers import TaggableManager
from django.utils.html import mark_safe
from django.utils.translation import gettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
# Create your models here.
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(TranslatableModel):
translations = TranslatedFields(
title = models.CharField(_('title'),max_length=200, db_index=True),
slug = models.SlugField(_('slug'), max_length=250, unique=True, db_index=True),
body = models.TextField(_("body"), db_index=True),
)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
image = models.ImageField(upload_to="post_images/%Y/%m/%d/")
# publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
views = models.PositiveIntegerField(default=0)
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
tags = TaggableManager() # Tag maneger
# class Meta:
# ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.created.year,
self.created.month,
self.created.day,
self.slug])
def avatar_tag(self):
return mark_safe('<img src="/media/%s" width="50" height="50" />' % (self.image))
avatar_tag.short_description = 'Rasmi'
我的admin.py:
from django.contrib import admin
from .models import Post, Card, Contact
from django.utils.html import mark_safe
from parler.admin import TranslatableAdmin
# Register your models here.
@admin.register(Post)
class PostAdmin(TranslatableAdmin):
list_display = ('title', 'slug', 'author', 'created','status',"avatar_tag")
list_filter = ('status', 'created', 'author')
search_fields = ('title', 'body')
raw_id_fields = ('author',)
date_hierarchy = 'created'
ordering = ('status', 'created')
readonly_fields = ('avatar_tag',)
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('title',)}
def avatar_tag(self, obj):
return obj.avatar_tag
avatar_tag.short_description = 'Rasmi'
my views.py :
class ListPost(ListAPIView):
queryset = Post.objects.order_by('-created').all()
serializer_class = PostSerializer
py序列化器.py:
from rest_framework import serializers
from .models import Post, Card
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = (
'id',
'title',
'slug',
'author',
'image',
'body',
'publish',
'status',
)
py urls.py(在应用程序中):
from django.urls import path
from .views import ListPost, DetailPost, ListCard, DetailCard
from django.utils.translation import gettext_lazy as _
urlpatterns = [
path(_('<int:pk>/'), DetailPost.as_view()),
path(_(''), ListPost.as_view()),
path(_('<int:pk>/card/'), DetailCard.as_view()),
]
我的 urls.py(主要):
“”
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.utils.translation import gettext_lazy as _
from django.conf.urls.i18n import i18n_patterns
from posts.views import ContactView
urlpatterns = i18n_patterns (
path(_('admin/'), admin.site.urls),
path('rosetta/', include('rosetta.urls')),
path(_('posts/'), include('posts.urls'), name='posts'),
path(_('hitcount/'), include(('hitcount.urls', 'hitcount'), namespace='hitcount')),
path('contact/', ContactView, name='contact')
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我有 2 个型号。卡片和邮政。刷卡可以,但是邮寄不行。 我是 django 新手,因为我在 2 天之前没有找到解决这个问题的方法。
请帮我解决
我也有同样的问题。我不确定这背后的原因是什么,但我用该项目的一个小版本进行了测试,如果您删除字段对象并在 Post 模型中发布,它就可以工作。可能有一个更具技术性的解决方案,但现在我将尝试修复此问题,删除模型管理器。
这是因为您刚刚在中定义了一个自定义查询集
objects = models.Manager() # The default manager.
解决这个导入TranslatableQuerySet
from parler.managers import TranslatableQuerySet
并使其像
objects = CustomQuerySet.as_manager()
和
class CustomQuerySet(TranslatableQuerySet):
# Your custom queryset methods
pass