Cant import models.py in views.py - python

I want to use my model file from my database by importing it in views.py. But I get an error when I call a class from models.py.
ERROR: ImportError: cannot import name Vehicle
My path:
+ vehicle
---> __init__.py
---> models.py
---> views.py
vehicle/models.py
from __future__ import unicode_literals
from django.db import models
class Vehicle(models.Model):
id = models.BigAutoField(primary_key=True)
plate = models.TextField()
driver = models.ForeignKey(Driver, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'vehicle'
Vehicle/views.py
from vehicle.models import Vehicle
s = Vehicle.objects.all()
print s

If you are calling model in view, you can call it directly
from model import Vehicles
If you want to have a full path, you can add the location of vehicles on your Path
import sys
sys.path.insert(0, 'path_to_vehicle_folder')
from vehicles.model import Vehicles
The way you are doing now, assumes that your execution happens outside vehicles directlory
vehicles\
__init__.py
model.py
view.py
this.py
In this.py you can import as you did.
You can always execute print(sys.path), to see where your python is going to look for packages/modules :) with the sys.path.insert, we add a location we want to include when looking for modules. There exists better ways :)

Related

Circular imports django

I have wrote this code in my models.py file.
As you see the code, I have a class called File and also I have imported in models.py the same class.
Now it gives me this error while migration:
Cannot import name "File" from 'uploadapp.models'
I understand it's the error for circular (recursive) import. But how can I solve this?
from django.db import models
from .models import File
class File(models.Model):
file = models.FileField(blank=False, null=False)
def __str__(self):
return self.file.name
You remove the from .models import File. It makes no sense to import the module in the same module:
from django.db import models
# from .models import File
class File(models.Model):
file = models.FileField(blank=False, null=False)
def __str__(self):
return self.file.name

Django Cannot find module i'm importing my model from

I'm trying to import a model from another Django app in my project. However, when I try to import, I keep getting an error for:
ImportError No module named trunk.profiles.models.
However, when I cmnd click on the model on my IDE it takes me to the model. So it recognizes where the model is coming from, but I think for some reason Django is not recognizing the path.
Here is my code from my models.py which I'm trying to import another model, Profiles from a different Django app:
from django.db import models
from trunk.profiles.models import Profiles # source of error
class ContentObject(models.Model):
course_name = models.CharField(max_length15)
course_topic = models.CharField(max_length = 30)
op_UserName = models.ForeignKey(Profiles)
Add trunk.profiles to Your INSTALLED_APPS
settings.py
INSTALLED_APPS = [
...
'trunk.profiles'
]
TIP
Instead of import model, specify a model with the full application label
from django.db import models
class ContentObject(models.Model):
course_name = models.CharField(max_length15)
course_topic = models.CharField(max_length = 30)
op_UserName = models.ForeignKey('trunk.profiles.Profiles')

Django get_models with models/__init.py__

I'm having a problem using get_model and get_models in django
I have several models under models/
models/blog.py
models/tags.py
models/users.py
models/comments.py
models/category.py
And a models/__init.py__
from myapp.models.blog import *
from myapp.models.tags import *
from myapp.models.users import *
from myapp.models.comments import *
from myapp.models.category import *
However in my views.py I have some code to use get_model
from django.db.models.loading import get_model
blog_class = get_model('myapp', 'blog') #Returns none
When I try get_models('myapp') it returns an empty list.
I also tried
print(get_app('myapp'))
Which returns:
<module 'myapp.models' from '/var/www/myapp/models/__init__.pyc'>
And if I try to iterate over it
for model in get_models(get_app('myapp')):
print(model)
It does nothing. Is there anything I'm missing or failing to spot?
Because you haven't defined your models in the app's models.py, you must explicitly set the app_label option for each model.
class Blog(models.Model):
title = models.CharField(max_length=30)
...
class Meta:
app_label = 'myapp'

The model FlatPage is already registered

I'm attempting to work my way through Practical Django Projects. It seems to be a bit old, but I've manage to convert the code up to this point.
At this point the book would like me to change my models.py to be this:
class SearchKeyword(models.Model)
keyword = models.CharField(maxlength=50, core=True)
page = models.ForeignKey(FlatPage, edit_inline=models.STACKED,
min_num_in_admin=3, num_extra_on_change=1)
I know that this is now done in the admin.py instead. So my models.py looks like this:
from django.db import models
from django.contrib.flatpages.models import FlatPage
class SearchKeyword(models.Model):
keyword = models.CharField(max_length=50)
page = models.ForeignKey(FlatPage)
class Admin:
pass
def __unicode__(self):
return self.keyword
And the admin.py I've created now looks like this:
from search.models import SearchKeyword
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
class SearchKeywordInline(admin.StackedInline):
model = SearchKeyword
extra = 3
class FlatPageAdmin(admin.ModelAdmin):
model = FlatPage
inlines = [SearchKeywordInline]
admin.site.register(FlatPage, FlatPageAdmin)
When I load the Admin page, I receive:
AlreadyRegistered at /admin/
The model FlatPage is already registered
Exception Value:The model FlatPage is already registered
Thank you!
You have to unregister it first as the app itself ships with an admin.py
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)

Split models.py into several files

