Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I rely on self.request in django class-based views?
I see code all the time that relies on using an instance variable to get the request, like: class MyView(): def get(self, request): return foo() def foo(): request = self.request return bar(request) My question is, can I rely on self.request being set for every view instance? I can't find anything in the documentation that even references this attribute, and while I see it being set in some places in the source I can't tell if it is always being set. -
Django: which plot library is needed to build website like quantopian?
I'd like to build web plot-application, something like Quatopian, which uses a lot of interactive plots. After I searched in Google for making easy to introduce plot in django, I found out some options: django-chartit bokeh (Not sure whether this library can be used smoothly with django... Do I have to use django-rest-framework?) plotly (Not sure whether this library can be used smoothly with django... Do I have to use django-rest-framework?) django-rest-framework and D3.js(or other plot js lib) Which one is the most suitable one and following modern trend? I'd like to choose the one which is easy to implement, too. Thanks -
Running Django on a Linux Server using Apache with HTTPS
I've been trying to figure this out for a while now and nothing I've found has really been helping. I've got a remote Linux server running with Apache installed, and right now everything going to the server is redirected to HTTPS through Apache. This all works fine and I can access the files I need to normally, but now I'd like to also add in a Django site to my server under a new "subdomain". (For example I'd like to still be able to access non-Django files as usual 'https://www.thesite.com/path/to/file.php' and also be able to access the Django site like 'https://www.thesite.com/djangosite/some/site/page') Could someone please give me some direction as to how I'd be able to do this? I can supply more information if it's needed. Thanks in advance! -
Django - hashtag links on all templates
I want to have whenever someone writes "#id_of_model" automatically the link to the model. The idea behind is I have a chat where people are discussing stuff and to make communication easier, I would like to provide more user friendly links. My first idea was that I would check every sent message - which is stored in an model - if it contains a #id_of_model, then convert it to an link and finally save it. Does anyone know an easier solution? -
Django: from implicit through model to ManyToManyField field that created it
Given the following models and instances (as an example, the involved models vary dynamically) class Foo(models.Model): # ... class Bar(models.Model): foos = models.ManyToManyField(Foo, related_name='bars') foo = Foo.objects.create() bar = Bar.objects.create() and one of these cases (examples again, could be any of add, remove, clear) bar.foos.add(foo) # case 1 foo.bars.add(bar) # case 2 I am handling the respective m2m_changed signal where I want to access the ManyToManyField underlying the relation: Bar.foos. Sounds simple enough, or so I thought. The signal kwargs give me access to: sender: Bar_foos # The implicitly created through model instance: 1. bar, 2. foo # instance being modified reverse: 1. False, 2. True # indicating direction wrt to original field model: 1. Foo, 2. Bar # model of instances being added The only two ways I could come up with in order to get to the original field were: src_model = model if reverse else instance.__class__ # 1 field_name = sender._meta.model_name[len(src_model._meta.model_name) + 1:] field = src_model._meta.get_field(field_name) # 2 field = next(f for f in src_model._meta.many_to_many if sender == f.remote_field.through) Both approaches are highly unsatisfying! On the one hand, relying on the naming convention of the auto-created through model seems bound to break and is downright ugly. On … -
Should I use django admin panel for regular users?
I am currently trying to make a learning app. The three main users would be the Admin, Teacher and Student. Should I use the django admin panel for the teachers ? It has a lot of features and is fully customizable and I can choose what a teacher can do or not from there. Is this a correct approach ? -
Celery logger configuration
I'm using Django 1.10, python 3.5 and celery 4.1.0 I'm trying to log celery tasks info into a file. So I tried as suggested in celery documentation - from celery.utils.log import get_task_logger logger = get_task_logger(__name__) and tried to log a message inside the task - logger.info(message) I expected it to log to my default logger. But it didn't. So I added to settings a dedicated logger named 'celery.task' (as I understand from documentation): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_test_false': { '()': 'myapp.utils.classes.logging.RequireTestFalse', }, 'suppress_deprecated': { '()': 'myapp.utils.classes.logging.SuppressDeprecated' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'json', 'filters': ['suppress_deprecated'] }, 'celery_file': { 'level': 'INFO', 'class': 'myapp.utils.classes.logging.SBRotatingFileHandler', 'maxBytes': 1024 * 1024 * 200, # 200 MB 'backupCount': 10, 'formatter': 'json', 'filename': BASE_DIR + '/../log/celery.log', } }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': LOG_LEVEL, 'propagate': True, }, 'celery.task': { 'handlers': ['console', 'celery_file'], 'level': 'INFO', 'propagate': True, }, } But I still don't see logs from celery task not in the celery.log file nor in the default log file. Only when starting celery worker with '-f' - it writes logs to that file Any ideas? -
Django runserver getting [Error 126] The specified module could not be found
I can't seem to figure out what the missing module actually IS though. Here is the error that prints to the console: Unhandled exception in thread started by <function wrapper at 0x04EF32B0> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\users\username\desktop\sandbox-code\company\more_company\community\models.py", line 5, in <module> from django.contrib.gis.geos import Point File "C:\Python27\lib\site-packages\django\contrib\gis\geos\__init__.py", line 18, in <module> HAS_GEOS = geos_version_info()['version'] >= '3.3.0' File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 188, in geos_version_info ver = geos_version().decode() File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 156, in __call__ self.func = self.get_func(*self.args, **self.kwargs) File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 161, in get_func func = GEOSFunc(self.func_name) File "C:\Python27\lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 39, in __init__ self.cfunc = getattr(lgeos, func_name + '_r') File "C:\Python27\lib\site-packages\django\utils\functional.py", line 234, in inner self._setup() File "C:\Python27\lib\site-packages\django\utils\functional.py", line 380, in _setup self._wrapped = self._setupfunc() File "C:\Python27\lib\site-packages\django\contrib\gis\geos\libgeos.py", line 63, in load_geos _lgeos = CDLL(lib_path) File "C:\Python27\lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could … -
ManyToManyField with extra information
I'm working on a django website and I need to store some information about the user like a isVerified BooleanField and a profile picture in an ImageField as well as ratings which stores ratings a user has given different elements. So I made a model like this: class UserProfile(AbstractBaseUser): is_verified = models.BooleanField(default=True) current_profile = models.ImageField(default=static('img/default_profile.jpg')) ratings = models.ManyToManyField(Element, on_delete=models.CASCADE) however I'd like to save some more about these ratings (like a timestamp and the actual value the user rated) Do I need to make a seperate model just for that or can this be acchieved in a better way? -
Django user authentication working properly EXCEPT 1 view/template
I am working with Django 1.11.5 and logging-in and validating users via Social Auth. The user authentication, log-in and logoff are working as expected in 12/13 of my templates. All my templates extend my navbar and footer base.html template. In 'base.html' I have the following code for the navbar: {% if user.is_authenticated %} <li class="nav-item"> <span class="nav-link" id="user-name">{{ request.user.username }}</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'logout' %}">Logoff</a> </li> {% else %} <li class="nav-item log-in-link"> <a class="btn btn-primary nav-link log-in" href="{% url 'social:begin' 'google-oauth2' %}"><span>Log-In <i class="fa fa-google-plus" aria-hidden="true"></i></span></a> </li> {% endif %} Now, this navbar code works properly in 12/13 of my templates. It is only for 1 template/view/URL where the user is not authenticated. I have tried debugging by printing out the user name and information in the template giving me errors but it looks like the user is getting logged out when reaching that template via its URL and view. I am totally lost. Could someone point out things I can check/do to debug and locate the source of this logoff error? I can provide the relevant code if needed. -
How to execute a decorator function at startup in a Django/Python Application?
I have a number of classes for which I wish to run a decorator function on. As I am aware decorators only run when the class/function/whatever they label is loaded into the code. e.g. def decorator(cls): print("Decorator executed") return cls @decorator class Example: pass Example() How can I trigger the decorator function on all the classes a decorator labels without having to load each class separately? (or without having knowledge of the classes for which a decorator labels) -
Django form issue with MultipleHiddenInput and Postgres ArrayField
I have a model that uses an ArrayField for storage and uses the MultipleHiddenInput field for use in a model form. Everything works fine when I create a new instance of the model. However, when I try to edit an existing instance it renders the hidden input stored in the model as a list [739, 9] as follows: <input type="hidden" name="control_instance_id" value="7" id="id_control_instance_id_0"> <input type="hidden" name="control_instance_id" value="3" id="id_control_instance_id_1"> <input type="hidden" name="control_instance_id" value="6" id="id_control_instance_id_2"> <input type="hidden" name="control_instance_id" value="," id="id_control_instance_id_3"> <input type="hidden" name="control_instance_id" value="9" id="id_control_instance_id_4"> It should be rendered as: <input type="hidden" name="control_instance_id" value="739" id="id_control_instance_id_0"> <input type="hidden" name="control_instance_id" value="9" id="id_control_instance_id_1"> The meta portion of my form is: class Meta: model = AdhocScan fields = ['name', 'schedule_for', 'notifications', 'report_type', 'control_instance_id'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'schedule_for': forms.DateTimeInput(attrs={'class': 'form-control'}), 'notifications': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}), 'report_type': MultiChoiceWidget(choices=ReportEnum.choices()), 'control_instance_id': forms.MultipleHiddenInput() } labels = { 'schedule_for': unicode('Schedule For'), 'report_type': unicode('Reports') }, help_texts = { 'report_type': unicode('NOTE: A Splunk report will always be automatically generated.') } My model is: class AdhocScan(models.Model): name = models.CharField(max_length=256) report_type = ArrayField(models.IntegerField()) control_instance_id = ArrayField(models.IntegerField()) schedule_for = models.DateTimeField(null=True,blank=True) notifications = models.TextField(null=True, blank=True) started_on = models.DateTimeField(null=True, blank=True) completed_on = models.DateTimeField(null=True, blank=True) owner = models.ForeignKey(User) created_on = models.DateTimeField(auto_now_add=True) execution_status = models.IntegerField(choices=ScanExecutionStatus.choices(), default=ScanExecutionStatus.CREATED.value) -
wsgi.py' cannot be loaded as Python module - Python3
I am making use of python3 for building the application [Tue Jan 16 19:07:13.587669 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] mod_wsgi (pid=22631): Target WSGI script '/u0/shsathya/html/captool/captool/wsgi.py' cannot be loaded as Python module. [Tue Jan 16 19:07:13.587752 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] mod_wsgi (pid=22631): Exception occurred processing WSGI script '/u0/shsathya/html/captool/captool/wsgi.py'. [Tue Jan 16 19:07:13.587979 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] Traceback (most recent call last): [Tue Jan 16 19:07:13.588026 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] File "/u0/shsathya/html/captool/captool/wsgi.py", line 14, in [Tue Jan 16 19:07:13.588036 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] from django.core.wsgi import get_wsgi_application [Tue Jan 16 19:07:13.588059 2018] [wsgi:error] [pid 22631:tid 140432910448384] [remote 172.19.217.162:48145] ImportError: No module named 'django.core' -
Django Checkout in an ecommerce application
I have an ecommerce application which was written based on tutorials found in a book. after implementing everything, I decided to improve it because according to the book, customers have to imput their details everytime they want to checkout from the application and this is very unprofessional. I have included all my codes in my GitHub because I cant include every bit of the code. https://github.com/Olar19/ecommerce . I have worked on this trying to improve it for some months and I just cannot wrap my head around it. any help would be appreciated. -
Django 1.11 how can I construct a url lookup with a hash symbol?
Here is the constructor in question: url(r"^app/#events/(?P<pk>\d+)$" % URL_PATTERNS, views.app, name="app-event"), There is a route to catch app/, so the problem is not that the server doesn't pick up the rest of the url. I know what the browser does there. We use this for links from reverse lookup. My question is, in Django 1.8 it would leave the string alone, not parsing # to %23. In Django 1.11 it does parse, and I don't want it to. -
Heroku Django Application Error: Worker Timout Issue (H12)
After fighting for a while, my first python (django) app is deployed successfully, the database is pushed and can be accessed (and I can run the app both locally as python manage.py runserver or within heroku). However, the end result is still the 'Applications Error' page. The heroku logs shows the following: 2018-01-16T18:43:18.905263+00:00 heroku[web.1]: Restarting 2018-01-16T18:43:18.906518+00:00 heroku[web.1]: State changed from up to starting 2018-01-16T18:43:19.978422+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2018-01-16T18:43:19.998918+00:00 app[web.1]: [2018-01-16 18:43:19 +0000] [4] [INFO] Handling signal: term 2018-01-16T18:43:26.659760+00:00 heroku[web.1]: Starting process with command `gunicorn extend_sp_radii.wsgi --timeout 20 --keep-alive 5 --log-level debug --log-file -` 2018-01-16T18:43:29.067589+00:00 app[web.1]: [2018-01-16 18:43:29 +0000] [4] [DEBUG] Current configuration: 2018-01-16T18:43:29.067608+00:00 app[web.1]: config: None 2018-01-16T18:43:29.067609+00:00 app[web.1]: bind: ['0.0.0.0:48177'] 2018-01-16T18:43:29.067616+00:00 app[web.1]: max_requests_jitter: 0 2018-01-16T18:43:29.067617+00:00 app[web.1]: timeout: 20 2018-01-16T18:43:29.067618+00:00 app[web.1]: graceful_timeout: 30 2018-01-16T18:43:29.067619+00:00 app[web.1]: keepalive: 5 2018-01-16T18:43:29.067620+00:00 app[web.1]: limit_request_line: 4094 2018-01-16T18:43:29.067621+00:00 app[web.1]: limit_request_fields: 100 2018-01-16T18:43:29.067624+00:00 app[web.1]: reload: False 2018-01-16T18:43:29.067623+00:00 app[web.1]: limit_request_field_size: 8190 2018-01-16T18:43:29.067625+00:00 app[web.1]: reload_engine: auto 2018-01-16T18:43:29.067626+00:00 app[web.1]: spew: False 2018-01-16T18:43:29.067627+00:00 app[web.1]: check_config: False 2018-01-16T18:43:29.067628+00:00 app[web.1]: preload_app: False 2018-01-16T18:43:29.067629+00:00 app[web.1]: sendfile: None 2018-01-16T18:43:29.067630+00:00 app[web.1]: chdir: /app 2018-01-16T18:43:29.067631+00:00 app[web.1]: daemon: False 2018-01-16T18:43:29.067633+00:00 app[web.1]: pidfile: None 2018-01-16T18:43:29.067632+00:00 app[web.1]: raw_env: [] 2018-01-16T18:43:29.067634+00:00 app[web.1]: worker_tmp_dir: None 2018-01-16T18:43:29.067635+00:00 app[web.1]: user: 55457 2018-01-16T18:43:29.067636+00:00 app[web.1]: group: 55457 2018-01-16T18:43:29.067637+00:00 app[web.1]: umask: 0 2018-01-16T18:43:29.067638+00:00 app[web.1]: initgroups: … -
Convert django RawQuerySet to Queryset
I have 2 Django models, ModelA with an ArrayField that is used to store a large list of primary key values (possibly 50k+ list) class ModelA(models.Model): pk_values = ArrayField(models.IntegerField()) class CustomManager(manager.Manager): def get_for_index(self, index_id): qs = self.get_queryset() obj = ModelA.objects.get(pk=index_id) return qs.filter(id__in=obj.pk_values) class ModelB(models.Model): # [...] some fields objects = CustomManager() This works: qs = ModelB.objects.get_for_index(index_id=1) However this would be super where "pk_values" is very large. So I tried doing raw SQL queries: class CustomManager(manager.Manager): def get_for_index(self, index_id): qs = self.get_queryset() sql = "SELECT * FROM myapp_model_b JOIN myapp_model_a ON myapp_model_b.id = ANY(myapp_model_a.pk_values) WHERE myapp_model_a.id = '%s'" % index_id return qs.raw(sql) But this returns a django.db.models.query.RawQuerySet instance. And I cant do things like queryset.values() afterwards. How can convert this to a normal Django queryset? Is there a better way of doing this? Docs: ArrayField https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#arrayfield Custom Manager https://docs.djangoproject.com/en/2.0/topics/db/managers/#custom-managers-and-model-inheritance Raw queries https://docs.djangoproject.com/en/2.0/topics/db/sql/#performing-raw-sql-queries -
django: How can I create a custom Logging Filter for SuspiciousOperation exeption?
After migrate to 1.11 ( from 1.8 ) I start to receive from logging a lot of SuspiciousOperationerror. It seems it comes from JS request who keeps session alive if user move their mouse. But this is not important. How can I filter just this exception? -
If you extend the user model in Django using AbstractUser from one app within a project, how do you refer to it from a second app?
Are you able to have a foreign key relationship from a model within the app that does not contain the extended user model to the extended user model in the other app? Is the only way to refer to the extended user model from the second app settings.AUTH_USER_MODEL? -
YouTube Plugin in CKEditor Django returns 404
I've been trying to install the YouTube plugin in CKEditor for a project, but I have failed and I couldn't figure out why. I have configured my settings.py in the following manner (stripping it of irrelevant-to-this-issue code: CKEDITOR_CONFIGS = { 'default': { 'toolbar_Collective':[ ['Source', '-', 'Bold', 'Italic'], # ... { 'name': 'links', 'items': ['Link', 'Unlink'] }, { 'name': 'media', 'items': ['ImageButton', 'Youtube'] }, # ... {'name': 'tools', 'items': ['Maximize']}, ], 'toolbar':'Collective', 'width': '100%', 'height': 400, 'tabSpaces': 4, 'extraPlugins': ','.join([ ]), } } Currently I have left the 'extraPlugins' configurations empty, because as soons as I write 'youtube' in there: 'extraPlugins': ','.join([ 'youtube', ]), CKEditor fails, and the following is shown on my terminal: [16/Jan/2018 18:31:16] "GET /post/new/ HTTP/1.1" 200 7239 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor-init.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/css/main.css HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/ckeditor.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/js/script.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=H4PG HTTP/1.1" 404 1749 Performing system checks... You can see there are other error codes, even regarding the page css. I don't know why they are there, but they are there regardless of any editing, and the editor functions regardless of them. The real issue is with the YouTube … -
Make django url path to match my model objects' name
So I have a courses app, and when I click on the course name I want it to redirect me to the specific course page (like a detail page) and URL path to match the course name. E.g. If course name is 'Science', then when I click on it, url becomes '/science/' and im on the science page. I tried something. re_path('(?P<course_id>[0-9]+)', views.courses, name='courses'), <ul> <li>{{ courses.name }}</li> </ul> def courses(request, course_id): con = Course.objects.all() return render(request, 'courses/courses.html', {'courses': con}) -
Creating title on django form
I currently have my django template displaying about 25 forms. What I need it a way to display a title above each form For example: {% form in formset %} <h1>{{ form.title}}</h1> {{ form.as_ul}} {% endfor %} Currently my formset displays 25 forms or more on one page and it is hard to tell which form I am editing. I would like to add a title on to the form so it is more user friendly Please let me know if you know of a way to do this -
Changing type of primary case changes behavior of ManyToMany field addition
class Word(Model): id = BigAutoField() name = CharField() categories = ManyToMany('Category') When id was an UUIDField I could easily write Word.objects.create(name='apple', categories=[1,2]) (where 1 and 2 are ids of categories). Now I can't write that. Instead I need to write w=Word.objects.create(name='apple') w.categories.add(1,2) Why is that? -
Django: Adding column to model giving error that the column doesn't exist
I have two models, each in separate apps of the same names: class Vendor(models.Model): name = models.CharField(max_length=200, blank=True, default='DEFAULT') serial_num = models.CharField(max_length=200, blank=True) class Node(models.Model): name = models.CharField(max_length=200, blank=True) persons = models.ForeignKey(Person, on_delete=models.SET_NULL, null=True) When I try python3 manage.py makemigrations I get the lengthy error below. I think the issue might be the migration files. Because Home has a foreign key to Person, 0001_initial.py has dependency ('Person', '0007_auto_20180110_1827'), and I am unable to add the serial_num column to Person. So I tried deleting the location column and adding the location column back in, then got the following error saying it doesn't recognize a column location. How do I fix the issue? Also, let me know if I need to provide more info about the issue. Traceback (most recent call last): File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: vendor_vendor.location The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/karthikpullela/Desktop/Django-projects/QuikBikes/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File … -
Type hints for generic code
Let's say, I have this piece of code: class BaseModel(object) pass class AppleModel(BaseModel): pass class OrangeModel(BaseModel): pass def get_record(model, pk): try: result = model.objects.get(pk=pk) # Some code working with BaseModel.. return result except model.DoesNotExist: return None Now, I want to use it like in this example with proper type annotation... myApple = get_record(AppleModel, 12) myApple. # type hints for AppleModel myOrange = get_record(OrangeModel, 433) myOragne. # type hints for OrangeModel How should I annotate get_record function? I tried something like def get_record(model: Type[BaseModel], id: int) -> Optional[BaseModel]: # ... But then, I loose info about subclasses. I tried use Generic, but without success. Real code is more advanced. This is only simplified example. Thanks for any suggestions...