如何解决 Django 中的 ImportError?

How to Solve ImportError in Django?

我是 django 新手,在从 AbstractUser 模型创建用户时遇到了一些困难。现在我开始怀疑我的用户模型是否没有以正确的方式构建。这是我的所有者模型

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models import CASCADE, BooleanField
from user_app.forms import LoginForm
        
        
class user_type(AbstractUser):
    is_user = models.BooleanField('Is user', default=False)
    is_police = models.BooleanField('Is police', default=False)
    is_insurance = models.BooleanField('Is insurance', default=False)
    is_rto: BooleanField = models.BooleanField('Is rto', default=False)
    
class Owner(models.Model):
    user_id = models.AutoField(primary_key=True)
    login_id = models.ForeignKey(LoginForm, on_delete=models.DO_NOTHING)
    user_name = models.CharField(max_length=255)
    aadhar_number = models.CharField(max_length=16)
    photo = models.FileField()
    mobile = models.IntegerField()
    licence = models.CharField(max_length=10)
    address = models.TextField()
    state = models.CharField(max_length=10)
    district = models.CharField(max_length=10)
    city = models.CharField(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)
    objects = models.Manager()

并且 forms.py 中发生了另一个导入错误。这是我的 form.py

from django import forms
from user_app.models import user_type
    
    
class LoginForm(forms.Form):
    username = forms.CharField(
            widget = forms.TextInput(
                attrs = {
                    "class": "form-control"
                }
            )
        )
    password = forms.CharField(
            widget = forms.PasswordInput(
                attrs = {
                    "class": "form-control"
                }
            )
        )
    
    class Meta:
        model = user_type
        fields = ('username', 'email', 'password1', 'password2', 'is_user','is_insurance', 'is_police', 'is_rto')

当我 运行 这个项目使用 'python manage.py runserver' 然后它显示

 File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py", line 7, in <module>
    from user_app.forms import LoginForm
  File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\forms.py", line 2, in <module>
    from user_app.models import user_type
ImportError: cannot import name 'user_type' from 'user_app.models' (D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py)

在 Owner 模型中,在这一行中:

login_id = models.ForeignKey(LoginForm, on_delete=models.DO_NOTHING)

外键只需要归属于一个模型。但是在您的代码中,有一个与表单关联的 ForeignKey。所以,在这里编写一个模型。在此之后无需导入:

from user_app.forms import LoginForm

因此,它将避免您面临的循环导入错误。