这是用于将数据发送到视图的形式:
class RegisterForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': _('User Name')
}))
password = forms.CharField(widget=forms.PasswordInput(attrs={
'class': 'form-control',
'placeholder': _('Password')
}))
roles = forms.ModelChoiceField(queryset=Role.objects.exclude(role_name="Admin"), widget=forms.Select(attrs={
'class': 'form-control',
}))
这是正在使用其中的表单进行测试的视图:
def register(request):
user = request.user
current_user = CustomUser.objects.get(username=user.username)
if current_user.role.role_name == "Admin":
register_form = RegisterForm(request.POST)
if request.method == "POST":
if register_form.is_valid():
username = register_form.cleaned_data['username']
password = register_form.cleaned_data['password']
role = register_form.cleaned_data['roles']
if CustomUser.objects.filter(username=username).exists():
messages.error(request, _('Username already exists.'))
else:
new_user = CustomUser.objects.create_user(username=username, password=password, role=role)
messages.success(request, _('User created Successfully'))
return redirect("user_details", pk=new_user.pk)
else:
register_form = RegisterForm(request.POST)
context = {
'register_form': register_form,
}
return render(request, 'register.html', context)
else:
messages.error(request, _('You are not allowed to view this page.'))
return redirect('index')
以下是我尝试通过发送带有数据的 post 请求 (reverse
( 来测试它的方法:
def test_post_request_correct_date(self):
call_command("start_app")
self.client.login(username='user', password='pass')
waiter_role = Role.objects.get(role_name="Waiter")
url = reverse('register')
data = {
'username': 'new_user',
'password': 'just good password',
'roles': waiter_role.pk
}
response = self.client.post(url, data, follow=True)
self.assertEqual(response.status_code, 302)
new_user = CustomUser.objects.get(username="new_user")
self.assertRedirects(response, reverse('user_details', args={"pk": new_user.pk}))
self.assertTemplateUsed(response, 'user_profile.html')
请注意,call_command("start_app")
是创建自定义命令,用于创建我从中选择的角色。
我收到此错误:
self.assertEqual(response.status_code, 302)
AssertionError: 200 != 302
我不是这方面的专家,但我相信如果您在帖子中设置follow=true
,响应中的status_code
将设置为redirect_chain
最后一个元素的status_code
- 即 200。
这基本上就是断言重定向检查的内容,所以我认为这里的status_code"手动"检查
self.assertEqual(response.status_code, 302)
是不必要的,可以删除。