我有一个Django应用程序,并希望在用户的配置文件中显示多个 Select 复选框.然后,他们将能够 Select 多个项目.

这是My Models.py的简化版本:

from profiles.choices import SAMPLE_CHOICES

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True, verbose_name_('user'))
    choice_field = models.CharField(_('Some choices...'), choices=SAMPLE_CHOICES, max_length=50)

和我的窗体类:

class ProfileForm(forms.ModelForm):
    choice_field = forms.MultipleChoiceField(choices=SAMPLE_CHOICES, widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Profile

和我的views.py:

if request.method == "POST":
    profile_form = form_class(request.POST, instance=profile)
    if profile_form.is_valid():
        ...
        profile.save()
return render_to_response(template_name, {"profile_form": profile_form,}, context_instance=RequestContext(request))

我可以看到POST只发送了一个值:

choice_field u'choice_three' 

本地的vars params正在发送一个列表:

[u'choice_one', u'choice_two', u'choice_three']

所有的表单域都显示正确,但是当我提交帖子时,我收到一个错误

绑定参数7时出错-可能是不支持的类型.

我是否需要在视图中进一步处理多项 Select 域?模型字段类型是否正确?任何帮助或推荐人都将不胜感激.

推荐答案

配置文件 Select 需要设置为ManyToManyField才能正常工作.

所以你的模型应该是这样的:

class Choices(models.Model):
  description = models.CharField(max_length=300)

class Profile(models.Model):
  user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
  choices = models.ManyToManyField(Choices)

然后,同步数据库并加载具有您想要的各种选项的选项.

现在,ModelForm将自行构建.

class ProfileForm(forms.ModelForm):
  Meta:
    model = Profile
    exclude = ['user']

最后,观点是:

if request.method=='POST':
  form = ProfileForm(request.POST)
  if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    profile.save()
else:
  form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

应该提到的是,您可以通过几种不同的方式设置配置文件,包括继承.这就是说,这也应该对你有用.

祝好运.

Django相关问答推荐

通过 B 的外键列表访问模型 B 的行

通过get_form_kwargs将请求传递给Django表单未能使表单访问self.request.user.

Django中的InvalidOperation错误[]

在 Django 中按月份和年份对帖子进行分类

在 Django 4.1 中提交表单之前显示数据

无法创建超级用户,因为 Django 中的一列(外键)不能为空

Django Query 在基于通用类的 UpdateView 中重复了 2 次

Django celery 页面给出 404

超级用户在基于类的视图中进行身份验证

Django 长时间运行带有线程/处理的异步任务

Django Blob 模型字段

根据模型属性获取django对象id

Django - 在模板中显示当前日期和时间

Django:在管理界面中显示图像

django 模板中对象的模型名称

如何在不发送信号的情况下保存模型?

import_module 的 Django 1.9 ImportError

ModelForm 上的 Django 和字段集

django.db.utils.OperationalError 无法连接到服务器

使用 .order_by() 和 .latest() 的 Django 查询