我有以下单元测试,但无法弄清楚为什么它会失败(如果我删除,测试会通过if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):),但我无法弄清楚如何在它仍然存在的情况下通过测试。
文件测试.py
def test_redirects_after_POST(self):
user = User.objects.create_superuser('username')
self.client.force_login(user)
response = self.client.post(
reverse('page1'), data={
'first_name': 'testuser',
'dob': UnitTest.set_age(20)}
)
self.assertRedirects(response, reverse('page2'))
我试过添加这个,但它没有帮助:
referer = 'http://testserver{}'.format(reverse('page1'))
# Also tried: referer = 'http://testserver{}'.format(reverse('page2'))
response = self.client.post(
reverse('page1'), data={
'first_name': 'testuser',
'dob': UnitTest.set_age(20)}
, HTTP_REFERER=referer)
文件views.py
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page1(request):
if request.method == 'POST':
form = Page1Form(request.POST, request.FILES, instance=request.user.page1)
if form.is_valid():
form.save()
return redirect('page2')
else:
form = Page1Form(instance=request.user.page1)
context = {
'form' : form,
}
return render(request, 'website/page1.html', context)
@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page2(request):
if request.method == 'POST':
form = Page2Form(request.POST, request.FILES, instance=request.user.page2)
if form.is_valid():
form.save()
return redirect('page3')
else:
# redirect if user didnt access the page from page1
if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
return redirect('page1')
else:
form = Page2Form(instance=request.user.page2)
context = {
'form' : form
}
芜湖不芜
相关分类