Search code examples
pythondjangopycharm

pyCharm warning in django code: Unresolved attribute reference 'user' for 'WSGIRequest'


in my brandnew PyCharm professional edition I get the warning "Unresolved attribute reference 'user' for 'WSGIRequest'". The warning occurs in the first line of MyClass.post() (see code below).

from django.views import generic
from django.db import models
from django.http.request import HttpRequest
from django.shortcuts import render
from django.contrib.auth.models import AbstractUser


class CustomUser( AbstractUser ):
    emailname = models.CharField()


class Invoice( models.Model ):
    posted = models.DateField()


class BaseView ( generic.DetailView ):

    model = Invoice

    def __int__( self, *args, **kwargs ):
        super().__init__( *args, **kwargs )
        # some more code


class MyClass( BaseView ):

    def __int__( self, *args, **kwargs ):
        super().__init__( *args, **kwargs )
        # some more code

    def post( self, request: HttpRequest, *args, **kwargs ):
        context = { 'curr_user': request.user, } # <-- Unresolved attribute reference 'user' for class 'WSGIRequest'
        # some more code
        html_page = 'mypage.html'
        return render( request, html_page, context )

user ist a CustomUser object. Debugging shows, that user is a known attribute in CustomUser and the code works well, 'curr_user' in context is the expected one. Other attributes of request like request.path or request.REQUEST are not warned. Django support is enabled.

I work with PyCharm 2023.2.5 (Professional Edition), Windows 11

Can anybody help? What is my mistake?

Regards


Solution

  • request.user is not necessarily a thing for all requests (it depends on you having a middleware that injects it), hence it's not shown as necessarily existing.

    If you need it to, you can of course add a

    class HttpRequestWithUser(HttpRequest):
        user: CustomUser
    

    class that you use for your type annotations.