Django / Automatically retrieve models names - django

I'd like to retrieve automatically, in a loop, the names of the models located in a specific Django app inside my project. Does someone know how to do that ?
Best Regards
Guillaume

from django.db import get_models, get_app
app = get_app('myappname')
models = get_models(app)

Related

How do I import from current app in Django without using the app name?

My app is full of statements like this:
from my_app.model import Customer
While it works, I'll like to have a way to reference the current app without hard coding the app name into the import. Something like:
from keyword_for_current_app.model import Customer
Is there a clean way of achieving this with Django?
This is more of a python question than a Django one as it relates to how imports work. As far as I know, there isn't a way to do it as you describe, unless you change the structure of your files.
However, it isn't impossible to do something using Django's functionality to dynamically import models. You could swap some of this with importlib if you need a more general import rather than just returning the model class:
from django.apps import apps
# option 1
model = apps.get_model('app.Model')
# option 2
def get_model(model_name):
return apps.get_model(f'myapp.{model_name}')
# option 3
def get_model(model_name):
for model in apps.get_models():
if model.__name__ == model_name:
return model
The problem with option 1 for your use case is that you still need to specify the app name. Option 2 is an improvement, but you are hardcoding the app name into the function. Option 3 is the best, but might be problematic if you have models with the same name but in different apps/tables.
In my opinion, you should import each model explicitly at the top of your files. This is the cleanest and most readable way - if someone were to read your code, they would expect models to be imported this way.

I was trying to use apps.get_model function. And, I want to use this without specifying the app name, is there any way to do that.

I was referring this link : Django: Get model from string?
. And, I found there is a way to do this by using apps.get_model. But,In my scenario, the model can be from other apps. So, I can't actually name the app_name here. Is there any way to do this ?
If you don't care which app the model comes from, you can do it the following way:
from django.apps import apps
def get_model_from_any_app(model_name):
for app_config in apps.get_app_configs():
try:
model = app_config.get_model(model_name)
return model
except LookupError:
pass
model = get_model_from_any_app('SomeModelName')
But in Django models in different apps can have the same name, i.e. your project can have model Post in your blog app and model Post in your news app etc.
So this way you can end up with not the model you expect, if they have duplicate names across apps (i.e. you probably should not do it this way, just think why in the world would you want a semi-random model?).
Docs which explain the code:
https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.apps.get_app_configs
https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.get_model

Change app label of groups in Django 1.5

I have extended the User model, but now the new user model is in an app called "account" which gives all models inside this app the app label "account". The Django model "Groups" still has the app label "Auth", so now models which all has something to do with auth is in separate apps in the admin site. Is it possibly to change the app label for "Groups"?
Try this:
from django.db.models.loading import get_models
get_models(django.contrib.auth.models)[1]._meta.app_label = 'group' #or whatever
If you need still more flexibility in the admin you could try django-admin-tools. It makes it easy to reorder and group models in different layouts (tabs, collapsible boxes, etc.) and also add dashboard-like features.
Just in case anyone needs this in Django 3.0+:
from django.apps import apps
apps.get_model('auth', 'Group')._meta.app_label = 'group' #or whatever, but have to be a registered app
Please not that this will mess with django internal model handling, e.g. generate migrations in contrib.auth sitepackage and so on

How to save inputs from Django forms?

I have a very entry level question but I could figure it out... My question is how to save inputs created by Django forms to a database (like google datastore)? It seems like there is no .save or .put functions associated with forms. Can anyone give me some suggestions or point out some examples?
Thanks!
Here is the Django forms and the website is hosted by Google app engine.
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
from django import forms
from django.utils.safestring import mark_safe
class KabamInp(forms.Form):
chemical_name = forms.CharField(widget=forms.Textarea (attrs={'cols': 20, 'rows': 2}))
Koc = forms.FloatField(label=mark_safe('K<sub>OC</sub> (mL/g OC)'),initial=25000)
you need to create a Model class for the Form and use the values you get from the form to create your entity.
Look into the sample of Google App Engine Djnago Guest Book
It will guide thru creating a model/view/controller (MVC) application using Django on the App Engine.

Where to put Django comments moderation code?

I am implementing the stock Django comments to an existing site.
I'd like comments to appear in multiple apps and models and have all the comments behave the same - i.e. an email sent, plus other bits (listening to 'flag' signals and dealing with accordingly)
Where's the best place to put my custom moderator code?
I understand that I can pass in an iterator of Models to the register function - at first I placed it inside the __init__.py module of my main app as so:
from django.contrib.comments.moderation import moderator, CommentModerator
from app.models import Model1
from app2.models import Model2
#.... etc
class MyCommentModerator(CommentModerator):
email_notification = True
enable_field = 'enable_comments'
#...
moderator.register(
[Model1,Model2,Model3,Model4,...],
MyCommentModerator
)
But this gave an error saying that Model1 was already registered.
I would probably re-factor this code into a comments_moderation.py module - but where should I include it?
Or is it best practice to register each model inside each apps models.py file?
Are there any samples out there that use comments?
I only found out how the Comment moderation queue works by trial and error - are there any docs for this that I've missed?
Comment Moderation Documentation
Definitely put the codein an own file and the file in a "helper" app (every project has one).