简体   繁体   中英

Django Import Class From models.py

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)

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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