3

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 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

8 Comments

I don't really have a project app structure though. Just a project.
you do... you have a project named library, and within it an app named library...
Ok i see what you mean. So this should work: from library.models import 7DTagmap but it doesn't so i must be missing something.
In Python - any identifier (variable or class name), can only begin with a letter or an underscore _
Its not just PEP8, its in the lexer for python
|
3

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 Comments

Tried this: from library.models import 7DTagmap and that didn't work
I used djangos inspectdb and it generated that as the class name
Error added to question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.