擅长:python、mysql、java
<p>您还可以将<code>HttpRequest</code>子类化,并显式地将子类上的<code>user</code>字段设置为将类型显式定义为<code>User</code>,而不是默认的联合对,如下所示:</p>
<pre><code>from django.http import HttpRequest
from my_user_app.models import MyUser
class AuthenticatedHttpRequest(HttpRequest):
user: MyUser
</code></pre>
<p>然后,每当您想要使用<code>login_required</code>装饰器时,将<code>request</code>参数的类型提示设置为您的子类(在本例中是<code>AuthenticatedHttpRequest</code>),如下所示:</p>
<pre><code>@login_required
def view(request: AuthenticatedHttpRequest) -> HttpResponse:
if not request.user.some_attribute:
return redirect("somewhere")
return render(request, "template_name")
</code></pre>
<p>此方法在<a href="https://github.com/typeddjango/django-stubs#how-can-i-create-a-httprequest-thats-guaranteed-to-have-an-authenticated-user" rel="nofollow noreferrer">^{<cd7>} readme file</a>中指定为推荐的方法,显然您正在使用该方法为<code>mypy</code>获取Django骨骼</p>