尝试创建一个表单,您可以在其中注册为用户,并将自己添加到一个或多个类别。执行此操作时出错:
/users/add-user/ 处的类型错误
'categories' 是此函数的无效关键字参数
这是我的forms.py:
class AddUser(forms.Form):
name = forms.CharField()
title = forms.CharField()
website = forms.CharField(required=False)
email = forms.EmailField()
phone = forms.CharField(required=False)
company = forms.ModelChoiceField(queryset=Company.objects.all())
categories = forms.ModelMultipleChoiceField(queryset=Category.objects.all())
最后一行是我遇到的麻烦。
这是我的views.py:
def add_user(request):
if request.method == 'POST':
form = AddUser(request.POST)
if form.is_valid():
cd = form.cleaned_data
try:
p = User.objects.get(email=cd['email'])
error = "There's already a user with that e-mail adress registered. Maybe he/she is already here?"
return render_to_response('users/add_user.html', {'form': form, 'error': error}, context_instance=RequestContext(request))
except User.DoesNotExist:
p = User(name=cd['name'], title=cd['title'], website=cd['website'], email=cd['email'], phone=cd['phone'], company=cd['company'], categories=cd['categories'])
p.save()
return HttpResponseRedirect('../thanks/')
else:
form = AddUser(request.POST)
error = "You can't really submit empty forms. Try adding something useful :)"
return render_to_response('users/add_user.html', {'form': form}, context_instance=RequestContext(request))
如果有人对这个问题有任何建议(或者甚至是改进我的代码的一般建议),我会很高兴!我是 Django 的初学者,感谢所有帮助。