我正在使用Django框架编写基本的注册视图代码。
我有以下代码:
def register(request):
if request.method == 'POST':
username = request.POST.get("username")
password = request.POST.get("password")
email = request.POST.get("email")
firstname = request.POST.get("firstname")
lastname = request.POST.get("lastname")
userObj = User.objects.filter(username)
if userObj.exists():
return HttpResponse("username already exists")
emailObj = User.objects.filter(email)
if emailObj.exists():
return HttpResponse("email already exists")
newUser = User.objects.create_user(username, email, password, first_name=firstname, last_name=lastname)
if newUser is not Null:
newUser.save()
# render main menu page
return HttpResponse("user successfully registered")
else:
return HttpResponse("error creating newUser")
失败是由于行userObj = User.objects.filter(username)
和emailObj = User.objects.filter(email)
这是跟踪的一部分:
Traceback (most recent call last):
File "G:\Program Files\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "G:\Programming\project3\orders\views.py", line 21, in register
userObj = User.objects.filter(username)
File "G:\Program Files\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1247, in build_filter
arg, value = filter_expr
Exception Type: ValueError at /register
Exception Value: too many values to unpack (expected 2)
可以避免这种情况的发生,因为我只按照文档本身的要求进行了基本的Django注册。.
答案 0 :(得分:2)
User.objects.filter(username)
毫无意义,您必须使用类似User.objects.filter(username=username)