我想获取选择表单,该表单可以显示组名为“sale”的所有用户。 我对表单的定义是这样的:
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
user_choices = []
for user in User.objects.all():
if user.groups.filter(name="sale"):
user_choices.append(user.first_name)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
我的观点是这样的:
class ArrangeUserHandler(View):
def get(self, request):
form = ArrangeUserForm()
return render(request, 'student/student_form.html', {'form': form,})
def post(self, request):
pass
当我运行我的代码并请求该视图时,我收到以下错误:
/ student / arrangeuser /
中的ValueError要解压的值太多
谁能告诉我这里出了什么问题?回溯:
request Method: GET
Request URL: http://domain/student/arrangeuser/
Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'accounts',
'student',
'order')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template error:
In template /home/rogerliu/newproject/crm/templates/student/student_form.html, error at line 7
too many values to unpack
1 :
2 : <form method="post">
3 : {% csrf_token %}
4 : {% for field in form %}
5 : <div class="fieldWrapper">
6 : {{ field.errors }}
7 : {{ field.label_tag }}: {{ field }}
8 : </div>
9 : {% endfor %}
10 : <input type="submit" value="submit" />
11 :
12 : </form>
13 :
14 :
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/rogerliu/newproject/crm/student/views.py" in get
318. return render(request, 'student/student_form.html', {'form': form,})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
177. return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
140. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
74. return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
188. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
87. output = force_text(output)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_text
99. s = s.__unicode__()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
411. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
458. return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
555. options = self.render_options(choices, [value])
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
579. for option_value, option_label in chain(self.choices, choices):
Exception Type: ValueError at /student/arrangeuser/
Exception Value: too many values to unpack
〜
答案 0 :(得分:2)
根据我的评论,选择需要是一个关键的价值映射,使用:
tuple(enumerate(user_choices))
答案 1 :(得分:0)
我的问题是:你是如何定义模型的? 你能从小组中获得用户吗? 你能从用户那里得到这些团体吗? 类似的东西:
groups = Group.objects.get(pk=1)
groups.users
user = User.objects.get(pk=1)
user.groups
你可以在你的代码中写这个:
#models.py
class User(Model):
name = CharField(max_length=200)
class Group(Model):
name = CharField(max_length=200)
users = ManyToManyField(User, related_name="groups")
#forms.py
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
#And you views.py
class ArrangeUserHandler(FormView):
form_class = ArrangeUserForm
template_name = 'student/student_form.html'
def form_valid(self, form):
#When the form is valid
return super(ArrangeUserHandler, self).form_valid(form)
def form_invalid(self, form):
#When the form is invalid
return super(ArrangeUserHandler, self).form_invalid(form)
我认为它应该很好并且很快。 你能告诉我这条线是否有用吗?
# ...
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
# ...
我希望有所帮助。 请参阅 ManyToMany field和。{的文档 FormView 如果你在django 1.5