我正在尝试为创建事件模型对象的视图编写测试。事件模型包含foreignKey字段,该字段引用auth用户作为模型对象的创建者。在测试中我尝试登录用户,我假设会将request.user设置为登录的用户。正在测试的视图在创建事件时引用request.user,通过ajax正常触发时工作正常但是当我运行时测试我一直得到以下错误。此外,我尝试在测试函数中创建用户,而不是引用在" class.setupTestData()"中创建的用户,同样的错误。
错误
ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x108ae9cc0>>": "Event.creator" must be a "User" instance.
模型
class Event(models.Model):
name = models.CharField(max_length=200)
event_type = models.CharField(max_length=200, null=True)
creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
attendees = models.ManyToManyField(User, related_name='attendees')
start_date = models.DateField(null=True)
start_time = models.TimeField(null=True)
end_date = models.DateField(null=True)
end_time = models.TimeField(null=True)
location = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
description = models.TextField()
def __str__(self):
return self.name
视图
def createEvent(request):
# dec vars
event_title = str(request.POST['event-title']).title()
event_type = str(request.POST['event-type'])
event_location = str(request.POST['event-location'])
event_description = str(request.POST['event-description'])
event_start_date = str(request.POST['event-start-date'])
event_start_time = str(request.POST['event-start-time'])
event_end_date = str(request.POST['event-end-date'])
event_end_time = str(request.POST['event-end-time'])
creator = request.user
# create event
Event.objects.create(
name=event_title,
event_type=event_type,
creator=creator,
location=event_location,
description=event_description,
start_date=event_start_date,
start_time=event_start_time,
end_date=event_end_date,
end_time=event_end_time
)
# #create response
response = {
'status': 'success',
}
# send reponse JSON
return JsonResponse(response)
测试
def test_create_event(self):
today = timezone.now()
user = User.objects.get(pk=1)
# login user
self.c.login(username=user.username, password=user.password)
# Check event create
response = self.c.post('/event/create/', {
'event-title': 'test create event',
'event-type': 'combat',
'event-location': 'ltt 9455',
'event-description': lorem.paragraph,
'event-start-date': today.date(),
'event-end-date': today.date(),
'event-end-time': today.time(),
'event-start-time': today.time()
})
self.assertTrue()
答案 0 :(得分:1)
user.password
是哈希密码,因此当您致电client.login()
您可以在致电login
user = User.objects.get(pk=1)
self.client.login(username=user.username, password='actual_password')
或者您可以改为使用client.force_login()
,而不需要密码。
user = User.objects.get(pk=1)
self.client.force_login(user)
请注意,您的失败测试已发现您的视图存在问题。如果匿名用户使用该视图,ValueError
将导致500服务器错误。最简单的解决方法是使用login_required
装饰器。
from django.contrib.auth.decorators import login_required
@login_required
def createEvent(request):
...