Я новичок в django, и я хочу проверить свой CRUD для класса утверждения, который я сделал, но я обнаружил ошибку:
Трассировка (последний вызов был последним): файл "E: \ Django_Workspace \ berryenroll \ BerryEnroll \ api \ tests.py ", строка 19, в test_add serializer.create (validated_data) Файл" E: \ Django_Workspace \ berryenroll \ BerryEnroll \ api \ serializers.py ", строка 29, в создании validated_data ['имя пользователя' ] = self.context ['request']. user.username KeyError: 'request'
это тестовый класс:
class ApprovalTest(TestCase):
def test_add(self):
validated_data = dict()
validated_data['status'] = 'APPROVED'
validated_data['given_role'] = ['ROLE_ADMIN']
validated_data['asked_role'] = ['ROLE_ADMIN']
serializer = ApprovalRequestSerializer(data=validated_data)
if serializer.is_valid():
print(serializer.data)
serializer.create(validated_data)
else:
print(serializer.errors)
Это модель утверждения с customUser:
matrix_roles = settings.MATRIX_RULES
allowed_roles = list(set([elem.role for elem in matrix_roles])) # Convert to a unique list
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])
STATUS_CHOICES = sorted([(item, item) for item in ["PENDING", "APPROVED", "REJECTED", "CANCELED"]])
ROLE_CHOICES = sorted([(item, item) for item in allowed_roles])
class ApprovalRequest(models.Model):
# TODO: Add caller_id ?
username = models.CharField(blank=True, default='', max_length=255)
status = models.CharField(choices=STATUS_CHOICES, default='PENDING', max_length=100)
creation_date = models.DateTimeField(auto_now_add=True)
created_by = models.CharField(max_length=255, blank=True, default='username')
last_update = models.DateTimeField(null=True)
updated_by = models.CharField(max_length=255, blank=True, null=True)
asked_role = MultiSelectField(choices=ROLE_CHOICES, default=settings.ASKED_DEFAULT_ROLE, max_length=100)
given_role = MultiSelectField(choices=ROLE_CHOICES, default=settings.ASKED_DEFAULT_ROLE, max_length=100)
# given_role = models.CharField(choices=ROLE_CHOICES, default=settings.ASKED_DEFAULT_ROLE, max_length=100)
class Meta:
ordering = ['id']
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('username'), unique=True, max_length=255)
roles = []
objects = None
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def save (self, **kwargs):
"""saving to DB disabled"""
pass
def get_group_permissions (self):
"""If you don't make your own permissions module,
the default also will use the DB. Throw it away"""
return [] # likewise with the other permission defs
def get_and_delete_messages (self):
"""Messages are stored in the DB. Darn!"""
return []
А это ApprovalSerializer:
class ApprovalRequestSerializer(serializers.ModelSerializer):
given_role = fields.MultipleChoiceField(choices=ROLE_CHOICES,required=False)
asked_role = fields.MultipleChoiceField(choices=ROLE_CHOICES,required=False)
class Meta:
fields = '__all__'
model = ApprovalRequest
read_only_fields = ['username', 'creation_date', 'created_by', 'last_update', 'updated_by']
def create(self, validated_data):
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
"""Override default dataform read-only fields"""
validated_data['username'] = self.context['request'].user.username
validated_data['status'] = 'PENDING'
validated_data['created_by'] = self.context['request'].user.username
validated_data['creation_date'] = now
validated_data['updated_by'] = self.context['request'].user.username
validated_data['last_update'] = now
return super(ApprovalRequestSerializer, self).create(validated_data)
def update(self, instance, validated_data):
now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
validated_data['updated_by'] = self.context['request'].user.username
validated_data['last_update'] = now
res = super(ApprovalRequestSerializer, self).update(instance, validated_data)
# Check if the new role is approved, the call the Gateway to update the user role
if 'status' in validated_data.keys():
if validated_data['status'] == 'APPROVED':
logger.info("The role should be updated to %s" % list(validated_data['given_role']))
server_url = settings.BCS_URL
username = settings.BCS_ADMIN_USERNAME
password = settings.BCS_ADMIN_PASSWORD
bcs = System(server_url)
bcs.login_as_admin(username, password)
users = bcs.users()
# Look for my user in the gateway and update it's 'authorities'
for user in users:
if user['login'] == instance.username:
user['authorities'] = list(validated_data['given_role'])
bcs.update_user(user)
# TODO: Log warning if the user does not exist / This case should never happen / Synchro error with gateway
# pass
return res
Я хочу просто протестировать метод создания и обновления, но я не знаю, как добавить контекст ['request'] для его тестирования.