- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试为我的模型添加一个“所有者”字段。我已经看过其他问题,但我仍然没有运气。理想情况下,当创建新笔记时,当前用户将设置在所有者字段中并且不可更改。
下面是我的模型、序列化程序和就我所知的 Note View 。我猜 CurrentUserDefault() 函数需要额外的上下文,但我无法正确设置它。
View .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
class NoteSummarySerializer(serializers.ModelSerializer):
owner = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
class Meta:
model = Note
fields = (
'pk',
'title',
'containerId',
'created',
'updated',
'owner',
)
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.
最佳答案
对于这种情况,我有一个干净的例程,我会解释的。首先,CurrentUserDefault
不做something magical ,它只是返回了 request
的用户我们之前提供给序列化程序的(泛型 View 通过调用 get_serializer
将请求传递给序列化程序,因为您使用的是泛型,您做得很好)。
但出于我们的目的,我们将编写一个新的定制 CurrentUserDefault
,它将返回用户的 id:
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__)
现在我们只需要使用这个 CurrentUserDefault 并填充
owner_id
领域
NoteSummarySerializer
, 建议你用
serializers.HiddenField
,根据 drf 文档的原因:
A field class that does not take a value based on user input, but instead takes its value from a default value or callable.
This field will be present in validated_data but will not be used in the serializer output representation.
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.
)
然后是最后一步,因为我们使用了
owner_id
填写业主姓名
owner
可用于其他用途。在这种情况下,我认为将其设为 CharField 并给出
owner.username
(或任何你想要的)到它的
source
并使其
readonly
真的,
class NoteSummarySerializer(serializers.ModelSerializer):
owner_id = serializers.HiddenField(default=CurrentUserDefault())
owner = serializers.CharField(source='owner.username', read_only=True)
class Meta:
model = Note
fields = (
'pk',
'title',
'containerId',
'created',
'updated',
'owner_id',
'owner'
)
关于带有序列化程序的 Django REST 框架 CurrentUserDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51940976/
我对编程真的很陌生,并且在理解 RESTful API 的概念时遇到了一些麻烦。我读过 REST 和 RESTful API。我已经查看了 SO 中已经提出的问题,但似乎无法更好地理解该主题。 在我的
我以为我知道REST /“RESTFul”,restfulservices,webservices,SOA和微服务是什么,但是我遇到了许多不同的定义,我得出的结论是这些术语被过度使用,滥用或完全错误定
我有一个列表,其中有一个“人员和组”列。当我使用 REST 查询行时,我会在此列中列出用户 ID。 我发现这篇文章将帮助我将每个 id 转换为标题 http://www.codeproject.com
我想问一些关于 REST 调用的问题。我是 REST 调用的绿色,我想了解什么是 REST 调用以及如何使用 URL 向服务器发送 REST 调用。谁能给我一些基本的教程或链接供我引用? 另外,如果我
很难说出这里问的是什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或言辞激烈,无法以目前的形式合理回答。如需帮助澄清此问题以便可以重新打开,visit the help center . 8年前关闭
如果有一个 REST 资源我想监视来自其他客户端的更改或修改,那么最好(也是最 RESTful)的方法是什么? 我这样做的一个想法是通过提供特定资源来保持连接打开,而不是在资源不(尚)存在时立即返回。
我有一个可以返回大量项目的 RESTful API,我希望能够使用分页样式技术来限制项目数量,这是 RESTful API 中的一个好主意吗? 如果有可能最好通过链接(在这种情况下为 url)或请求正
我仍然处于适应以 REST 方式做事的过程中。 在我的情况下,客户端软件将与 RESTful 服务交互。很少,客户端会上传其整个实体数据库(每个实体序列化为大约 5kb 的 xml 块)。 也许我错了
设计一个路径解析可能有歧义的 REST API 是否被认为是不好的做法?例如: GET /animals/{id} // Returns the animal with the given ID
我知道 REST 并且知道在不使用 session 的情况下创建 RESTful Web 服务,我更了解它,但我不太了解无状态的概念以及使用 REST 如何使您的应用程序可扩展 有人可以解释 REST
我正在尝试找到解决以下问题的最佳方法:我们的应用程序是SaaS,它支持Web登录的SAML。该应用程序还公开了应该在自动化和无人值守的流程中使用的REST API,这意味着没有交互式用户可以键入凭据。
由于 REST 是无状态的,因此传入的每个请求都不知道传入的前一个请求。在这种情况下是否可以使用连接池? 如果要实现连接池,它将像标准数据库连接一样在每个请求时打开连接池并关闭它。 如何实现 REST
得墨忒耳定律(真的应该是得墨忒耳的建议)说你不应该“穿过”一个物体去接触它们的子物体。如果您作为客户需要执行一些重要的操作,大多数情况下您使用的域模型应该支持该操作。 REST 原则上是一个愚蠢的对象
我唯一真正接触到 REST 的想法已经通过 Ruby on Rails 的 RESTful routing .这非常适合我使用 Rails 构建的基于 CRUD 的应用程序,但因此我对 RESTful
有什么好处 http://www.example.com/app/servlet/cat1/cat2/item 网址 超过 http://www.example.com/app/servlet?c
我知道以前有人问过这类问题。我有我的问题的解决方案,我想知道我是否在任何地方破坏了 REST 或 HTTP 主体。 在我的系统中,我有一个名为 member 的资源。支持通常的GET/POST/PUT
我有一个API,可以执行一些批量处理任务。假设它确实为某些资源命名。 我批量传递了7个请求,其中5个更新成功,2个失败。 我的问题是如何应对。使用HTTP时,我无法同时返回成功和错误。 有一个部分成功
我来自 RPC 世界,但目前正在调查使用 REST 是否适合我的项目。至于据我了解 Wikipedia RESTful 服务的基本思想是提供对集合及其各个元素的访问。 在我的情况下,服务器将是一个测量
我想将REST添加到我的挂毯项目中,因此需要知道如何实现它。 有什么更好的方法? 谢谢。 [编辑,从答案中复制:]我必须将GET,PUT,POST和DELETE服务添加到我的挂毯应用程序中。我看到Ta
让 /users/{id}成为 RESTful 服务中的资源 url。 启用基本身份验证,只有经过身份验证的用户才能访问该 url。 示例场景: User_1 & User_2是经过身份验证的用户,用
我是一名优秀的程序员,十分优秀!