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'
Related
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 :)
I face the problem:
AttributeError: module 'django.db.models' has no attribute 'MultiPolygonField'.
It was thrown by django when I trying to makemigrations. Old file of migrations (only 1 makemigrations file was done) was deleted. So Django, thinks for some reason that I import django.db.models instead of django.contrib.gis.db.
There is problem part my models.py code (off cause code break on 'geom' field line)
from django.contrib.gis.db import models
from renter.models import *
from classification_list.models import*
class ForestryKeys(models.Model):
id = models.IntegerField(primary_key=True)
df_forestry = models.TextField(blank=True, null=True),
geom = models.MultiPolygonField(geography=True, null=True, blank=True, verbose_name='gmtry')
class Meta:
managed = True
verbose_name = 'frst'
verbose_name_plural = 'frtses'
The problem is the 'star imports'. You did import django.contrib.gis.db.models, but then it was replaced on the following lines.
from django.contrib.gis.db import models
from renter.models import * # this could replace models with django.db.models
from classification_list.models import * # and so could this
The best fixes are to explicitly import the models you need,
from renter.models import MyModel1
from classification_list.models import MyModel2
or to import the renter.models module
import renter.models as renter_models
import from classification_list.models as classification_models *
# now use renter_models.MyModel1, classification_models.MyModel2
As a hack, you could swap the order of the models, but it's much better to use one of the approaches above.
from renter.models import *
from classification_list.models import *
from django.contrib.gis.db import models
Trying to use django-image-cropping. I don't get any errors, I just have what looks like CharField in Django Admin instead of the django-image-cropping functionality:
base.py (settings):
from easy_thumbnails.conf import Settings as thumbnail_settings
THUMBNAIL_PROCESSORS = (
'image_cropping.thumbnail_processors.crop_corners',
) + thumbnail_settings.THUMBNAIL_PROCESSORS
added easy_thumbnails and image_cropping to INSTALLED_APPS
models.py:
from image_cropping import ImageRatioField
# ...
class Organization(models.Model):
image_cover = models.ImageField(upload_to='media', blank=True, help_text="blah")
cropping = ImageRatioField('image_cover', '308x850')
admin.py:
from django.contrib import admin
from image_cropping import ImageCroppingMixin
class OrganizationAdmin(ImageCroppingMixin, admin.ModelAdmin):
pass
class OrganizationAdmin(admin.ModelAdmin):
filter_horizontal=['categorys']
#...
admin.site.register(Organization, OrganizationAdmin)
You're defining OrganizationAdmin twice in admin.py. Once, correctly, subclassing ImageCroppingMixin and once without. Since the latter definition overwrites the former, you end up without the Mixin. This is how it should look like:
from django.contrib import admin
from image_cropping import ImageCroppingMixin
class OrganizationAdmin(ImageCroppingMixin, admin.ModelAdmin):
filter_horizontal=['categorys']
#...
admin.site.register(Organization, OrganizationAdmin)
I don't think that it is recognizing the existence of my fields. Here's my models.py:
from django.db.models import *
from django.contrib import admin
from django.forms import *
class Stock(Model):
name = CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)
When I run it, I get this error: "portfolio.stock: "ordering" refers to "name", a field that doesn't exist." When I comment the meta function out and run it, it works fine until the admin site, where when I try to create a stock object, the fields don't show up.
I'm completely confused by what's going on.
The problem is your * imports.
django.db.models.CharField is being replaced by django.forms.CharField:
>>> from django.db.models import *
>>> CharField
<class 'django.db.models.fields.CharField'>
>>> from django.forms import *
>>> CharField
<class 'django.forms.fields.CharField'>
So, actually name = CharField(max_length=60) defines a form field instead of a model one - it breaks everything and makes this bug subtle.
Solution: remove unnecessary forms import and be explicit in your imports:
from django.db import models
from django.contrib import admin
class Stock(models.Model):
name = models.CharField(max_length=60)
class Meta:
ordering = ["name"]
def __unicode__(self):
return self.name
admin.site.register(Stock)
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)