I created an instance of AdminSite as I wanted the admin page for editing the models available under my app (as opposed to the project):
in the myproj/myapp/admins.py I have:
from django.contrib.admin.sites import AdminSite
from models import mymodel
class myadminsite(AdminSite):
pass
my_admin_site = myadminsite(AdminSite)
my_admin_site.register(my model)
in the myproj/myapp/urls.py I have :
url(r'admin/', include(my_admin_site.urls)),
So when I point my browser to 'http://example.com/myapp/admin' I get the admin page correctly and when I log in I see the model also. I am able to add and modify any of the model objects without any problem. BUT when I try to delete any of the model objects it gives me this error:
NoReverseMatch at /myapp/admin/myapp/mymodel/2/delete/
u"<class 'django.contrib.admin.sites.AdminSite'>" is not a registered namespace
I have been trying for almost four hours now to figure out what is wrong but am unable to. Any ideas/help will be very much appreciated.
Related
I'm working on a Django based project right now. I 'm getting an error something called AppRegistryNotReady when I'm trying to import a model into another app's model with django get_model() method.. Now the interesting this is, I can import the models from another app in the view files with the same get_model() method.
In views file:
from django.apps import apps
Course = apps.get_model('course', 'Course')
Order = apps.get_model('course', 'Order')
*Now everything is working parfectly.
In models file:
from django.apps import apps
Course = apps.get_model('course', 'Course')
Order = apps.get_model('course', 'Order')
*Now it is getting the following error:
File "/home/mohul/.local/share/virtualenvs/django-backend-and-view-1OsDTUBe/lib/python3.9/site-packages/django/apps/registry.py", line 141, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
This is from Django Docs.
You must define or import all models in your application’s models.py or models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.
Once this stage completes, APIs that operate on models such as get_model() become usable.
https://docs.djangoproject.com/en/3.2/ref/applications/#how-applications-are-loaded
Finally I got the solution from my own. Many peoples get into this problem I saw around me.
Here how I solved the problem:
project-name/
...project-name/
...apps1/
.....models.py
...apps2/
.....models.py
...manage.py
Just the basic django project structure.
Now to import the models of apps1 into apps2:
In apps2/models.py:
from apps1 import models as apps1Model
# Now accessing the models
apps1Model.Model1
apps1Model.Model2
I have a ML model saved in a pkl (pickel file), I have no problem loading this model and using it for prediction, even I have a rest service that expose it, the only problem is that I load the model in every request, something like this:
https://www.analyticsvidhya.com/blog/2017/09/machine-learning-models-as-apis-using-flask/
I really want that my model just load one time like a global variable and every request useing this variable without the necessity of load the model every request
is it possible?
You can assign the model variable in settings.py. Whenever the server will start/restart django will store the model variable globally. It can be accessed like
from django.conf import settings
print settings.my_ml_model_variable
Based on the comment of Kaushal, I solved my problem using django rest framework as the following:
first I saved my model as :
> joblib.dump(<your scikit model here> , <"yourfilename.pkl">, compress
> = 1)
Once I had my model saved with the pkl extension I needed to create a variable in the settings.py file(this file is created automatically by django)
YOURMODEL = joblib.load(<"yourfilename.pkl">)
The django process call this file when you start your server, so it is called just one time
Now we just need to call our model in whatever place we want, usually in a views.py file since we are using django and/or django-rest-framework
myModel = getattr(settings, 'YOURMODEL', 'the_default_value')
res = myModel.predict_proba(s).tolist()
A simple example of the rest service:
from django.conf import settings
class myClass(APIView):
permission_classes = (permissions.AllowAny,)
'''Httpverb post method'''
def post(self, request,format=None):
myModel = getattr(settings, '../mymodel.pkl', 'the_default_value')
data = preparePostData(request.data)
res = myModel.predict_proba(data).tolist()
message = prepareMessage(res)
return Response(message, status=status.HTTP_200_OK)
Here preparePostData and prepareMessage are just function that I developed for prepare the object to my model and my response
Regards
You can do it in Django by creating yourfile.py config.
Just you should redfine the django AppConfig there, and instanciate your models .
It will load all your models when django is starting for just once .
After that you can use it in views simpely by importing your class models from yourfile.py .
To do that you should define Yourfile.py
It should look like that :
from django.apps import AppConfig
class YourModelsConfig(AppConfig):
#write what you need
And in your views you can do:
from yourfile import YourModelsConfig
YourModelsConfig.your_method_or_your_variable
I think you can get more details here .
https://medium.com/saarthi-ai/deploying-a-machine-learning-model-using-django-part-1-6c7de05c8d7v
I want to catch up some extra information within my Django Admin through some extra Fields. I want to use inlines for that purpose.
I have:
class YourModelForm(forms.ModelForm):
slot_count_request = forms.IntegerField(label='#-slot-size', initial=4 )
class Card_Group_proxy_inline(admin.TabularInline):
model = SomeRandomModel
form = YourModelForm
This works fine for if I want to use a model within. I thought I can get rid of it, if I inherit from admin.InlineModelAdmin, but then I get an error:
AttributeError: module 'django.contrib.admin' has no attribute 'InlineModelAdmin'
The InlineModelAdmin class can be imported with:
from django.contrib.admin.options import InlineModelAdmin
However, I have not seen InlineModelAdmin used directly before. Usually, you would use admin.TabularInline or admin.StackedInline.
in my new Django app I use 3rd-part Photologue app.
This app works well, but I need to add some field in its model without change the original source code of Photologue app.
With this snippet, all works well, but maybe this is not the best solution:
Photo.add_to_class("link", models.URLField(max_leng.... ))
I've read some posts where I should use OneToOneRelationField ... but then, in django admin app, I will have two different form page of Photo and new PhotoLink class...
Does anyone can help me?
If you are using a OneToOneField, you can use your 'extension' model as an inline to the model you are extending. You do this by first un-registering the original admin class, and then overriding it with our variant:
from otherapp.admin import OriginalFooAdmin
from otherapp.models import Foo
from yourapp.models import YourExtension
from django.contrib import admin
admin.site.unregister(Foo)
class ExtensionInline(admin.StackedInline):
model = YourExtension
class NewFooAdmin(OriginalFooAdmin):
inlines = OriginalFooAdmin.inlines + [ExtensionInline]
admin.site.register(Foo, NewFooAdmin)
I use mongoengine with django. I have two applications with models.
app1/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model1(Document):
name = fields.StringField()
lists = fields.ListField(fields.ReferenceField("Model2", dbref=False))
app2/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model2(Document):
name = fields.StringField()
All applications were added to INSTALLED_APPS. When I use the django dev-server, everything is fine. But using this code with uwsgi-server there is an error:
Model2 has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
What I should do?
You should import app2.models somewhere. Put a comment by the import saying why it's there, so nobody removes the useless-looking import in the future.
When the django dev server starts up it imports the models from all installed apps and validates them. You'll see
Validating models...
0 errors found
This does not happen in a production environment. It is just a nicety of the dev server.