Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- how can I get the selections of a many-to-many field in my model's table?
I have a django model (MyModel) where one of the fields (tags) is a ManyToManyField field --tag's value is actually another model (Tag). When a user creates a MyModel instance/entry in the Django admin panel they choose at least one tag from a list of tags for that entry. bytes/models.py class Tag(models.Model): CATEGORY_CHOICES = ( ('topic', 'topic') ) tag = models.CharField(max_length=100, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I'm trying to write a custom Django management task where I use SQL to get all of the data from MyModel (on a PSQL server): import psycopg2 class Command(BaseCommand): def handle(self, *args, **options): config = settings.DATABASES['default'] try: query = F'''SELECT * from bytes_mymodel''' conn = psycopg2.connect(..use config to connect to server) cursor = conn.cursor() cursor.execute(query) results = cursor.fetchall() print(results) However when I print the 'results' I get a list of tuples - each tuple is a MyModel instance/entry. However, I don't see what tags are selected for the tags entry of each MyModel instance. For example: [('abc', 'The Title Here', 'Written By', 'Lots of copy'), ('efg', 'The Second Title Here', 'Written By', 'Lots of … -
How can I encrypt <int:pk> inside my URLs?
I think it's a dumb question, but I can't solve this problem anyway. I'm building a simple card game with chatrooms in Django. When a mod creates a room, to enter this room you need to use the following URL: cardgame/room/<int:pk> where inside of <int: pk> is replaced by the id of the room created. My problem is that some random user could enter the room of id=x just using a link like cardgame/room/x without being invited. I wanted to encrypt the id number whenever a room is created, just like when you create a Google meet call but I dont know how to this using Django/Python. How can I do this? -
exec() function in python not executing in django
Hope you all are fine. I want to use the exec() function in django to execute my strings picked from the database. The code I wrote is working in just python script but not working in Django views. Below is my code in python script which I'm running in notebook. ticker = 'AAPL' title = 'f"hey {ticker} is a really doing good."' exec('title = ' + title) print(title) But same code in Django views is not executing. Below is the code in views.py. ticker = 'AAPL' title = queryset.title #The title here is The {ticker} is not doing good. exec('title = ' + title) It is not giving the write anwser, just returning the first title as shown below. The {ticker} is not doing good. Thats is the {ticker} body. If anyone have any solution, kindly help me to figure it out. -
Django Redirect If Authenticated Mixin
i want to create a mixin to be redirect user to a specified page if they're already authenticated. i want to be able to use this mixin in different parts of the application without having to rewrite the logic over and over again. i get a accounts.views.view didn't return an HttpResponse object. It returned None instead. error if the user is not authenticated but it works if user is authenticated. accounts is the app_name here's my code in mixin.py class RedirectIfAuthenticatedMixin: """ RedirectIfAuthenticatedMixin: redirect authenticated user to different page via redirect_to parameter """ redirect_to = None def get(self, request): """ Get request handler to check if user is already authenticated then redirect user to specified url with redirect_to """ if request.user.is_authenticated: return HttpResponseRedirect(self.get_redirect_url()) # return ??? <- WHAT TO WRITE HERE TO ALLOW REQUEST TO CONTINUE EXECUTION def get_redirect_url(self): """ Get the specified redirect_to url """ if not self.redirect_to: raise ImproperlyConfigured('no url to redirect to. please specify a redirect url') return str(self.redirect_to) -
STARTTLS extension not supported by server in django
i am using gmail to do this, and i'm still at devlopment. it just keep throwing this error, yesterday it was working, sometimes it would also stop and show this error, but throughtout today it havent been working as expected setting.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "testemail@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" views.py def mail_letter(request): emails = NewsLetter.objects.all() df = read_frame(emails, fieldnames=['email']) mail_list = df['email'].values.tolist() print(mail_list) if request.method == "POST": form = MailMessageForm(request.POST) if form.is_valid: form.save() # Sending Messages title = form.cleaned_data.get('title') message = form.cleaned_data.get('message') send_mail( title, message, '', mail_list, fail_silently=False, ) # Success Alert messages.success(request, f"Messages sent successfully") subscribed = True return redirect('elements:mail_letter') else: form = MailMessageForm() -
Django Admin: manage auth.models User from different model
I would like to manage auth.models.User is_active attribute from my custom UserProfile model via admin page. class UserProfile(models.Model): user = models.OneToOneField( User, verbose_name=_('User'), related_name='user_profile', on_delete=models.CASCADE, ) invited_by = models.ForeignKey( User, verbose_name=_('Invited by'), on_delete=models.SET_NULL, related_name='profile_invitations', null=True, blank=True, ) avatar = ResizedImageField( size=[512, 512], crop=['middle', 'center'], quality=90, verbose_name='avatar', null=True, blank=True, upload_to=get_user_upload_path ) attrs = models.CharField( _('User data'), max_length=10000, ) phone_number = models.CharField( _('Phone number'), max_length=80, null=True, blank=True, validators=[phone_regex_validator], ) def __str__(self): return '{}({})'.format(self.__class__.__name__, self.user.username) def save(self, **kwargs): if self.phone_number: self.phone_number = create_alphanumeric_string(self.phone_number) super().save(**kwargs) @property def attributes(self): return json.loads(self.attrs or '{}') @attributes.setter def attributes(self, value): self.attrs = json.dumps(value or {}) and in my admin.py @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'attrs', 'invited_by') search_fields = ('user__username',) What I want to achieve is to allow from UserProfile admin view change is_active field from auth.models.User. My question is what is the best way to solve this? Write new custom form and attach it to admin view or somehow attach this field to UserProfile model? Or maybe different solution? -
Selectively escape strings in html using python/django
I'm working with email content that has been formatted in html. What I have found is that email addresses are often formatted similarly to html tags. Is there a way to selectively escape strings in html code, but render others as-is? For example, email addresses are often formatted as "Guy, Some <someguy@gmail.com>" How can I escape this, which python sees as an html tag, but leave <br></br><p></p>, etc. intact and render them? -
How can I add a image on a post in django?
I want to create an upload image button in django admin post models. When an image is uploaded, will be nice to be displayed on both blog card and then on post detail on the website. Here is my code until now. How should I do this in order to make this work? Here is my blog.html page <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="column"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <img class="card-image">{{post.header_image}}</img> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p class="card-text">{{post.content|slice:":200"}}</p> <a href="{% url 'post_detail' post.pk %}" class="btn-grey">Află mai multe</a> </div> </div> {% endfor %} </div> </div> </div> Here is my post detail.html <div class="container"> <div class="detail-row"> <div class="card-detail-body"> <h1> {{ post.title }} </h1> <p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p> <p class="card-text ">{{ post.content | safe }}</p> </div> </div> </div> Here is models.py from django.db import models import datetime from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=1048) slug = models.SlugField(max_length=1048) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') related_name=('blog_posts') content = models.TextField() status = models.IntegerField(choices=STATUS, default=0) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title And here are … -
Multiple checkboxes validation rules, only works when every checkbox selected
I have a template which goes through a queryset and creates a checkbox for each item which seems to be a validation problem. I can only submit this when I check every checkbox and I just can't seem to figure out what is wrong. my template: <form method="POST"> {% csrf_token %} <fieldset> {% for choice in choices %} {{ choice.description }} <input type="checkbox" value="{{choice.section}}" name="sections" required=""> {% endfor %} <button type="submit">Submit</button> </fieldset> my forms.py class AddSectionForm(forms.Form): sections = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple()) -
Multiple databases for the same model in Django
Django seems to support multiple databases and allows each model to override methods to route to a specific database (official doc). Two questions: Does it support routing for the same model into different databases, for example for partitioning (say I want to split my users across multiple databases based on a predicate like the length of the username or the first letter, etc...) How does it works/render in the admin UI? I would need to aggregate the data from all databases in my case. -
Background process in Django
I am a freshman in Django and I have a problem with understanding of implementation background processes. For example, I have: model.py class Person(models.Model): name = models.CharField(max_length=23) math_grade = models.IntegerField(null=True, blank=True) phys_grade = models.IntegerField(null=True, blank=True) avg_grade = models.IntegerField(null=True, blank=True) class PersonAdmin(admin.ModelAdmin): list_display=('name', 'math_grade ','phys_grade', 'avg_grade') admin.py from django.contrib import admin from .models import * admin.site.register(Person, PersonAdmin) How to implement the next thing: Automatically check (periodically) if math_grade and phys_grade are saved into the DB for this Person, and then automatically f.e. save avg_grade as (a+b)/2 -
Query parameters in url in Django project
I would like to have query parameters in the url of my request that allow to retrieve data according to the plant id + the name of the step (sowing, planting or harvesting. Example : http://localhost:8000/api/plant/life/calendars?plant_id=1&step_title=sowing Let me explain: in my current model plant_life_calendars I have plant_step_id which joins the plant_step table and in this table I have as modele the plant_id which is a foreingkey of the plant table and a step_title for the title of the stage as its name suggests. I hope it's clear enough, it's hard to explain in writing but I put screens below of the different models in order to better understand. So I would like for the plant_life_calendars request to enter in the url the plant_id and step_title which comes from the plant_step table so in the view I did this: class PlantLifeCalendarLinkAPIView(ListAPIView): permission_classes = (AllowAnonymous,) serializer_class = ReadPlantLifeCalendarSerializer def get_queryset(self): try: plant_id = int(self.request.GET.get('plant_id')) except (ValueError, TypeError): plant_id = None plant_step_id = self.request.GET.get('plant_step_id') params = {} if plant_id: params['plant__id'] = plant_id if plant_step_id: params['plant_step_id'] = plant_step_id if params: return PlantLifeCalendar.objects.filter(**params) return PlantLifeCalendar.objects.all() But it doesn't work, it gives me this error message: <pre class="exception_value">Cannot resolve keyword &#x27;plant&#x27; into field. Choices are: end, … -
items not rendering in django-template
I am just trying to render a query but it's not showing in the template for one view and it's showing up in another i am not sure why. the template : <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">{{vessel_id.name}}</button> <div id="myDropdown" class="dropdown-content"> {%for vessel in vessel%} <a href="{% url 'maintenance:home' pk=vessel.id %}">{{vessel.name}}</a> {%endfor%} </div> </div> here in this view the {{vessel.name}} is not working and doesn't render any drop down vessels view.py def update_component(request, pk): vessel_id = Vessel.objects.get(id=pk) # get the id of this specfic component component_id = Component.objects.get(id=pk) # get the vessel of this specfic component component_vessel = component_id.vessel # fetch all components of this specfic vessel component = component_vessel.components.all() vessel = Vessel.objects.all() form = ComponentModelForm(instance=component_id) if request.method == 'POST' and 'form-update' in request.POST: form = ComponentModelForm( request.POST, request.FILES, instance=component_id) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) if request.method == 'POST' and 'form-delete' in request.POST: component_id.delete() return redirect('/maintenance') context = { 'components': component, 'form': form, 'component_id': component_id, 'vessel': vessel, "component_vessel":component_vessel, 'vessel_id':vessel_id } return render(request, 'update_component.html', context) while this view is working just fine for the same template view.py: def index(request, pk): vessel_id = Vessel.objects.get(id=pk) vessel = Vessel.objects.all() component = vessel_id.components.all() component_id = Component.objects.get(id=1) form = ComponentModelForm(instance=component_id) if request.method == 'POST': form = ComponentModelForm( … -
Celery task behave strangely while testing
I'm trying to test that my Celery task updates Django model. It works fine, but behaves strangely during testing. # someapp/models.py class SomeModel(models.Model): ... hidden = models.BooleanField(default=False) # someapp/tasks.py @shared_task() def my_task(model_id): model_instance = someapp.models.SomeModel.objects.get(id=model_id) model_instance.hidden = True model_instance.save() logger.info(f'Uncovered model instance with id {model_id]') To test this I've implemented following workflow: I create SomeModel object via factory-boy factory because SomeModel depends on multiple models. I assign this object to variable model_instance I apply the task locally I assert that model_instance.hidden is True The code below # someapp/tests.py @pytest.mark.django_db @pytest.mark.celery(task_always_eager=True) def test_celery_task_uncovers_model_instance() -> None: SomeModelFactory.create(hidden=False) some_model = someapp.models.SomeModel.objects.first() assert some_model.hidden is True my_task.apply((some_model.id, )) assert some_model.hidden is True raises at the last line. Then I assert: assert (model_instance.pk, model_instance.hidden) == (someapp.models.SomeModel.objects.first().pk, someapp.models.SomeModel.objects.first().hidden) It raises: E assert (1, True) == (1, False) E At index 1 diff: True != False Finally, I want to check ids: assert id(model_instance) == id(authapp.models.SomeModel.objects.first()) And it raises something like this: E AssertionError: assert 139938217188656 == 139938219885184 E + where 139938217188656 = id(<SomeModel: - 2022-02-01>) E + and 139938219885184 = id(<SomeModel: - 2022-02-01>) Why does not the task update the some_model object in my test? -
Python Django, How I Can use username(uname) or email as a login credentials?
Python Django, How I Can use username(uname) or email as a login credentials ? my python file are views,URLs,models,settings.py def loginpage(request): if request.method=="POST": try: Userdetails=newacc.objects.get(email=request.POST['email'],pwd=request.POST['pwd']) print("Username=",Userdetails) request.session[ 'email']=Userdetails.email return render(request,'Logout.html') except newacc.DoseNotExist as e: messages.success(request,' Username / Password Invalid.') return render(request,'Login.html') -
How to log to file using Django and Gunicorn? Using TimedRotatingFileHandler misses logs
I have a Django app that logs INFO using a TimedRotatingFileHandler. In a development server that works fine but when running in production using gunicorn, not all log lines make it to the file. I also use a console handler which correctly logs everything, and looks like the file used by TimedRotatingFileHandler only has some of those lines and drops a lot of what appears from the console logger. It also exhibits another strange behavior; my logging dictConfig has a midnight rotation. What I expected was mylog.log being written to until midnight and then rotates the content into a mylog.log. file. This is the behavior when running in development server that came with Django. What happens when running my app with gunicorn is it continuously writes into both mylog.log file and mylog.log.2022-02-01 file. The content inside mylog.log does not appear in the other file as well. It's almost as if log is being distributed between mylog.log and mylog.log.2022-02-01 throughout the day... My config: 'handlers': { 'console': { 'level': 'INFO', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'INFO', 'formatter': 'verbose', 'filename': mylog.log, 'when': 'midnight', 'encoding': 'utf-8', 'backupCount': 7, 'class': 'logging.handlers.TimedRotatingFileHandler', }, }, 'loggers': { '': { 'handlers': ['console', 'file'], 'level': … -
UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte
I am getting this error after django installation phase. Help After installing, I transfer the manage.py file, but it does not improve. -
Django Template Queryset Issue
So Im literally going crazy trying to understand why I can't retrieve an individual value from a dictionary that's being passed to my template. def createCharacterSkills(request): user = request.user if user.is_authenticated and request.method=="GET": characterid = request.session["characterid"] print(characterid) characterrecord = character.objects.filter(pk=characterid) print(characterrecord.values()) return render(request, "characters/createcharacter2.html", {'characterrecord':characterrecord}) Is what I am passing to my template. Below is the relevant code in my template: <b>Name: </b>{{ characterrecord.values }} <br> <b>Player Reference: </b>{{ characterrecord.id }}<br> The characterrecord.values is working correctly and returning the whole dictionary as expected. <QuerySet [{'id': 48, 'player_id': 1, 'character_name': 'Avalon', 'character_race': 'Dwarf', 'character_faction': 'Jhereg', 'character_group': 'Moredhel', 'ambidexterity': 0, 'dagger': 0, 'one_handed_weapon': 0, 'pole_arms': 0, 'projectile_weapons': 0, 'shield': 0, 'two_handed_weapons': 0, 'thrown_weapons': 0, 'wear_light_armour': 0, 'wear_medium_armour': 0, 'wear_heavy_armour': 0, 'wear_extra_heavy_armour': 0, 'body_development': 0, 'literacy': 0, 'surgeon': 0, 'numeracy': 0, 'alchemist': 0, 'crafting': 0, 'evaluate': 0, 'ranger_1': 0, 'ranger_2': 0, 'make_and_read_maps': 0, 'recongnise_forgery': 0, 'poison_lore_1': 0, 'posion_Lore_2': 0, 'potion_lore_1': 0, 'potion_lore_2': 0, 'ritual_contribute': 0, 'ritual_magic': 0, 'invocation': 0, 'corporeal_1': 0, 'corporeal_2': 0, 'mage_1': 0, 'mage_2': 0, 'shamanism_1': 0, 'shamanism_2': 0, 'forage': 0, 'meditation': 0, 'vet_ritual_magic': 0, 'vet_ritual_contribute': 0, 'chameleon': 0, 'fearless': 0, 'natural_armour': 0, 'sense_magic': 0, 'track': 0, 'intuition': 0, 'poison_resistance': 0, 'resist_magic': 0, 'sense_trap': 0, 'iron_will': 0, 'resist_disease': 0, 'discern_truth': 0, … -
Is it possible to add a feature to attach code-blocks to a post form?
I've been trying to find something about this for a while, but I don't know if its my wording but I can't seem to find anything about it. Anyways... I'm working on a project for school, and basically it's a website that does many things, and one of those things is like a mini-stackoverflow thing but just for my school's community. So I have designed a form for the post using crispy forms however I can't seem to find any information on how to add the feature to write in code blocks to a form (just like we do here on Stack Overflow). This is what the form looks like on code: Template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Nueva Publicación</legend> {{ form|crispy }} </fieldset> <div> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Crear Publicación</button> </div> </form> Models class Post(models.Model): titulo = models.CharField(max_length=150) contenido = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) imagen = models.ImageField(default='default.jpg', upload_to='blog_images') def __str__(self): return self.titulo def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) Visually: If you guys need anything else in order to help, please tell me and I will provide ASAP. -
How can I encrypt url in Django Rest Framework?
I found a documentation since it is not working with python updated version so I am having this problem. I want to prevent scrapping from my application. There are some api where I am passing sensitive data and my api endpoing is like localhost:8000/api/products/1 but I want this url to be like localhost:8000/api/products/dheudhuehdeidiwf4yfg4gfy4yf4f4fu4f84j4i this. So which procedure should I follow here? -
Getting TypeError when trying to use Django and Pandas to show data in html
import pandas as pd from django.shortcuts import render # Create your views here. def home(): data = pd.read_csv("\\pandadjangoproject\\nmdata.csv", nrows=11) only_city = data[['name']] context = { "data": data.to_html(index=False), "only_city": only_city.to_html() } return request(render, 'home.html', context) #Here is my HTML Page <html> <head> <title>NM Biggest citys</title> </head> <body> <h1>New Mexicos Largest Citys</h1> {{only_city|safe}} </body> </html> #I get this error: TypeError at / home() takes 0 positional arguments but 1 was given Request Method: GET Request URL: http://localhost:8000/ Django Version: 4.0.1 Exception Type: TypeError Exception Value: home() takes 0 positional arguments but 1 was given -
Python Web Development
Like Javascript has ReactJS framework for Frontend development and NodeJS for Backend Development .But Python has Django Framework for backend Development But Why it doesn't have any Frontend Framework? -
Soft Delete for many to many does not work in Django
We have soft delete implementation where we do softdelete for every record, but this doesn't work for Many to Many relationship. Below is the code for soft delete implementation class SoftDeletionQuerySet(models.QuerySet): def delete(self, **kwargs): defaults = {"deleted_at": time.now()} args = {**defaults, **kwargs} return super().update(**args) class SoftDeletionManager(models.Manager): def get_queryset(self): return SoftDeletionQuerySet(self.model).filter(deleted_at=None) class SoftDeletionModel(models.Model): deleted_at = models.DateTimeField(null=True, blank=True) objects = SoftDeletionManager() class Meta: abstract = True class A(SoftDeletionModel): name = models.CharField(max_length=128, default="") things = models.ManyToManyField("B", through="ThroughModel") class B(SoftDeletionModel): text = models.TextField() class ThroughModel(SoftDeletionModel): a = models.ForeignKey(A) b = models.ForeignKey(B) extra = models.BooleanField() a = A.objects.filter(name="xyz").first() a.things.all() this fetches deleted record which is present in ThroughModel but not in B model. Ideally i want to fetch all records for B model which are not marked deleted in ThroughModel.I tried to override ThroughModel queryset but that doesn't seems to be working -
Retrieve a list of related data from mysql DB and show it in html on page load automatically
I would love to add a feature to my Django app but I am not able to find the correct way to do it. What I am trying to achieve is to obtain a list of related data when the user load a particular page of my database, automatically. By saying automatically, I mean without hitting any further button. Specifically, I have this odorant_detail.html page that shows details on a selected odourant: </script> <h1 style="text-align: center;">You are looking to {{ odorant.Name }}</h1> <fieldset> <legend>General Information</legend> <p>Pubchem ID: <strong>{{ odorant.Pubchem_ID }}</strong></a></p> <p>IUPAC Name: <strong>{{ odorant.IUPAC_Name }}</strong></p> <p>Synonim/s: <strong>{{ odorant.Synonim}}, {{ odorant.Synonim_2 }}</strong></p> <p>Molecular Formula: <strong>{{ odorant.Molecular_Formula }}</strong></p> <p>SMILES: <textarea readonly style="border:solid 2px black; background-color: #eeeeee; font-family: 'Courier New', Courier, monospace;" id="smiles" name="smiles" ro> </fieldset> <input role="button" class="btn btn-info px-3 button" type="button" id="copyID" value="Copy SMILES to clipboard" /> <script type="text/javascript"> var button = document.getElementById("copyID"), input = document.getElementById("smiles"); button.addEventListener("click", function(event) { event.preventDefault(); input.select(); document.execCommand("copy"); }); </script> <fieldset> <legend>Known Interactions</legend> </fieldset> That takes information from this model.py from django.db import models from django.urls import reverse # Create your models here. class Odorant(models.Model): Pubchem_ID = models.IntegerField(primary_key = True) Name = models.CharField(max_length =50) IUPAC_Name = models.CharField('IUPAC Name', max_length = 250) Synonim = models.CharField(max_length = 50) Synonim_2 … -
django model and manager inheritance
I have flag models what originates from Flag object and helps me to categorise types. class Flag(models.Model): title = models.CharField(max_length=20) content = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) createTime = models.DateTimeField(default=now, editable=0) class ArticleFlag(Flag): article = models.ForeignKey('articles.Article', on_delete=models.CASCADE) class CommentFlag(Flag): comment = models.ForeignKey('comments.Comment', on_delete=models.CASCADE) class QuestionFlag(Flag): question = models.ForeignKey('questions.Question', on_delete=models.CASCADE) class AnswerFlag(Flag): answer = models.ForeignKey('questions.Answer', on_delete=models.CASCADE) Then I tries to define a method on any of the child classes: class ArticleFlag(Flag): article = models.ForeignKey('articles.Article', on_delete=models.CASCADE) def test(self): return self.article.title then I tested its database storage by: from flags.models import * flags = Flag.objects.all() articleflags = ArticleFlag.objects.all() for flag in articleflags: print(flag.pk) # 1, 3 for flag in flags: print(flag.pk) # 1, 2, 3, 4, 5, 6, 7 and realised child class objects are always a subset to parent class objects, then I test its method by from flags.models import * flags = Flag.objects.all() articleflags = ArticleFlag.objects.all() for flag in flags: try: print(flag.test()) except: pass however I got nothing, even through there are instances of article flags stored in the db, it seems that the method is always undefined; then I tried this: from flags.models import * flags = Flag.objects.all() articleflags = ArticleFlag.objects.all() for flag in articleflags: try: print(flag.test()) except: pass this …