Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django assertion error when testing file upload on TravisCI
I have an app that allows a user to upload a file and have it displayed on the page. I've created a test class with a method that checks whether a file (stored locally) that is uploaded is the same as the one that is returned from the POST request. This test works locally, but for some reason, when I run the test on TravisCI, the POST doesn't seem to be returning the file and the build fails. I think the error is due to the fact that I'm using the python module whitenoise to manage static files in production. Since whitenoise is storing the uploaded files somewhere different than usual, maybe the django.test.Client.post() doesn't know where to look for the file. The test was working on TravisCI before I installed whitenoise so this would seem to be the case. If I leave the whitenoise package in the requirments.txt file to be installed on the TravisCI build server, this scenario happens, but when I try to remove the package from the file, I get the following error, even though I removed the whitenoise settings from the local version of the project settings: ====================================================================== ERROR: test_uploaded_file (photoViewer.test_upload.FileUploadTestClass) ---------------------------------------------------------------------- Traceback (most recent … -
Django URL error in typing
url(r'^post/', include('post.urls')), I get "Error in typing": -
deleted django_admin_log and now i can not use the django admin
Django Version: 2.0.3 Exception Type: ProgrammingError Exception Value: relation "django_admin_log" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_ad... hen i try './manage.py sqlmigrate admin 0001' or './manage.py sqlmigrate admin 0001' I get: db1=> manage.py sqlmigrate admin 0001 db1-> \q (renew_project) renew_project@renew:~/renew$ python manage.py sqlmigrate admin 0001 BEGIN; -- Create model LogEntry CREATE TABLE "django_admin_log" ("id" serial NOT NULL PRIMARY KEY, "action_time" timestamp with time zone NOT NULL, "object_id" text NULL, "object_repr" varchar(200) NOT NULL, "action_flag" smallint NOT NULL CHECK ("action_flag" >= 0), "change_message" text NOT NULL, "content_type_id" integer NULL, "us er_id" integer NOT NULL); ALTER TABLE "django_admin_log" ADD CONSTRAINT "django_admin_log_content_type_id_c4bce8eb_fk_django_co " FOREIGN KEY ("content_type_id") REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERR ED; ALTER TABLE "django_admin_log" ADD CONSTRAINT "django_admin_log_user_id_c564eba6_fk_auth_user_id" FOR EIGN KEY ("user_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED; CREATE INDEX "django_admin_log_content_type_id_c4bce8eb" ON "django_admin_log" ("content_type_id"); CREATE INDEX "django_admin_log_user_id_c564eba6" ON "django_admin_log" ("user_id"); COMMIT; but there is no django_admin_table I have --- INSTALLED_APPS = [ 'django.contrib.admin', I use Postgresql I tried all migrations - in different way - no results Please, share your ideas - how to deal with it? Thanks -
Django 1.11 upgrade creating `user_id` constraints
I am upgrading from Django 1.8 to 1.11. There are 2 migrations included in the upgrade 0007_auth and 0008_auth. For some reason 0008 is creating a bunch of MySQL foreign key constraints that didn't exist before even though when looking at the migration all that changed was the username max_length. Here is an example of the query that is being run on one table that I recorded when running the migration ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_user_id_xxxxxx_fk` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`) From what I can read from the 1.8 documentation these constraints should already exist on the tables that have foreign keys to the User model, as should other tables that make use of foreign keys. But my database has no fk constraints at all. The reason this is a problem is because when I deploy this to production there is an ALTER TABLE being run on a huge table which results in the database being held (I cancelled before I could time it, but it was more than 10 minutes) Any idea why this is happening? And if there is a way to do it manually, or more effeciently? I can take my site down for maintenance … -
pagination not showing in Django
Hi im new to django and am trying to set up pagination but its not working i don't know why. this is my code for the project. paginator is working it is limiting to 5 but just not showing the pages number. when i type ?page=2 in the address bar it works what am i doing wrong please help. in my view class def post_list(request): queryset = Post.objects.all().order_by("-timestamp") paginator = Paginator(queryset, 5) # Show 5contacts per page page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "page_request_var": page_request_var, } return render(request, "community.html", context) in my template <div class="container"> {% for obj in object_list %} <div class="row"> <div class="col-sm-4 col-md-4"> <div class="post"> <div class="post-img-content"> <img src="http://placehold.it/460x250/e67e22/ffffff&text=HTML5" class="img-responsive" /> <span class="post-title"><b><a href='{{ obj.get_absolute_url }}'>{{ obj.title }}</a></b><br /> </span> </div> <div class="content"> <div class="author"> By <b>changeme</b> | <small> {{ obj.timestamp|timesince }} ago</small> </div> <div> {{ obj.content|linebreaks|truncatechars:120 }} </div> <div> <a href="{{ obj.get_absolute_url }}" class="btn btn-warning btn-sm">Read more</a> </div> <hr /> </div> </div> </div> … -
How to properly implement a search input with suggestions in django
I'm new to django, and i'm building a Q&A website, in the site there is a search input in the home page. What i want is to suggest related questions (by using only the title attribute of the Question entity) to the user while he is typing. After some research i found haystack (http://django-haystack.readthedocs.io/en/master/toc.html) but it seems to much, for my problem, is there a more simple way to implement this? -
Django Many to Many grouping in form
I have the following model where I want to save countries visited by tourists class Tourist(models.Model): complete_name = models.CharField(max_length=255) countries = models.ManyToManyField(Countries, realted_name='name+') class Countries(models.Model): name = models.CharField(max_length=255) region = models.ForeignKey(Region) class Region(models.Model): name = models.CharField(max_length=10) My form: class TouristForm(forms.ModelForm): countries = forms.ModelMultipleChoiceField( queryset=Countries.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Tourist This display a template with one text box to introduce the complete_name field and a list of checkbox with each row un the table Countries Complete Name -> Input text Countries -> Uk USA China Japan Italy I want to display the countries list in a diffirent way. I want to show the region, and below each region their countries. Something like this: Complete Name -> Input text Europe Uk Italy America USA Asia China Japan Do you know how can I do that? How can I custom my for to show the field Countries in this way? Thanks -
how to fill an author field with current username
I have looked at a lot of different places but none of their solutions work. This is most likely to do them being for older versions of django or my own stupidity. So I am making a blog type of app that for some reason is called reviews instead of blog... anyway I need to automatically fill up an author field with the username of the logged in user. Here is my models.py: from django.db import models from django.contrib.auth.models import User #vars # Create your models here. class reviews(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.PROTECT,) body = models.TextField() date = models.DateTimeField(auto_now_add=True, blank=True) and forms.py: from django import forms from django.forms import ModelForm from .models import reviews from django.contrib.auth.decorators import login_required class CreatePost_form(ModelForm): class Meta: model = reviews exclude = ['author'] fields = ['title', 'body',] and views: from django.shortcuts import render, render_to_response from .forms import CreatePost_form from django.http import HttpResponseRedirect # Create your views here. def reviewlist(request): return render def index(request, ): return render(request, template_name="index.html") def CreatePost(request): form = CreatePost_form(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/reviews/succesfulpost') return render(request, "reviews/CreatePostTemplate.html", {'form':form}) def succesfulpost(request): return render(request, "reviews/succesfulpost.html") -
Drop Down Menu in Django displaying as text field
I've followed the process laid out on the Django ModelForm's documentation, as well as a couple of tutorials. My field displays as a standard text-entry, rather than a drop down. Can anyone point me in the right direction? forms.py from .models import Authority # change to rating!!! from django import forms class AuthorityForm(forms.ModelForm): class Meta: model = Authority fields = ('authority_name',) views.py from django.shortcuts import render from django.views.generic import CreateView from .models import Authority from .forms import AuthorityForm # Create your views here. class HomeCreateView(CreateView): model = Authority form_class = AuthorityForm template_name = 'home.html' success_url = 'home.html' models.py from django.db import models # Create your models here. class Authority(models.Model): authority_name = models.CharField(max_length = 100) authority_url = models.URLField() def __str__(self): return self.authority_name class Rating(models.Model): authority_name = models.CharField(max_length = 100) ratings = models.CharField(max_length = 20000) # Could this be reduced if remove the trailing letters of non-int values? # Perhaps all values could be one-hot encoded home.html <h2>Choose Authority:</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Submit</button> </form> -
Connecting Django to MSSQL Server Express 2014 database
I'm running Django (1.8) off a Ubuntu server, using VirtualEnv and Pip. pip freeze astroid==1.5.3 backports.functools-lru-cache==1.4 configparser==3.5.0 Django==1.8 django-mssql==1.8 django-pyodbc==1.1.1 django-pyodbc-azure==1.11.0.0 django-sqlserver==1.11 enum34==1.1.6 future==0.16.0 inflection==0.3.1 isort==4.2.15 lazy-object-proxy==1.3.1 mccabe==0.6.1 peewee==3.1.5 pkg-resources==0.0.0 psycopg2==2.7.3.1 pyad==0.5.15 pylint==1.7.4 pyodbc==4.0.19 PyPiwi==1.8 python-tds==1.8.2 pytz==2017.2 singledispatch==3.4.0.3 six==1.11.0 South==1.0.2 wrapt==1.10.11 I'm currently struggling with sqlserver_ado ENGINE and am using it because it seems to be the most popular, but am aware of django.db.backends.postgresql_psycopg2 and sql_server.pyodbc, and am willing to jump ship at the drop of a hat. So my DATABASES definition looks like this: 'default': { 'NAME': 'DB_NAME', 'ENGINE': 'sqlserver_ado', 'HOST': 'HOSTNAME\\SQLEXPRESS', 'PORT': '56988', 'USER': 'mssql_name', 'PASSWORD': 'mssql_pw',} Django runs with this information. Fantastic. But when I hit my function, def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("SELECT * FROM [GM].[Acct]") row = cursor.fetchone() return row I get an exception: When using DATABASE PORT, DATABASE HOST must be an IP address. If I try to change the host to an IP address, Django won't run, and spews this: File "/home/jason/env/local/lib/python2.7/site-packages/sqlserver_ado/dbapi.py", line 183, in connect import pythoncom I've tried pip install pypipwin32. When I run django using python3, I get ImportError: No module named 'sqlserver_ado' If anyone is able to nudge me in the right direction that would be appreciated. -
Opening a PDF based on URL
So, my goal here is for a user to click the link for an invoice, and it opens up a window with the PDF of that invoice displayed. Currently, I'm getting the following error: NoReverseMatch at /laptops/invoices/ Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/wordpress-pdf-invoice-plugin-sample.pdf'}' not found. 1 pattern(s) tried: ['laptops\\/invoices\\/(?P<invoice>[^/]+)\\/$'] Bad programming practices, I know. I just wanted to get it to work before I cleaned it up a bit, but I don't know what I'm doing wrong. urls.py urlpatterns = [ path('',views.laptop_list, name ="list"), path('add/',views.laptop_add,name="add"), path('invoices/', views.invoice_list,name="invoices"), path('invoices/<str:invoice>/', views.pdf_view, name ="pdfview") ] views.py def pdf_view(request, invoice): invoicename=Laptop.objects.get(invoicename=invoice) pdfpath = settings.MEDIA_ROOT with open(pdfpath+'/'+invoicename, encoding="latin-1") as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') return response laptop_invoices.html <h2>View invoices</h2> {%for i in invoices%} <ul> <li> <a href = "{%url 'laptops:pdfview' invoice=i.invoice%}"> {{i.invoice}} </a> </li> </ul> {%endfor%} -
Django rest framework serializer with reverse relation
I have two models where employee have relation with person model but person have no relation with employee model. Like: class Person(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) class Employee(models.Model): person = models.ForeignKey(Person, related_name='person_info') code = models.CharField() In such cases I want code field data in person serializer. I solved this with model method or serializer method def get_employee_code(self): return Employee.objects.get(person=self).id and add this as source in person serializer employee_code = serializers.CharField(source='get_employee_code') Or adding employee serializer into person serialiszer class PersonSerializer(serializers.ModelSerializer): employee = EmployeeSerializer() class Meta: model = Person fields = ('name', 'address', 'employee') But i was trying to do this with reverse relation but i can't. I have tried like this, it gives an error Serializer: class PersonSerializer(serializers.ModelSerializer): employee_code = serializers.CharField(source='person_info.code') class Meta: model = Person fields = ('name', 'address', 'employee_code') How can i solve this with reverse relation? -
How can I add an extra field to a proxied model in Django?
I'm specifically talking about the Tag model, which I have no much experience with. The code goes like this: @register_snippet class ArticleTag(index.Indexed,Tag): class Meta: proxy=True search_fields = [ index.SearchField('name', partial_match=True), index.SearchField('slug', partial_match=True), ] The Tag model has two fields, 'name' and 'slug'. But now I want to add a third custom field named 'type' that will be simply a CharField. I tried modifying it like this: @register_snippet class ArticleTag(index.Indexed,Tag): class Meta: proxy=True search_fields = [ index.SearchField('name', partial_match=True), index.SearchField('slug', partial_match=True), ] merge_to = models.CharField(max_length=500, blank=True, null=True) panels = [ FieldPanel('name'), FieldPanel('slug'), FieldPanel('merge_to'), ] However the server yields: ERRORS: ?: (models.E017) Proxy model 'ArticleTag' contains model fields. How can I achieve what I am trying to do? -
DJANGO: How to make validation of multiple forms based on class based views?
I have the problem with validating two forms at once. Help me, please. I need to validate field , but, as I understand, I cant pass to form_invalid method. class TrainerCreateView(ActiveOnlyMixin, BrandOwnersPermissionMixin, CreateView): form_class = TrainerForm model = Trainer second_form_class = UserCreationForm def get_context_data(self, **kwargs): context = super(TrainerCreateView, self).get_context_data(**kwargs) context['user_form'] = self.second_form_class def form_valid(self, form): ....... def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form)) from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm class UserCreationForm(UserCreationForm): first_name = forms.CharField(required=True, label='Имя') last_name = forms.CharField(required=True, label='Фамилия') class Meta: model = User fields = ("email", "username", "password1", "password2", 'first_name', 'last_name') def clean_username(self): username = self.cleaned_data['username'] if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists(): raise forms.ValidationError(u'Username "%s" is already in use.' % username) return username Thank you! -
Test if docker memcached container is used
I am using memcached for caching in django and both are in separate containers. Everything seems to be working well, however, how can I make sure that the new caching mechanism is being used? I have read about a couple of approaches (telnet, cache.set and cache.get etc.), but I am not sure if they will yield an appropriate result, when both are in different docker containers. -
Storing several informations in one variable in Django Models
class Cities(models.Model): city_main_image = models.FileField() city_name = models.CharField(max_length=200) city_info = models.CharField(max_length=1000) city_images = models.FileField() In my models.py I have Cities class and I want to upload several images for this class variable, to be clearly for city_images variable how can I do this? Are there any way to do this or not? -
Returning the text value of Choice Field in DRF serializer
How do I return the "character" value of a Choice field in a Serializer Class. Sample code below. from rest_framework import serializers from model_utils import Choices from django.utils.translation import ugettext_lazy as _ COMPANY_TYPE = Choices( (1, 'Public', _('Public Company')), (2, 'Private', _('Private Company')), (3, 'Other', _('Other Type')), ) class Company(serializers.ModelSerializer): company_type = serializers.ChoiceField(choices=COMPANY_TYPE) company_type_name = serializers.ReadOnlyField(COMPANY_TYPE['company_type']) # <=== This is the issue class Meta: model = Company fields = ('id', 'title', 'company_type', 'company_type_name') If say an entry in the company table has company_type = 1, and a user makes an API request, I want to include the extra field of company_type_name with the value Public Company. So the issue is am unable to pass the current value of company_type to the serializer so that it can return the String value of the Choice Field. -
Django Cache Manifest Not Including Files
I'm trying to cache some files which I'll be using over and again and won't change too often. I am using cache manifest in Django. I get the idea of how to use it and and I see the console actually including all files in the cache when I load the web app landing page. However when I navigate off it and then to it again errors appear (::net err appears ) for some files. Why is it so inconsistent? Also, if I am using Google analytics within these pages i can't exactly include that in the manifest so it wouldn't load it which is a problem. I want to be able to choose what is cached and what is not. Is there a way of caching some things and the loading the page from a mix of the cached files as well as the static files in the page which are not in the manifest? This would be ideal for me. -
Django Table went missing?
I was trying to add a column to a table in Django through modifying my models.py, as well as adding the column in the mytemplate.html , but after i tried modifying the models.py physically the entire table wont show up now. I did find out that i was trying to add the column wrong and that i was supposed to use:python manage.py makemigrations But it didn't bring the table back (eventtable) nor did it add the column, (although it could've added it for all i know , i just cant see the table at all anymore) What can i do to get my table back? Part 2 of my question is i have another table (deletetable) that refrences (shares) the same DB table (postgreSQL) as 1 other (maintable). my question is why does THAT table (deletetable) now say there is no data in the table , yet, the maintable still shows everything... can i not reference the same table and show its data on 2 different html (template) pages? By the way, I upgraded to django 2.0 from 1.8 recently, and my deletetable 's data disappeared after the upgrade. The eventtable completely disappeared (column titles and all) BEFORE i even … -
Django - I get "Page not found (404)" after I try to log in (Shared Hosting)
I installed Django in my server, after that i was able to see the "IT WORKED" page and the "Django administration" page (www.mydomain.com/admin). I sync my Database (No problem with that), I collected my static files as well The problem comes when I try to login into the administration page, After I try to login with or without the correct username or password I get: I checked my urls.py and didn't find anything out of the ordinary: project/urls.py: from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from app_belldent import views from django.conf import settings from django.conf.urls.static import static from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from sitio_belldent import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^$', views.inicio, name="inicio"), url(r'^servicios/$', views.servicios, name="servicios"), url(r'^portafolio/$', views.portafolio, name="portafolio"), url(r'^contactenos/$', views.contact, name="contactenos"), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() app/urls.py: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.inicio), url(r'^servicios/$', views.servicios, name="servicios"), url(r'^portafolio/$', views.portafolio, name="portafolio"), url(r'^contactenos/$', views.contact, name="contactenos"), url(r'^inicio/$', views.inicio, name="inicio"), url(r'^thanks/$', views.thanks, name='thanks'), ] -
Server error(500) in page
I have created a code to display a value of percent in html page. percentage.py from plagiarism.lines import length1,length2 from plagiarism.samelines import same_lines def percent(): a=length1() a1=length2() print("number of lines in file1 and file2: ") print(a,a1) b=same_lines()/a*100 print("percentage :") return b example3.py from django.shortcuts import render from plagiarism.percentage import percent from plagiarism.lines import length1,length2 from plagiarism.samelines import same_lines from plagiarism.file3 import tokens1 def getresult(request): data=percent() return render(request,'plagiarism/page3.html',{'data': data}) plagiarism/page3.html {% block h1 %} {% endblock %} <body> <h1> Here is your Result </h1> <h2> {{data}} </h2> </body> I expect an output of the percent. I can assure you that the code written for percent() is correct, as I've checked it. So I need an output in the html page showing HERE ARE YOUR RESULTS 86.66 But instead I get Server error(500) -
Django Tutorial polls app reponds with 404
I'm getting an error trying to run the polls app example for Django. I know there were similar questions here but most of them were about using '^$' instead of '^&' or having the wrong path to urls.py mysite/mysite/urls.py is : from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] mysite/polls/views.py is : from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") mysite/polls/urls.py is : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] I'm getting 404 if I run this. If I remove polls entry from mysite/urls.py the admin part works. If I include polls there, I get `Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The empty path didn't match any of these.` Any insight would be greatly appreciated. I know this must be some silly mistake from my end. Thank you in advance -
Included URLconf does not have any patterns in it
I was following the django tutorials on the website and I got to a point where I get an error by when I run python manage.py runserver. My django version is 1.11.1 In my settings.py file, I set: ROOT_URLCONF = 'SimpleVotingApp.urls' The SimpleVotingApp.urls file looks like this: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] And my polls.urls file looks like this: from django.conf.urls import url from . import views urlPatterns = [ url(r'^$', views.index, name='index'), ] I keep getting the error below when I run the python manage.py runserver command. Unhandled exception in thread started by <function wrapper at 0x10f3cb410> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in … -
How to run Django migrations in Google App Engine deployment step
I have a Django app up and running in Google App Engine flexible. I know how to run migrations using the cloud proxy or by setting the DATABASES value but I would like to automate running migrations by doing it in the deployment step. However, there does not seem to be a way to run a custom script before or after the deployment. The only way I've come up with is by doing it in the entrypoint command which you can set in the app.yaml: entrypoint: bash -c 'python3 manage.py migrate --noinput && gunicorn -b :$PORT app.wsgi' This feels a lot like doing it wrong. A lot of Googling didn't provide a better answer. -
Adding additional attributes to a Django field
Consider this Family model in Django: class Family(models.Model): EMPLOYEE = 'Employee' PARTNER = 'Partner' BIRTH_PARENT_CHOICES = ( (EMPLOYEE, EMPLOYEE), (PARTNER, PARTNER), ) employee_user = models.OneToOneField(User, blank=True, null=True, related_name='employee_family') partner_user = models.OneToOneField(User, blank=True, null=True, related_name='partner_family') employee_first_name = models.CharField(max_length=255, blank=True) employee_last_name = models.CharField(max_length=255, blank=True) employee_email = models.CharField(max_length=255, blank=True) employee_phone = models.CharField(max_length=255, blank=True) partner_first_name = models.CharField(max_length=255, blank=True) partner_last_name = models.CharField(max_length=255, blank=True) partner_email = models.CharField(max_length=255, blank=True) partner_phone = models.CharField(max_length=255, blank=True) point_of_contact = models.CharField(max_length=255, choices=BIRTH_PARENT_CHOICES) A Family consists of an employee and a partner, both of which have various attributes (user, first name, last name, email, phone). There is also a point_of_contact field which is either 'Employee' or 'Partner'. What I'd like to be able to do is to, on an instance family of Family, do something like family.point_of_contact.phone_number which would resolve to family.employee_phone_number if family.point_of_contact == Family.EMPLOYEE and family.partner_phone_number otherwise, and similarly for first_name, last_name, etc. As far as I can tell from https://docs.djangoproject.com/en/2.0/ref/models/fields/, however, it isn't possible to define additional attributes on Django fields. Is there some other way I could do this?