问题
I'm trying to get close to 100% test coverage and I've come across a 403 error in a test on Django-Admin features, as follows:
class AdminTest(LiveServerTestCase):
def setUp(self):
self.client = Client()
self.my_admin = User(username='user', is_staff=True)
self.my_admin.set_password('password')
self.my_admin.save()
(...)
def testCreatePost(self):
self.client.get('/admin/', follow=True)
loginResponse = self.client.login(username='user',password='password')
self.assertTrue(loginResponse)
response = self.client.get('/admin/blog/post/add/', follow=True)
self.assertEqual(response.status_code, 200)
The error occurs on the last line:
self.assertEqual(response.status_code, 200)
AssertionError: 403 != 200
Logging in manually to the client.get
URL works. Parts of the test that pass make it clear that I can log into the admin page, yet, I cannot access the Post model's 'add' page.
回答1:
Setting is_staff=True
allows you to access the admin. It does not let you access all admin pages automatically. You need the 'add blog post' permission to be able to access the page to add blog posts.
The easiest option would be to create a superuser, then they would have permissions to access the page.
self.my_admin = User(username='user', is_staff=True, is_superuser=True)
self.my_admin.set_password('password')
self.my_admin.save()
Using the create_superuser password, this simplifies to:
self.my_admin = User.objects.create_superuser('user', email=None, password='password')
Or you could manually add the required permission to the user (or a group that the user belongs to).
from django.contrib.auth.models import User, Permission
self.my_admin = User(username='user', is_staff=True)
permission = Permission.objects.get(content_type__model='blog', codename='add_blog')
self.my_admin.user_permissions.add(permission)
来源:https://stackoverflow.com/questions/37188822/django-forbidden-httpresponse-in-test-drive