How to give FileField's upload_to parameter a dynamic function?
I wrote 3 models: ... def generate_mugshot(instance, filename): filename, ext = os.path.splitext(filename) return "mugshot/%s/%s%s" % (instance.id, uuid4(), ext) def generate_team_photo(instance, filename): filename, ext = os.path.splitext(filename) return "team/%s/%s%s" % (instance.id, uuid4(), ext) def generate_gift_photo(instance, filename): filename, ext = os.path.splitext(filename) return "gift/%s/%s%s" % (instance.id, uuid4(), ext) class User(AbstractUser): ... mugshot = models.ImageField('头像', upload_to= generate_mugshot, validators=[check_image_extension], null=True, blank=True) class Team(models.Model): ... photo = models.ImageField('队标', upload_to= generate_team_photo, validators=[check_image_extension], blank=True, null=True) class Gift(models.Model): ... photo = models.ImageField('图片', upload_to= generate_gift_photo, validators=[check_image_extension], null=True, blank=True) If I want to add a new model, I have to write a new duplicate function "generate_something(instance, filename)", it is not pythonic. So I modify it to following code: def generate_attachment_by_id(prefix): def _return_function(instance, filename): filename, ext = os.path.splitext(filename) return "%s/%s/%s%s" % (prefix, instance.id, uuid4(), ext) return _return_function ... class User(AbstractUser): mugshot = models.ImageField('头像', upload_to=generate_attachment_by_id( 'mugshot'), validators=[check_image_extension], null=True, blank=True) class Team(models.Model): photo = models.ImageField('队标', upload_to=generate_attachment_by_id( 'team'), validators=[check_image_extension], blank=True, null=True) class Gift(models.Model): photo = models.ImageField('图片', upload_to=generate_attachment_by_id( 'gift'), validators=[check_image_extension], null=True, blank=True) Then I execute makemigrations, an error raised: ValueError: Could not find function _return_function in app.account.models. Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared and used in the same class body). Please move the function into the main module body to use migrations. For more information, see https://docs.djangoproject.com/en/1.10/topics/migrations/#serializing-values So, how to solve the problem? Thank you for helping me... -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e11aa79e-a103-4b5e-8420-371599d4a7eb%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
set_cookie raise exception when the value contains Unicode charset
Hello everyone, Following is my code: def post(self, request, *args, **kwargs): self.object = self.get_object() form = forms.CommentForm(request.POST or None) if form.is_valid(): response = self.form_valid(form) return self._set_cookies(response, form) ... @transaction.atomic def form_valid(self, form): self.object = form.save(commit=False) self.object.ip = get_remote_addr(self.request) self.object.save() return HttpResponseRedirect(self.get_success_url()) def _set_cookies(self, response, form): year = 365 * 24 * 60 * 60 response.set_cookie('nickname', form.cleaned_data['nickname'], max_age=year) response.set_cookie('url', form.cleaned_data['url'], max_age=year) response.set_cookie('email', form.cleaned_data['email'], max_age=year) return response But if the form.cleaned_data['nickname'] contains Chinese, an exception is raised: Traceback (most recent call last): File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__ return str(self).encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode characters in position 227-228: ordinal not in range(256) So how to save the unicode data into cookie? I have to urlencode it manually? -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4a5ca63a-e947-4c5a-80eb-bab026b6445a%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: set_cookie raise exception when the value contains Unicode charset
But I never change the DEFAULT_CHARSET , this is my diffsettings: $ ./manage.py diffsettings 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'}] AUTH_USER_MODEL = 'ucenter.User' BASE_DIR = '/Users/shiyu/pro/python/talkbook' ### DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'PORT': '', 'NAME': '/Users/shiyu/pro/python/talkbook/db.sqlite3', 'TEST': {'COLLATION': None, 'NAME': None, 'CHARSET': None, 'MIRROR': None}, 'PASSWORD': '', 'AUTOCOMMIT': True, 'TIME_ZONE': None, 'CONN_MAX_AGE': 0, 'USER': '', 'ATOMIC_REQUESTS': False, 'OPTIONS': {}, 'HOST': ''}} DEBUG = True DEFAULT_FROM_EMAIL = None EMAIL_HOST = None EMAIL_HOST_PASSWORD = None EMAIL_HOST_USER = None EMAIL_PORT = None EMAIL_USE_SSL = None EMAIL_USE_TLS = None INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_select2', 'django_markup', 'bootstrap3', 'pure_pagination', 'django_gravatar', 'mptt', 'captcha', 'app.ucenter', 'app.front', 'app.manager'] IP_HEADER = None ### LANGUAGE_CODE = 'zh-hans' LOGGING = {'version': 1, 'formatters': {'standard': {'format': '[%(asctime)s] - [%(levelname)s] - [%(name)s:%(lineno)d] - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'level': 'DEBUG'}, 'file': {'filename': '/Users/shiyu/pro/python/talkbook/error.log', 'class': 'logging.FileHandler', 'level': 'WARNING'}}, 'disable_existing_loggers': False, 'loggers': {'': {'handlers': ['console'], 'level': 'WARNING'}, 'talkbook': {'propagate': True, 'handlers': ['console'], 'level': 'DEBUG'}, 'django': {'handlers': ['file'], 'level': 'WARNING'}}} LOGIN_REDIRECT_URL = 'manager:index' LOGIN_URL = 'manager:login' MARKUP_SETTINGS = {'markdown': {'safe_mode': 'escape', 'extension_configs': {'toc': {'anchorlink': True}}, 'extensions': ('extra', 'nl2br', 'codehilite', 'toc', 'linkify')}} ### MEDIA_ROOT = '/Users/shiyu/pro/python/talkbook/media' MEDIA_URL = '/media/' 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'] OPTION_INI_PATH = '/Users/shiyu/pro/python/talkbook/conf/option.ini' ### PAGINATION_SETTINGS = {'SHOW_FIRST_PAGE_WHEN_INVALID': True, 'PAGE_RANGE_DISPLAYED': 5, 'MARGIN_PAGES_DISPLAYED': 2} ### ROOT_URLCONF = 'conf.urls' ### SECRET_KEY = '.' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SETTINGS_MODULE = 'conf.settings' ### STATIC_URL = '/static/' TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/Users/shiyu/pro/python/talkbook/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', 'talkbook.context.global_site_context']}}] TIME_ZONE = 'Asia/Shanghai' USE_L10N = True USE_TZ = True WSGI_APPLICATION = 'talkbook.wsgi.application' 在 2017年1月30日星期一 UTC+8上午9:48:47,Melvyn Sopacua写道: > > On Sunday 29 January 2017 13:03:34 Xx Johnsua wrote: > > > > > > > File > > > "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versio > > > ns/3.5/lib/python3.5/wsgiref/headers.py", line 142, in __bytes__ > > > return str(self).encode('iso-8859-1') > > > > https://docs.djangoproject.com/en/1.10/ref/settings/#default-charset > > > > I believe your default charset is set to 'iso-8859-1'. > > -- > > Melvyn Sopacua > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f45e726e-b6bd-4bad-a556-9283eeeb79a3%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.