You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 4.2.2导入错误:无法从django.contrib.auth.models导入Students

Django 4.2.2 运行项目时出现导入错误

错误信息

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Python39\lib\threading.py", line 950, in _bootstrap_inner
    self.run()
  File "C:\Python39\lib\threading.py", line 888, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run
    self.check(display_num_errors=True)
  File "C:\Python39\lib\site-packages\django\core\management\base.py", line 485, in check
    all_issues = checks.run_checks(
  File "C:\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check
    for pattern in self.url_patterns:
  File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked       
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed     
  File "C:\Users\admin\Desktop\runapp\amsdjangocrud\urls.py", line 23, in <module>
    path('', include('amsapps.urls')),
  File "C:\Python39\lib\site-packages\django\urls\conf.py", line 38, in include    
    urlconf_module = import_module(urlconf_module)
  File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked       
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed     
  File "C:\Users\admin\Desktop\runapp\amsapps\urls.py", line 2, in <module>
    from . import views
  File "C:\Users\admin\Desktop\runapp\amsapps\views.py", line 4, in <module>       
    from django.contrib.auth.models import Students
ImportError: cannot import name 'Students' from 'django.contrib.auth.models' (C:\Python39\lib\site-packages\django\contrib\auth\models.py)

项目代码片段

models.py

from django.forms import ModelForm, Textarea
from django.db import models

class Students(models.Model):
    student_id = models.IntegerField(primary_key=True)
    id_number = models.IntegerField(blank=True, null=True)
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    gender = models.CharField(max_length=50)
    address = models.CharField(max_length=200)
    contact = models.IntegerField(blank=True, null=True)
    course = models.CharField(max_length=50)

    def __str__(self):
        return f'{self.course}, {self.contact}, {self.address}, {self.gender}, {self.lastname}, {self.firstname}, {self.id_number}, {self.student_id},'

class Assignment(models.Model):
    assignment_id = models.IntegerField(primary_key=True)
    assignment_name = models.CharField(max_length=50)
    instructor = models.ForeignKey('Instructor',on_delete=models.CASCADE)
    status = models.ForeignKey('Status',on_delete=models.CASCADE)
    subject = models.ForeignKey('Subject',on_delete=models.CASCADE)

    
    class Meta:
        managed = True
        db_table = 'assignment'

class Instructor(models.Model):
    instructor_id = models.IntegerField(primary_key=True)
    firstname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)

    class Meta:
        managed = True
        db_table = 'instructor'

views.py(导入及相关函数)

from django.contrib.auth.models import Students
from django.contrib.auth.models import Assignment

def main(request, id):
    joined_data = Assignment.objects.get(id>=1)
    return render(request, 'amsapp/main.html', {'data': joined_data })

admin.py(导入尝试)

from .models import (
    Assignment,
    Instructor,
    Student,
    Subject
)

问题解决步骤

  1. 修正模型导入路径
    views.py错误地从django.contrib.auth.models导入自定义模型,该模块是Django自带的认证模型库,没有你定义的Students和Assignment。需从当前app的models导入:

    # views.py 修正后
    from .models import Students, Assignment
    
  2. 修正admin.py的导入错误

    • 模型类名是Students,但admin里写的是Student,名称不匹配;
    • Subject模型在models.py中未定义,需删除该导入,或在models.py中补充定义Subject和Status模型(Assignment模型关联了这两个)。
      修正后的admin.py:
    from .models import (
        Assignment,
        Instructor,
        Students
    )
    
  3. 修正views中查询语句错误
    Assignment.objects.get(id>=1)会报错,get()用于获取单个对象,不能使用范围条件。若要获取所有id>=1的Assignment数据,改用filter():

    def main(request, id):
        # 注意:Assignment模型主键是assignment_id,不是默认id,需用assignment_id__gte
        joined_data = Assignment.objects.filter(assignment_id__gte=1)
        return render(request, 'amsapp/main.html', {'data': joined_data })
    

    函数参数id未被使用,可根据需求删除或合理利用。

  4. 补充缺失的模型
    Assignment模型关联了Status和Subject,但models.py中无这两个模型的定义,需补充:

    # 在models.py中添加
    class Status(models.Model):
        status_id = models.IntegerField(primary_key=True)
        status_name = models.CharField(max_length=50)
    
        class Meta:
            managed = True
            db_table = 'status'
    
    class Subject(models.Model):
        subject_id = models.IntegerField(primary_key=True)
        subject_name = models.CharField(max_length=50)
    
        class Meta:
            managed = True
            db_table = 'subject'
    

    补充后执行迁移命令:python manage.py makemigrations和python manage.py migrate

内容的提问来源于stack exchange,提问作者TryoutProgrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:02:31