Django Import Class From models.py

2020-07-22 16:40发布

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?

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

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'

error:

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

2条回答
乱世女痞
2楼-- · 2020-07-22 16:44

for example in your models.py you got :

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 :

from library.models import register
查看更多
祖国的老花朵
3楼-- · 2020-07-22 16:51

use:

from library.models import MyClass

and you should be good to go :)

(the basic structure is 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 :)

查看更多
登录 后发表回答