Python Django从models.py导入类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18479134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Import Class From models.py
提问by hanleyhansen
Using a folder structure like this:
使用这样的文件夹结构:
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
How can i import a class in my views.py that is defined in models.py?
如何在models.py 中定义的views.py 中导入一个类?
I've tried:
我试过了:
from . import models.class
from models import class
from projectname.models import class
from projectname import models.class
from project import class
But for all those i get invalid syntax errors
但是对于所有这些我都收到无效的语法错误
views.py
视图.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
模型.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'
error:
错误:
invalid syntax (views.py, line 11)
Exception Type: SyntaxError
Exception Value: invalid syntax (views.py, line 11)
采纳答案by simon
use:
用:
from library.models import MyClass
and you should be good to go :)
你应该很高兴去:)
(the basic structure is from <app>.models import <ModelName>
)
(基本结构是from <app>.models import <ModelName>
)
update:
更新:
the problem is (almost!) certainly that your model begins with '7' -- change it to a letter character, and all will be well, I'm (almost!) sure :)
问题是(几乎!)当然,您的模型以“7”开头 - 将其更改为字母字符,一切都会好起来的,我(几乎!)确定:)
回答by Romans 8.38-39
for example in your models.py
you got :
例如在你models.py
你得到:
from django.db import models
from django.contrib.auth.models import User
class register(models.Model):
user = models.OneToOneField(User)
Then in your views.py
, you can call like this :
然后在您的views.py
,您可以这样调用:
from library.models import register