Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Code & Django: Error when importing User model

Edit: Still have this issue.

Visual Studio Code throws the following error:

User model imported from django.contrib.models

The error appears in line 2 of the following script (models.py). The code is from a Django tutorial and works fine. But it is annoying that Visual Studio Code (Pylint) throws an error (and marks the script red).

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

# Create your models here.


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Also VSC throws an error when importing a custom model, e.g. Post.

from app_blog.models import Post.

The error: Unable to import 'app_blog.models'

My setup:

  • Win10
  • Virtual Enviroment (Python, Django, Pylint, ...)
  • Django 3.1.1
  • Python 3.8.5
  • Pylint Django
  • VSC runs Python in my VENV

Pylint settings:

"python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
"python.linting.pylintUseMinimalCheckers": true

There are the following interpreter, Interpreter No. 2 is selected.

  1. Python 3.8.3 64-bit ('base': conda), ~\Anaconda3\python.exe
  2. Python 3.8.5 64-bit('venv'), .\venv\Scripts\python.exe
  3. Python 3.8.5 64-bit, ~\AppData\Local\Programs\Python\Python38\python.exe
like image 384
michaelT Avatar asked Mar 02 '23 02:03

michaelT


2 Answers

This is late but you can always run the following in your terminal

pip install pylint-django

and add this to settings.json file found in .vscode folder (assuming you're using vscode)

 "python.linting.pylintArgs": [
    "--load-plugins",
    "pylint_django",
    "--errors-only",
    "--load-plugins pylint_django"
]

Hope this works for you!

like image 149
paul iyinolu Avatar answered Mar 04 '23 15:03

paul iyinolu


For the first problem with the User, I've encountered a similar problem not sure if it's the same as yours, but I resolved it like this

  1. in models.py insted of from django.contrib.auth.models import User, I used

     from django.conf import settings
    
  2. in the line:

     author = models.ForeignKey(User, on_delete=models.CASCADE)"
    

    I replaced it with:

     author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    

    Accordind to the docs https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.get_user_model

like image 36
taha maatof Avatar answered Mar 04 '23 16:03

taha maatof