ValueError:应设置给定的用户名

时间:2013-04-28 00:12:55

标签: django django-forms django-views

我正在尝试编写我的方法来在注册时添加用户类型对象。这是代码:

views.py

def registration(request):
c= {}
c.update(csrf(request))
state = "Please Register below..."
username = None
email = None
password = None
user_success = None
user_created = None
if request.POST:
    username = request.POST.get('username')
    email = request.POST.get('email')
    password = request.POST.get('password')
    print "username ",username

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        user_created = True
    else:
        user_created = False
else:
        user = User.objects.create_user(username=username,password=password,email=email)
        user.save()
        user.is_active = True
        user_success = True

return render_to_response('register.html',{'success':user_success,'created':user_created,'username': username},context_instance = RequestContext(request))

forms.py

class RegistrationForm(forms.Form):

username = forms.CharField()
email = forms.EmailField()
password =  forms.CharField()

templates / register.html是:

{% extends "base.html" %}
{% block pageContent %}
<div class="container">


    <form action="/register" method="post">

            {% csrf_token %}
            username:
            <input type="text" name="username" value="{{ username}}" /><br />
            password:
            <input type="password" name="password" value="" /><br />
            Email:
            <input type="text" name="email" value="{{email}}" /><br />

            <input type = 'submit' value='Register' />
    </form>


</div>
{% endblock %}

任何人都可以帮我发现错误吗?如果我正在进行注册,也请告诉我

2 个答案:

答案 0 :(得分:0)

此时username的值必须评估为True。

user = User.objects.create_user(username=username,password=password,email=email)
#                                        ^^^^^^^^ this can't be a bool() false 

为什么呢?该错误消息非常具体..它是在django auth中从this specific place调用的:

  def create_user(self, username, email=None, password=None, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        now = timezone.now()
        if not username:
            raise ValueError('The given username must be set')

你能100%肯定用户名是正确的价值吗?这听起来像是一个空字符串。

答案 1 :(得分:0)

我发现了错误。错误是在view.py的缩进。

if user is not None:

部分代码应仅在请求类型为POST时。所以需要缩进。