search

Home  >  Q&A  >  body text

python - django form.instance在单元测试时一直取不到值

1. 定义了一个SignupForm(注册用户),又override了save():目的是创建一个用户。save()代码如下:

def save(self):
    return MyUser.objects.create_user(self.instance.email, # 这三个参数是关键
                                      self.instance.username,
                                      self.instance.password)

2. 我在views.py里调用form.save()一切正常, 代码如下:

def user_signup(request):
    form = SignupForm()
    if request.method == 'POST':
        form = SignupForm(data=request.POST)
        if form.is_valid():
            form.save()
            # extra_tags是Bootstrap中的样式
            messages.success(request, const.SIGNUP_SUCCESS,
                             extra_tags='alert-success')
            return redirect('user_login')

    return render(request, 'signup.html', {'form': form})

3. 在单元测试test_forms.py中,调用form.save(), 调试发现create_user的三个参数(self.instance.email、self.instance.username、self.instance.password)全是空的,代码如下:

form = SignupForm(data={'email': 'a@a.com', 'username': 'test', 'password': '774411'})
user = form.save() # 这句会报错

请问哪位大神知道是什么原因?

PHP中文网PHP中文网2809 days ago303

reply all(1)I'll reply

  • 阿神

    阿神2017-04-18 09:44:02

    I know the reason, this should be a bug in Django (1.10.1).
    Because I am in unit testing, this does not work:

    form = SignupForm(
        data={'email': 'a@a.com', 'username': 'test', 'password': '774411'})
    user = form.save()
    

    But just print the form before save() and that’s it:

    form = SignupForm(
        data={'email': 'a@a.com', 'username': 'test', 'password': '774411'})
    print(form) # 加了这句
    user = form.save()
    

    reply
    0
  • Cancelreply