我已经尝试了一段时间,将一个“所有者”字段添加到我的模型中。我看过其他问题,但我仍然没有运气。理想情况下,创建新便笺时,当前用户将在所有者字段中设置,并且不会更改。
以下是我的模型,序列化程序,以及据我所知查看的Note。我猜想CurrentUserDefault()函数需要其他上下文,但无法正确设置。
views.py
class NoteListCreateView(ListCreateAPIView):
authentication_classes = (SessionAuthentication, TokenAuthentication)
permission_classes = (DjangoModelPermissions,)
lookup_field = 'pk'
serializer_class = serializers.NoteSummarySerializer
def get_queryset(self):
qs = Note.objects.all()
# general search
query = self.request.GET.get('search')
if query is not None:
qs = qs.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
).distinct()
# title search
query = self.request.GET.get('title')
if query is not None:
qs = qs.filter(title__icontains=query)
# content search
query = self.request.GET.get('content')
if query is not None:
qs = qs.filter(content__icontains=query)
return qs
serializers.py
class NoteSummarySerializer(serializers.ModelSerializer):
owner = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
class Meta:
model = Note
fields = (
'pk',
'title',
'containerId',
'created',
'updated',
'owner',
)
models.py
class Base(models.Model):
title = models.CharField(max_length=30)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
class Meta:
abstract = True
ordering = ['title', '-updated']
class Note(Base):
containerId = models.ForeignKey(Folder, related_name='notes', on_delete=models.CASCADE, null=True)
content = models.TextField()
class Meta:
db_table = 'marknote_notes'
当我尝试发布新笔记时,出现以下错误:
IntegrityError at /marknote/note
NOT NULL constraint failed: marknote_notes.owner_id
Request Method: POST
Request URL: http://localhost:8000/marknote/note
Django Version: 2.1
Python Executable: /Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/bin/python
Python Version: 3.7.0
Python Path: ['/Users/sheldonwoodward/Developer/projects/marknote', '/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python37.zip', '/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7', '/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/lib-dynload', '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages']
Server time: Tue, 21 Aug 2018 02:57:59 +0000
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'marknote']
Installed 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']
Traceback:
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py" in execute
296. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: marknote_notes.owner_id) was the direct cause of the following exception:
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/generics.py" in post
244. return self.create(request, *args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/serializers.py" in save
214. self.instance = self.create(validated_data)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/rest_framework/serializers.py" in create
940. instance = ModelClass.objects.create(**validated_data)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/query.py" in create
413. obj.save(force_insert=True, using=self.db)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/base.py" in save
717. force_update=force_update, update_fields=update_fields)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/base.py" in save_base
747. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/base.py" in _save_table
830. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/base.py" in _do_insert
868. using=using, raw=raw)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/query.py" in _insert
1133. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
1285. cursor.execute(sql, params)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
100. return super().execute(sql, params)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
77. return executor(sql, params, many, context)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py" in execute
296. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /marknote/note
Exception Value: NOT NULL constraint failed: marknote_notes.owner_id
Request information:
USER: sheldonwoodward
GET: No GET data
POST:
title = 'Test 1'
content = 'Test 1'
FILES: No FILES data
COOKIES: No cookie data
META:
Apple_PubSub_Socket_Render = '/private/tmp/com.apple.launchd.Ub5WC3uGKI/Render'
CLICOLOR = '1'
COLORFGBG = '15;0'
COLORTERM = 'truecolor'
CONTENT_LENGTH = '278'
CONTENT_TYPE = 'multipart/form-data; boundary=--------------------------010663819168948174069971'
DJANGO_SETTINGS_MODULE = 'django_server.settings'
GATEWAY_INTERFACE = 'CGI/1.1'
HOME = '/Users/sheldonwoodward'
HTTP_ACCEPT = '*/*'
HTTP_ACCEPT_ENCODING = 'gzip, deflate'
HTTP_AUTHORIZATION = 'Token f093f174c4e5df0e1ea2c0ed96b06e15ff210070'
HTTP_CACHE_CONTROL = 'no-cache'
HTTP_CONNECTION = 'keep-alive'
HTTP_HOST = 'localhost:8000'
HTTP_POSTMAN_TOKEN = '1a299d28-3fe5-4b44-afb0-bfaf812f450f'
HTTP_USER_AGENT = 'PostmanRuntime/7.2.0'
ITERM_PROFILE = 'Sheldon'
ITERM_SESSION_ID = 'w1t0p0:DEBAC83E-F158-4352-B9F7-A2E992591FAC'
LANG = 'en_US.UTF-8'
LOGNAME = 'sheldonwoodward'
LSCOLORS = 'GxBxhxDxfxhxhxhxhxcxcx'
PATH = '/Users/sheldonwoodward/.local/share/virtualenvs/marknote-1Se4K7YM/bin:/usr/local/Cellar/pipenv/2018.7.1/libexec/tools:/Applications/MAMP PRO/Library/bin/:/Applications/MAMP/Library/bin/:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/sheldonwoodward/.javacc-6.0/bin:/usr/local/opt/sqlite/bin:/Users/sheldonwoodward/.composer/vendor/bin'
PATH_INFO = '/marknote/note'
PIP_PYTHON_PATH = '/usr/local/Cellar/pipenv/2018.7.1/libexec/bin/python3.7'
PWD = '/Users/sheldonwoodward/Developer/projects/marknote'
PYTHONDONTWRITEBYTECODE = '1'
QUERY_STRING = ''
REMOTE_ADDR = '127.0.0.1'
REMOTE_HOST = ''
REQUEST_METHOD = 'POST'
RUN_MAIN = 'true'
SCRIPT_NAME = ''
SERVER_NAME = '1.0.0.127.in-addr.arpa'
SERVER_PORT = '8000'
SERVER_PROTOCOL = 'HTTP/1.1'
SERVER_SOFTWARE = 'WSGIServer/0.2'
SHELL = '/bin/bash'
SHLVL = '1'
SSH_AUTH_SOCK = '/private/tmp/com.apple.launchd.slrqyEZVoL/Listeners'
TERM = 'xterm-256color'
TERM_PROGRAM = 'iTerm.app'
TERM_PROGRAM_VERSION = '3.1.6'
TERM_SESSION_ID = 'w1t0p0:DEBAC83E-F158-4352-B9F7-A2E992591FAC'
TMPDIR = '/var/folders/kh/c1hbp5r97b9fbwqny9rr7cym0000gp/T/'
TZ = 'UTC'
USER = 'sheldonwoodward'
XPC_FLAGS = '0x0'
XPC_SERVICE_NAME = '0'
_ = '/usr/local/bin/pipenv'
__CF_USER_TEXT_ENCODING = '0x1F6:0x0:0x0'
wsgi.errors = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
wsgi.file_wrapper = ''
wsgi.input = <_io.BufferedReader name=5>
wsgi.multiprocess = False
wsgi.multithread = True
wsgi.run_once = False
wsgi.url_scheme = 'http'
wsgi.version = '(1, 0)'
Settings:
Using settings module django_server.settings
ABSOLUTE_URL_OVERRIDES = {}
ADMINS = []
ALLOWED_HOSTS = []
APPEND_SLASH = True
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS = '********************'
AUTH_USER_MODEL = 'auth.User'
BASE_DIR = '/Users/sheldonwoodward/Developer/projects/marknote'
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_KEY_PREFIX = '********************'
CACHE_MIDDLEWARE_SECONDS = 600
CSRF_COOKIE_AGE = 31449600
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_PATH = '/'
CSRF_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SECURE = False
CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/Users/sheldonwoodward/Developer/projects/marknote/db.sqlite3', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'USER': '', 'PASSWORD': '********************', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}}}
DATABASE_ROUTERS = []
DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000
DATETIME_FORMAT = 'N j, Y, P'
DATETIME_INPUT_FORMATS = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y']
DATE_FORMAT = 'N j, Y'
DATE_INPUT_FORMATS = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y']
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = False
DECIMAL_SEPARATOR = '.'
DEFAULT_CHARSET = 'utf-8'
DEFAULT_CONTENT_TYPE = 'text/html'
DEFAULT_EXCEPTION_REPORTER_FILTER = 'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
DEFAULT_INDEX_TABLESPACE = ''
DEFAULT_TABLESPACE = ''
DISALLOWED_USER_AGENTS = []
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_PASSWORD = '********************'
EMAIL_HOST_USER = ''
EMAIL_PORT = 25
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = '********************'
EMAIL_SUBJECT_PREFIX = '[Django] '
EMAIL_TIMEOUT = None
EMAIL_USE_LOCALTIME = False
EMAIL_USE_SSL = False
EMAIL_USE_TLS = False
FILE_CHARSET = 'utf-8'
FILE_UPLOAD_DIRECTORY_PERMISSIONS = None
FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440
FILE_UPLOAD_PERMISSIONS = None
FILE_UPLOAD_TEMP_DIR = None
FIRST_DAY_OF_WEEK = 0
FIXTURE_DIRS = []
FORCE_SCRIPT_NAME = None
FORMAT_MODULE_PATH = None
FORM_RENDERER = 'django.forms.renderers.DjangoTemplates'
IGNORABLE_404_URLS = []
INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'marknote']
INTERNAL_IPS = []
LANGUAGES = [('af', 'Afrikaans'), ('ar', 'Arabic'), ('ast', 'Asturian'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('be', 'Belarusian'), ('bn', 'Bengali'), ('br', 'Breton'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('dsb', 'Lower Sorbian'), ('el', 'Greek'), ('en', 'English'), ('en-au', 'Australian English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-co', 'Colombian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('es-ve', 'Venezuelan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy', 'Frisian'), ('ga', 'Irish'), ('gd', 'Scottish Gaelic'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hsb', 'Upper Sorbian'), ('hu', 'Hungarian'), ('ia', 'Interlingua'), ('id', 'Indonesian'), ('io', 'Ido'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kab', 'Kabyle'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lb', 'Luxembourgish'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'Marathi'), ('my', 'Burmese'), ('nb', 'Norwegian Bokmål'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('os', 'Ossetic'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('udm', 'Udmurt'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI = ['he', 'ar', 'fa', 'ur']
LANGUAGE_CODE = 'en-us'
LANGUAGE_COOKIE_AGE = None
LANGUAGE_COOKIE_DOMAIN = None
LANGUAGE_COOKIE_NAME = 'django_language'
LANGUAGE_COOKIE_PATH = '/'
LOCALE_PATHS = []
LOGGING = {}
LOGGING_CONFIG = 'logging.config.dictConfig'
LOGIN_REDIRECT_URL = '/accounts/profile/'
LOGIN_URL = '/accounts/login/'
LOGOUT_REDIRECT_URL = None
MANAGERS = []
MEDIA_ROOT = ''
MEDIA_URL = ''
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
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']
MIGRATION_MODULES = {}
MONTH_DAY_FORMAT = 'F j'
NUMBER_GROUPING = 0
PASSWORD_HASHERS = '********************'
PASSWORD_RESET_TIMEOUT_DAYS = '********************'
PREPEND_WWW = False
ROOT_URLCONF = 'django_server.urls'
SECRET_KEY = '********************'
SECURE_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_PROXY_SSL_HEADER = None
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False
SERVER_EMAIL = 'root@localhost'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 1209600
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_NAME = 'sessionid'
SESSION_COOKIE_PATH = '/'
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SECURE = False
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_FILE_PATH = None
SESSION_SAVE_EVERY_REQUEST = False
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE = 'django_server.settings'
SHORT_DATETIME_FORMAT = 'm/d/Y P'
SHORT_DATE_FORMAT = 'm/d/Y'
SIGNING_BACKEND = 'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS = []
STATICFILES_DIRS = []
STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT = None
STATIC_URL = '/static/'
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']}}]
TEST_NON_SERIALIZED_APPS = []
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR = ','
TIME_FORMAT = 'P'
TIME_INPUT_FORMATS = ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_THOUSAND_SEPARATOR = False
USE_TZ = True
USE_X_FORWARDED_HOST = False
USE_X_FORWARDED_PORT = False
WSGI_APPLICATION = 'django_server.wsgi.application'
X_FRAME_OPTIONS = 'SAMEORIGIN'
YEAR_MONTH_FORMAT = 'F Y'
You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will
display a standard page generated by the handler for this status code.
任何帮助将不胜感激。
答案 0 :(得分:3)
对于这种情况,我有一个清晰的例程,我将对其进行解释。首先,CurrentUserDefault
并没有something magical,它只是返回我们先前给序列化器的request
的用户(通用视图通过调用{将请求传递给序列化器{1}},因为您使用的是泛型,所以效果不错。
但出于我们的目的,我们将编写一个新的自定义get_serializer
,它将返回用户的ID:
CurrentUserDefault
现在我们只需要使用CurrentUserDefault并填写class CurrentUserDefault(object):
def set_context(self, serializer_field):
self.user_id = serializer_field.context['request'].user.id
def __call__(self):
return self.user_id
def __repr__(self):
return unicode_to_repr('%s()' % self.__class__.__name__)
的{{1}}字段,我建议您使用owner_id
,原因是根据drf doc:
一个字段类,它不基于用户输入获取值,而是从默认值或可调用对象获取其值。
此字段将出现在validated_data中,但不会在序列化器输出表示中使用。
,因此它仅从NoteSummarySerializer
获取其值,因此它不是serializers.HiddenField
的用户输入,也不会在序列化器输出表示中使用。看起来很棒,对吧?
我们只是将此字段添加到序列化器中:
default or callable
然后进行最后一步,因为我们使用Changeable
来填充所有者,所以名称class NoteSummarySerializer(serializers.ModelSerializer):
owner_id = serializers.HiddenField(default=CurrentUserDefault())
class Meta:
model = Note
fields = (
'pk',
'title',
'containerId',
'created',
'updated',
'owner_id', ### dont forget to add it to the fields.
)
可用于其他用途。在这种情况下,我认为将其设置为CharField并将owner_id
(或您想要的任何内容)赋予其owner
并使其owner.username
为真,
所以我们的序列化器最终会像这样:
source