【问题标题】:Django Import Class From models.pyDjango 从models.py 导入类
【发布时间】:2013-08-31 00:13:11
【问题描述】:

使用这样的文件夹结构:

library/
-django.wsgi
-manage.py
-static/
    --all my static files
-library/
    --__init__.py
    --models.py
    --settings.py
    --urls.py
    --views.py
    --wsgi.py
    --templates/
        ---where i plan to store all my templates

如何在我的views.py 中导入models.py 中定义的类?

我试过了:

from . import models.class

from models import class

from projectname.models import class

from projectname import models.class

from project import class

但是对于所有这些我都会遇到无效的语法错误

views.py

from django.core.context_processors import csrf
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.contrib import messages
from django.template import RequestContext, loader
from django.contrib.auth import logout

from library.models import 7DTagmap

models.py

from __future__ import unicode_literals

from django.db import models

class 7DTagmap(models.Model):
   id = models.IntegerField(primary_key=True)
    tag_id = models.CharField(max_length=50L)
    st_tag_id = models.IntegerField()
    class Meta:
        db_table = '7d_tagmap'

错误:

invalid syntax (views.py, line 11)
Exception Type: SyntaxError
Exception Value:    invalid syntax (views.py, line 11)

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

    使用:

    from library.models import MyClass
    

    你应该很高兴:)

    (基本结构为from <app>.models import <ModelName>

    更新:

    问题是(几乎!)您的模型肯定以“7”开头 - 将其更改为字母字符,一切都会好起来的,我(几乎!)肯定:)

    【讨论】:

    • 我并没有真正的项目应用程序结构。只是一个项目。
    • 你确实......你有一个名为library的项目,其中有一个名为library的应用程序......
    • 好吧,我明白你的意思了。所以这应该有效: from library.models import 7DTagmap 但它没有,所以我一定错过了一些东西。
    • 在 Python 中 - 任何标识符(变量或类名)只能以字母或下划线开头_
    • 它不只是 PEP8,它在 lexer for python
    【解决方案2】:

    例如在你的models.py 中你得到了:

    from django.db import models
    from django.contrib.auth.models import User
    
    class register(models.Model):  
        user = models.OneToOneField(User)
    

    然后在你的views.py,你可以这样调用:

    from library.models import register
    

    【讨论】:

    • 试过这个:from library.models import 7DTagmap 没有用
    • 我使用了 djangos inspectdb 并将其生成为类名
    • 错误添加到问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多