Я пытаюсь протестировать представление, которое требует, чтобы пользователь вошел в систему и имел роль role = 'Teacher'. Поэтому я настроил свой тестовый случай, создав пользователя, установив role = 'Teacher', сохранив пользователя и войдя в систему.
Проблема в том, что из-за представления current_user = User.objects.get(id=user_id)
не удается получить пользователя, возвращая accounts.models.User.DoesNotExist: User matching query does not exist.
Это мой тест:
class TeacherHomeViewTest(TestCase):
def setUp(self):
user = User.objects.create(
email='john.smith@example.com',
first_name='John',
last_name='Smith',
password='johnpass1'
)
user.role = 'Teacher'
user.save()
self.client.login(email='john.smith@example.com', password='johnpass1')
def test_successfully_create_problem_with_no_description(self):
"""
When a question is provided a problem
is successfully created.
:return: HttpResponse
"""
data = {
'description': '',
'question': 'What is the capital of England?'
}
# Initialize forms.
CreateProblemForm(data)
CreateAssessmentForm()
response = self.client.post('/create-assessment/', data)
qs = Problem.objects.all()
values = '<QuerySet:Problem: What is the capital of England?>'
self.assertQuerysetEqual(qs, values)
self.assertEqual(response.status_code, 200)
Это вид:
def create_assessment(request, assessment_problems=[]):
# Fetch the current user.
user_id = request.user.id
current_user = User.objects.get(id=user_id)
assessments = Assessment.objects.filter(creator__id=user_id).exclude(title='')
# Initialize forms.
create_problem_form = CreateProblemForm()
create_assessment_form = CreateAssessmentForm()
# Create an instance of Assessment
# without saving it (temporary).
current_assessment = Assessment.objects.create(
creator=current_user
)
current_assessment.save()
current_assessment.delete()
# Successfully create problem.
if request.method == 'POST' and 'create-problem' in request.POST:
create_problem_form = CreateProblemForm(request.POST)
if create_problem_form.is_valid():
description = create_problem_form.cleaned_data['description']
question = create_problem_form.cleaned_data['question']
new_problem = Problem.objects.create(
description=description,
question=question,
)
new_problem.save()
assessment_problems.append(new_problem)
# Successfully create an assessment.
if request.method == 'POST' and \
'create-assessment' in request.POST and \
assessment_problems != []:
create_assessment_form = CreateAssessmentForm(request.POST)
if create_assessment_form.is_valid():
for problem in assessment_problems:
problem.assessment = current_assessment
title = create_assessment_form.cleaned_data['title']
if title != '':
current_assessment = Assessment.objects.create(
creator=current_user,
title=title,
)
current_assessment.save()
assessment_problems.clear()
messages.success(request, f'Assessment "{title}" created successfully.')
# When trying to generate an assessment with no title
# a message informs the user that a title must be provided.
if request.method == 'POST' and \
current_assessment.title == '' and \
'create-assessment' in request.POST:
create_assessment_form = CreateAssessmentForm()
messages.error(request, 'You have to give your assessment a title before generating it.')
user_assessments = Assessment.objects.filter(creator=User.objects.get(id=user_id))
template_name = 'create_assessment.html'
context = {
'create_assessment_form': create_assessment_form,
'create_problem_form': create_problem_form,
'user_assessments': user_assessments,
'assessment_problems': assessment_problems,
'assessments': assessments,
}
return render(request, template_name, context)
А это модель пользователя:
class UserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
"""
Creates and saves a User with the given email,
first, last name and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password=None):
"""
Creates and saves a Superuser with the given email,
first, last name and password.
"""
user = self.create_user(
email,
password=password,
first_name=first_name,
last_name=last_name,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
ROLES = [
('Student', 'Student'),
('Teacher', 'Teacher'),
]
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
role = models.CharField(max_length=7, choices=ROLES, verbose_name='I am a...', blank=False, default='Student')
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return '{} {} - user ID: {}'.format(self.first_name, self.last_name, self.id)
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
def __eq__(self, other):
return self.id == other.id
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
Пожалуйста, примите во внимание, что пользователь является пользовательским и работает правильно. Кроме того, мой взгляд работает отлично. (Я только учусь писать тесты, поэтому я предпочел бы, чтобы сначала работал мой взгляд, а затем писать тесты.)
Вопрос в том, почему это происходит? И как я могу решить проблему? Надеюсь, что для новичка это не слишком сложно.