You need to enable JavaScript to run this app. 如何存储Django表单默认值到数据库并解决ChoiceField初始化报错
优惠活动
大模型
产品
解决方案
定价
更多

如何存储Django表单默认值到数据库并解决ChoiceField初始化报错

问题背景

我有一个书签页面,需要实现多种排序功能,用户选定的排序类型会被存储到数据库,同时下拉选择菜单会将用户选定的排序类型作为默认值展示。

我最初编写的代码如下:

class BookmarksSortingForm(forms.Form):

    SORTING_CHOICES =   [(1, "новым"),
                        (2, "имени"),
                        (3, "звёздам -"),
                        (4, "звёздам +")]

    bm_sorting = forms.ChoiceField(SORTING_CHOICES)

    # 在视图中调用方式:form = MyForm(..., request=request)
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super().__init__(*args, **kwargs)
        self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1][1]

    def get_current_sorting(self):
        user = User.objects.get(username=self.request.user)
        return user.profile.bookmarks_sorting # 小整数字段,默认值为1

运行时在bm_sorting字段定义行抛出错误:TypeError: __init__() takes 1 positional argument but 2 were given,使用的Django版本为3.2.4。

错误回溯信息

Traceback (most recent call last):
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__
    response = self.process_request(request)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/middleware/common.py", line 53, in process_request
    if self.should_redirect_with_slash(request):
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/middleware/common.py", line 70, in should_redirect_with_slash
    if not is_valid_path(request.path_info, urlconf):
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/base.py", line 153, in is_valid_path
    return resolve(path, urlconf)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/base.py", line 24, in resolve
    return get_resolver(urlconf).resolve(path)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 556, in resolve
    for pattern in self.url_patterns:
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
    <source code not available>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
    <source code not available>
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
    <source code not available>
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
    <source code not available>
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
    <source code not available>
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
    <source code not available>
  File "/home/gamecoach/Seearo/Seearo/urls.py", line 23, in <module>
    re_path('account/?', include('account.urls')),
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/gamecoach/.virtualenvs/django3/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
    <source code not available>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
    <source code not available>
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
    <source code not available>
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
    <source code not available>
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
    <source code not available>
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
    <source code not available>
  File "/home/gamecoach/Seearo/account/urls.py", line 2, in <module>
    from account.views import AccountView, AchievementsView, AddToBookmarksView, \
  File "/home/gamecoach/Seearo/account/views.py", line 8, in <module>
    from account.forms import SettingsForm, UploadPhotoForm
  File "/home/gamecoach/Seearo/account/forms.py", line 6, in <module>
    class BookmarksSortingForm(forms.Form):
  File "/home/gamecoach/Seearo/account/forms.py", line 13, in BookmarksSortingForm
    bm_sorting = forms.ChoiceField(SORTING_CHOICES)

Exception Type: TypeError at /account/bookmarks.html
Exception Value: __init__() takes 1 positional argument but 2 were given
问题原因&解决方案

错误原因

Django的ChoiceField构造函数不支持直接传入选项列表作为位置参数,所有参数都必须以关键字参数的形式传入,直接传SORTING_CHOICES作为位置参数不符合接口要求,所以会抛出参数数量不匹配的错误。

修复步骤

  1. 首先修改bm_sorting字段的定义,明确指定choices关键字参数:
bm_sorting = forms.ChoiceField(choices=SORTING_CHOICES)
  1. 其次调整初始值设置的代码,ChoiceField的初始值需要传入选项元组的第一个元素(也就是存到数据库的整数值),不需要取元组的第二个显示值:
self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1]

修改完成后表单即可正常渲染。


内容的提问来源于stack exchange,提问作者Albina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 16:24:04