简体   繁体   English

无法导入名称X

[英]Cannot Import Name X

Currently trying to create a Models.py file for my Django project to be able to store questions in a database. 当前正在尝试为我的Django项目创建一个Models.py文件,以便能够在数据库中存储问题。

But every time i reference the model in my forms.py for the Meta Class I receive an import error. 但是每次我在forms.py中为元类引用模型时,都会收到导入错误。

forms.py forms.py

from django import forms
from django.contrib.auth.models import User
from .models import Q1  

Question1_CHOICES = (
    ('1', 'I Like Smoking'),
    ('2', 'I Dislike Smoking'),
    ('3', 'I Do not Smoke'),
    ('4', 'I Do not mind Smokers '),
)

class QuestionForm(forms.Form):
    Q1 = forms.MultipleChoiceField(
         required=False,
         widget=forms.RadioSelect,
         choices=Question1_CHOICES
    )

    class Meta:
        model = Q1
        fields = ['question']
        widgets = {
            'question': forms.RadioSelect()
        }

Models.py Models.py

from django.db import models
from .forms import Question1_CHOICES

class Q1(models.Model):
    question = models.CharField(max_length=50, choices=Question1_CHOICES)

My Error is as follows 我的错误如下

File "forms.py", line 3, in from .models import Q1 从.models导入Q1中的文件“ forms.py”,第3行

Any help would be really appreciated as I'm stumped what it could be 任何帮助将不胜感激,因为我很困惑

You have a circular import 您有循环进口

forms.py is importing models.py Forms.py正在导入models.py

models.py is importing forms.py models.py正在导入Forms.py

I would recommend moving Question1_CHOICES into models.py. 我建议将Question1_CHOICES移到models.py中。 Follow the docs as an example https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices 遵循文档作为示例https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices

Try this 尝试这个

Models.py Models.py

from django.db import models  

Question1_CHOICES = ( ('1', 'I Like Smoking'), ('2', 'I Dislike Smoking'), ('3', 'I Do not Smoke'), ('4', 'I Do not mind Smokers '), )

class Q1(models.Model): 
    question = models.CharField(max_length=50, choices=Question1_CHOICES)

Forms.py Forms.py

from django import forms 
from django.contrib.auth.models import User 
from .models import Q1, Question1_CHOICES  

class QuestionForm(forms.Form): 
    q1 = forms.MultipleChoiceField( required=False, widget=forms.RadioSelect, choices=Question1_CHOICES ) 
    class Meta: 
        model = Q1 fields = ['question'] 
        widgets = { 'question': forms.RadioSelect() }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM