1

我使用 user.userprofile 中的信息来管理权限。

我如何使用它:

# List of status
STATUS_CHOICES = (
    ('teacher', 'Teacher'),
    ('student', 'Student'),
)

# More field for an user.
class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='student')

现在,在一个视图中,我有一个例子:

# Only the owner view this template
if request.user.userprofile.status != 'teacher':
    return redirect('Penelope.views.home')

我要如何测试:

def login_function(self, username, password, status):
    # Create a new user
    user = User.objects.create_user(username=username, password=password)
    user.userprofile.status = status
    user.save()

    # Use test client to perform login
    user = self.client.login(username=username, password=password)
    response = self.client.post('/login/')

class LoggedAsTeacherCase(TestCase):
    def setUp(self):
        # I create and log with a teacher user
        login_function(self, 'teststudent', 'password', 'teacher') 

    def test_login(self):  # Verify if login has been validated by server
        response = self.client.get('/login/')
        self.assertRedirects(response, '/')   # <<< It is ok (My user is detected as connected, he is redirected)

    def test_dashboard(self): 
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)   # <<< It is ok (Confirmation, my user is not redirected to login url, perfect)

    def test_newcourse(self):
        response = self.client.get('/newcourse/')
        self.assertEqual(response.status_code, 200)   # <<<  /!\ It is false, I have a redirection (302), not a 200...

因此,这意味着当视图测试用户是否是老师时(参见:我的主题的顶部),它发送了 False...

如何访问这些信息并进行测试?

4

2 回答 2

2

您对status字段的定义不正确。CharFields 需要一个正整数的“max_length”属性。

将其更改为以下内容:

models.CharField(max_length=..., choices=STATUS_CHOICES)

另请参阅此处

于 2012-08-24T15:07:53.080 回答
0

我发现了问题!

user = User.objects.create_user(username=username, password=password)
user.userprofile.status = status
user.save()

当我这样做时,我想user = User.objects.create_user(username=username, password=password)返回一个用户(假)。

所以,我必须提出一个要求:

user = User.objects.create_user(username=username, password=password)
test = UserProfile.objects.filter(user=username)
test.status = status
test.save()

没关系!

于 2012-09-02T19:45:30.883 回答