Visual Studio Code 和 Django:导入用户模型时出错

mic*_*elT 5 django pylint django-models visual-studio-code

编辑:仍然有这个问题。

Visual Studio Code 抛出以下错误:

User model imported from django.contrib.models

该错误出现在以下脚本 ( models.py) 的第 2 行中。该代码来自 Django 教程,运行良好。但令人烦恼的是 Visual Studio Code ( Pylint ) 会抛出错误(并将脚本标记为红色)。

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
Run Code Online (Sandbox Code Playgroud)

此外,VSC 在导入自定义模型时会引发错误,例如Post.

from app_blog.models import Post

错误:无法导入“app_blog.models”

我的设置:

  • WIN10
  • 虚拟环境(Python、Django、Pylint...)
  • 姜戈3.1.1
  • Python 3.8.5
  • 皮林特·姜戈
  • VSC 在我的 VENV 中运行 Python

皮林特设置:

"python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
        "--errors-only"
    ],
"python.linting.pylintUseMinimalCheckers": true
Run Code Online (Sandbox Code Playgroud)

有以下翻译员,选择2号翻译员。

  1. Python 3.8.3 64 位('base':conda),~\Anaconda3\python.exe
  2. Python 3.8.5 64 位('venv'),.\venv\Scripts\python.exe
  3. Python 3.8.5 64 位,~\AppData\Local\Programs\Python\Python38\python.exe

tah*_*tof 3

对于用户的第一个问题,我遇到了类似的问题,不确定是否与你的相同,但我是这样解决的

  1. 在 models.py 中from django.contrib.auth.models import User,我使用了

     from django.conf import settings
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在行中:

     author = models.ForeignKey(User, on_delete=models.CASCADE)"
    
    Run Code Online (Sandbox Code Playgroud)

    我将其替换为:

     author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    
    Run Code Online (Sandbox Code Playgroud)

    根据文档https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#django.contrib.auth.get_user_model