[英]Test a Django model that uses request.user in save_model
I have a Django model that overrides save_model
in order to automatically save the current authenticated user into a field on save.我有一个 Django model 覆盖save_model
以便在保存时自动将当前经过身份验证的用户保存到字段中。
The question is, how in a unit test can I test the creation of this model, without having to go through a view?问题是,如何在单元测试中测试这个 model 的创建,而不必通过视图 go?
The model: model:
class SomeClass(models.Model):
def save_model(self, request, obj, form, change):
self.prevent_update()
if not obj.pk:
# Only set added_by during the first save.
obj.created = request.user
super().save_model(request, obj, form, change)
The test just wants to set up SomeClass
before doing some other stuff.测试只是想在做一些其他事情之前设置SomeClass
。
class SomeClassTestCase(TestCase):
def setUp(self):
self.assertTrue(request.user)
SomeClass.objects.create(name="abc")
I know that there is a request getting set up automatically, since request.user
doesn't fail with request
being None
;我知道有一个请求会自动设置,因为request.user
不会因为request
为None
而失败; instead, the query constraint fails because the user is null.相反,查询约束失败,因为用户是 null。 How do I set a user on the request that appears to have been passed into save_model
如何在似乎已传递到save_model
的请求上设置用户
Alternatively, I know I can setup a request using RequestFactory
and generate a user.或者,我知道我可以使用RequestFactory
设置请求并生成用户。 In that case, how do I get that into the test so that the SomeClass.objects.create
actually sees it.在这种情况下,我如何将其纳入测试,以便SomeClass.objects.create
实际看到它。
Thanks to the comments, I realised that I had copied and pasted badly, placing save_model
into a model.感谢评论,我意识到我复制和粘贴得很糟糕,将save_model
放入 model 中。 This and my amateurish abilities with Django caused all kinds of confusion.这和我对 Django 的业余能力造成了各种混乱。 So the fact that request.user
was not failing was because it was never called.所以request.user
没有失败的事实是因为它从未被调用过。
I am now correctly overriding the save
method in the model, and the save_model
method in the admin, which passes the correct details to the model for it to save.我现在正确地覆盖了 model 中的save
方法和管理员中的save_model
方法,它将正确的详细信息传递给 model 进行保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.