I'm trying to split the models.py of my app into several files:
My first guess was do this:
myproject/
settings.py
manage.py
urls.py
__init__.py
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
views.py
__init__.py
models/
__init__.py
model3.py
model4.py
This doesn't work, then i found this, but in this solution i still have a problem, when i run python manage.py sqlall app1 I got something like:
BEGIN;
CREATE TABLE "product_product" (
"id" serial NOT NULL PRIMARY KEY,
"store_id" integer NOT NULL
)
;
-- The following references should be added but depend on non-existent tables:
-- ALTER TABLE "product_product" ADD CONSTRAINT "store_id_refs_id_3e117eef" FOREIGN KEY ("store_id") REFERENCES "store_store" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "product_product_store_id" ON "product_product" ("store_id");
COMMIT;
I'm not pretty sure about this, but i'm worried aboout the part The following references should be added but depend on non-existent tables:
This is my model1.py file:
from django.db import models
class Store(models.Model):
class Meta:
app_label = "store"
This is my model3.py file:
from django.db import models
from store.models import Store
class Product(models.Model):
store = models.ForeignKey(Store)
class Meta:
app_label = "product"
And apparently works but i got the comment in alter table and if I try this, same thing happens:
class Product(models.Model):
store = models.ForeignKey('store.Store')
class Meta:
app_label = "product"
So, should I run the alter for references manually? this may bring me problems with south?
For anyone on Django 1.9, it is now supported by the framework without defining the class meta data.
https://docs.djangoproject.com/en/1.9/topics/db/models/#organizing-models-in-a-package
NOTE: For Django 2, it's still the same
The manage.py startapp command creates an application structure that includes a models.py file. If you have many models, organizing them in separate files may be useful.
To do so, create a models package. Remove models.py and create a myapp/models/ directory with an __init__.py file and the files to store your models. You must import the models in the __init__.py file.
So, in your case, for a structure like
app1/
views.py
__init__.py
models/
__init__.py
model1.py
model2.py
app2/
views.py
__init__.py
models/
__init__.py
model3.py
model4.py
You only need to do
#myproject/app1/models/__init__.py:
from .model1 import Model1
from .model2 import Model2
#myproject/app2/models/__init__.py:
from .model3 import Model3
from .model4 import Model4
A note against importing all the classes:
Explicitly importing each model rather than using from .models import * has the advantages of not cluttering the namespace, making code more readable, and keeping code analysis tools useful.
I'd do the following:
myproject/
...
app1/
views.py
__init__.py
models.py
submodels/
__init__.py
model1.py
model2.py
app2/
views.py
__init__.py
models.py
submodels/
__init__.py
model3.py
model4.py
Then
#myproject/app1/models.py:
from submodels/model1.py import *
from submodels/model2.py import *
#myproject/app2/models.py:
from submodels/model3.py import *
from submodels/model4.py import *
But, if you don't have a good reason, put model1 and model2 directly in app1/models.py and model3 and model4 in app2/models.py
---second part---
This is app1/submodels/model1.py file:
from django.db import models
class Store(models.Model):
class Meta:
app_label = "store"
Thus correct your model3.py file:
from django.db import models
from app1.models import Store
class Product(models.Model):
store = models.ForeignKey(Store)
class Meta:
app_label = "product"
Edited, in case this comes up again for someone:
Check out django-schedule for an example of a project that does just this.
https://github.com/thauber/django-schedule/tree/master/schedule/models
https://github.com/thauber/django-schedule/
I've actually come across a tutorial for exactly what you're asking about, you can view it here:
https://web.archive.org/web/20190331105757/http://paltman.com/breaking-apart-models-in-django/
One key point that's probably relevant - you may want to use the db_table field on the Meta class to point the relocated classes back at their own table.
I can confirm this approach is working in Django 1.3
The relevant link for Django 3 is:
https://docs.djangoproject.com/en/3.2/topics/db/models/#organizing-models-in-a-package
Links to previous versions of documentation are broken. The example there is very succinct:
To do so, create a models package. Remove models.py and create a myapp/models/ directory with an init.py file and the files to store your models. You must import the models in the init.py file.
For example, if you had organic.py and synthetic.py in the models directory:
from .organic import Person
from .synthetic import Robot
Easiest Steps :
Create model folder in your app (Folder name should be model)
Delete model.py file from app directory (Backup the file while you delete it)
And after create init.py file in model folder
And after init.py file in write simple one line
And after create model file in your model folder and model file name should be same like as class name,if class name is 'Employee' than model file name should be like 'employee.py'
And after in model file define your database table same as write like in model.py file
Save it
My Code : from django_adminlte.models.employee import Employee
For your : from app_name.models.model_file_name_only import Class_Name_which_define_in_model_file
__init__.py
from django_adminlte.models.employee import Employee
model/employee.py (employee is separate model file)
from django.db import models
class Employee(models.Model):
eid = models.CharField(max_length=20)
ename = models.CharField(max_length=20)
eemail = models.EmailField()
econtact = models.CharField(max_length=15)
class Meta:
db_table = "employee"
# app_label = 'django_adminlte'
def __str__(self):
return self.ename
I wrote a script that might be useful.
github.com/victorqribeiro/splitDjangoModels
it split the models in individual files with proper naming and importing; it also create an init file so you can import all your models at once.
let me know if this helps

Categories

Resources