Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does OneToOne relationship cause long load - very slow Django?
I've added a OneToOneField to my models.py. Once I do this my detail view takes almost a minute to load when before it took less than a second. See below list for reference method flowchart of what Django docs says happens in a DetailView. Whatever is happening its happening after render_to_response (last one) and get_success_url (not listed). I added a print('HELLO') to both. I see render_to_response's HELLO immediately. Chrome spins/loads for a minute or two. And then I see get_success_url's HELLO. What happens between render_to_response and get_success_url? Method Flowchart setup() dispatch() http_method_not_allowed() get_template_names() get_slug_field() get_queryset() get_object() get_context_object_name() get_context_data() get() render_to_response() -
Why does the 'setAttribute' function not work in javascript?
I am working on a django project and have a simple javascript inline code and want to disable a button and enable another one when some condition meets. I tried three method to do that but when condition meets and i expect to run code, no one work for me and nothing happend. here is this part of my code: {% else %} <script > document.getElementById('prevBtn').removeAttribute('disabled'); document.getElementsByTagName('button')[0].disabled='disabled'; document.getElementById("nextBtn").setAttribute('disabled','disabled'); </script> <h2 > finished <h3> THANK YOU FOR YOUR TIME <br> BYE! </h3> </h2> {% endif %} <br> <div><br> <button type="submit" id="nextBtn" name="nextBtn">next </button> <br><br> <button type="button" id="prevBtn" name="prevBtn" disabled>previous</button> </div> Before i submit this question i read some similar questions and all suggest above approachs as answer. i'm confused what is wrong with my code. thank in advance for any help. -
Django Serializer relation problem : Got KeyError when attempting to get a value for field
I have a two model which one of them includes relation to the other like this: class RapicModel(models.Model): app = models.ForeignKey(RapicApp, on_delete=models.CASCADE, blank=True, related_name = "app") name = models.CharField(max_length=20, blank=False, default='undefined') class Field(models.Model): model = models.ForeignKey(RapicModel, on_delete=models.CASCADE, blank = True, related_name='rapicfields') fieldtype = models.ForeignKey(FieldType, on_delete=models.CASCADE, blank=False) name = models.CharField(max_length=20, blank=False, default='undefined') max_length = models.IntegerField(blank=False, default=30) blank = models.BooleanField(blank=False, default=False) default = models.CharField(max_length=200, blank=True, default='undefined') And these are the serializers: class RapicModelSerializer(serializers.ModelSerializer): rapicfields = FieldSerializer(many=True) class Meta: model = RapicModel fields = ('id','app', 'name', 'rapicfields') def create(self, validated_data): field_list = validated_data.pop('rapicfields') rapicmodel = RapicModel.objects.create(**validated_data) for single_field in field_list: Field.objects.create(model=rapicmodel, **single_field) return rapicmodel class FieldSerializer(serializers.ModelSerializer): class Meta: model = Field fields = ('id','model', 'fieldtype', 'name', 'max_length', 'blank', 'default') When I try to post a new rapicmodel with some fields in it with this JSON: { "app": 7, "name": "myfirstmodel", "rapicfields": [ { "fieldtype": 1, "name": "myfirstfield" }, { "fieldtype": 1, "name": "mysecondfield" } ] } I am getting this response: KeyError at /rapicmodel/ "Got KeyError when attempting to get a value for field `rapicfields` on serializer `RapicModelSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'rapicfields'." I really don't understand … -
Hide button when item is in the cart
I have got a product page where I have a button to add item to the cart and to remove it. <a href="{{ object.get_add_to_cart_url }}" class="btn btn-primary btn-md my-0 p" style="margin: 0;"> Add to cart <i class="fas fa-shopping-cart ml-1"></i> </a> <a href="{{ object.get_remove_from_cart_url }}" class="btn btn-danger btn-md my-0 p"> Remove from cart </a> I want to hide the remove button, until the item is in the cart, what if statement would have to be use to achieve that? Here's my function to add item to the cart: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") -
Deserializing model with multiple parent models throws "...object has no attribute..." error
First of all sorry for the long post. I'm just trying to really break down the issue. I'm using the django-moderation and django-comments-xtd packages to implement moderation for comments. I use the following model on top: class VotableComment(XtdComment): vote_score = models.IntegerField(db_index=True, default=0) (...) The XtdComment itself inherits from the Comment model from the django-comments package. Behind the hood all this works through OneToOneFields i.e.: migrations.CreateModel( name='XtdComment', fields=[ ('comment_ptr', models.OneToOneField(auto_created=True, primary_key=True, parent_link=True, serialize=False, to='django_comments.Comment', on_delete=models.CASCADE)), (...) migrations.CreateModel( name='VotableComment', fields=[ ('xtdcomment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='django_comments_xtd.XtdComment')), (...) This means that a VotableComment object should have both comment_ptr and xtdcomment_ptr as attributes. The error comes when django-moderation tries to set the changed_object attribute (which refers to the VotableComment object) of its ModeratedObject model which is a SerializedObjectField field. Then I get: The underlying issue happens when deserializing and trying to set the values of the VotableComment object's fields obtaining the value from its parent models. In particular the comment_ptr field: As you can see there is a problem when trying to set comment_ptr with value <Comment: :...> on the VotableComment model because later on related_descriptors.py is first trying to resolve all the inherited_pk_fields. There are two of them which come from the … -
Docker-compose Django Supervisord Configuration
I would like to run some programs when my django application running. That's why I choose supervisord. I configured my docker-compose and Dockerfile like : Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 # some of project settings here ADD supervisord.conf /etc/supervisord.conf ADD supervisor-worker.conf /etc/supervisor/conf.d/ CMD ["/usr/local/bin/supervisord", "-c", "/etc/supervisord.conf"] docker-compose: api: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" restart: unless-stopped container_name: project volumes: - .:/project ports: - "8000:8000" network_mode: "host" supervisord.conf [supervisord] nodaemon=true [include] files = /etc/supervisor/conf.d/*.conf [supervisorctl] [inet_http_server] port=*:9001 username=root password=root So my problem is when I up the docker-compose project and other dependencies (postgresql, redis) works fine but supervisord didn't work. When I run "supervisord" command inside container it's working. But in startup, It don't work. -
create() takes 1 positional argument but 2 were given
I'm using Django and allauth trying to get a signup page working but for some reason it does not work. Whenever I have entered all the sign up data that's required and press Create an account it gives me this error; TypeError at /accounts/signup/ create() takes 1 positional argument but 2 were given This is my signup script; {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <main> <div class="container"> <section class="mb-4"> <div class="row wow fadeIn"> <div class='col-6 offset-3'> <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class='btn btn-primary' type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </section> </div> </main> {% endblock %} -
How to fix NoReverseMatch? Reverse for 'porumbei' not found. 'porumbei' is not a valid view function or pattern name
I'm trying to edit some objects in django but when I'm accessing the view for editing it says that reverse not found. I've read almost all articles about noreversematch but none answered to my question. I'm new to django and maybe that could be the reason. Can anyone help me to fix that? Thanks! My code bellow. My view: @login_required(login_url='/auth/login/') def editareporumbei(request, pk): """ Pagina editare informatii porumbel """ global semi_frati sts = StatusPorumbei.objects.all() porumbel = get_object_or_404(Porumbei, pk=pk) if porumbel.crescator != request.user: raise PermissionDenied() descendenti = Perechi.objects.filter(Q(mascul=porumbel) | Q(femela=porumbel)) if porumbel.tata and porumbel.mama: frati = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))).exclude(serie_inel=porumbel) rude_tata = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & ~Q(Q(mama=porumbel.mama))) rude_mama = Porumbei.objects.filter(~Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))) vitregi = rude_tata | rude_mama semi_frati = vitregi.distinct() else: frati = None semi_frati = None try: rating_porumbel = Rating.objects.get(porumbel=porumbel) except Rating.DoesNotExist: rating_porumbel = None if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES, instance=porumbel) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return redirect('/porumbei/vizualizare') else: form = AdaugaPorumbel(instance=porumbel) context = { 'form': form, 'porumbel': porumbel, 'descendenti': descendenti, 'rating_porumbel': rating_porumbel, 'sts': sts, 'frati': frati, 'semi_frati': semi_frati, } template = loader.get_template("editare-porumbei.html") return HttpResponse(template.render(context, request)) My urls: urlpatterns = [ path('porumbei/vizualizare/', porumbei.views.viewpigeons, name='allpigeons'), path('porumbei/adaugare/', porumbei.views.porumbelnou, name="porumbelnou"), path('porumbei/editare/<int:pk>/', porumbei.views.editareporumbei, name='editareporumbei'), ] Template: <a href="{% url 'editareporumbei' … -
List objects of logged current user
I would like to ask how I could list all objects of logged current user via class based view in django. I have two apps in the project. One is called users and the other one is badminton. users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) badminton/models.py from django.db import models from users import models as users_models class Player(models.Model): name = models.OneToOneField(users_models.Profile ,null=True, on_delete=models.CASCADE) matches_played = models.IntegerField(default=0, blank=True, null=True) class Match(models.Model): player_home = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_home') player_away = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_away') How I can access all matches of logged user via queryset? Thank you for your help! -
Cannot find template url in django
I have this project structure, foo_project - templates - base.html - photo_list.html - photo_create.html - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - photo - __init__.py - admin.py - apps.py - models.py - tests.py - urls.py - views.py In apps.photo.views.py, from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.views.generic.detail import DetailView from .models import Photo class PhotoList(ListView): model = Photo template_name_suffix = '_list' class PhotoCreate(CreateView): model = Photo field = ['title', 'body', 'created', 'image'] template_name_suffix = '_create' success_url = '/ in foo_project/settings.py from os.path import abspath, dirname, join BASE_DIR = dirname(dirname(abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In foo_project/urls.py, from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static urlpatterns = [ path('', include('apps.photo.urls')), ] photo.urls, from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import PhotoList, PhotoCreate, PhotoDelete, PhotoDetail, PhotoUpdate app_name = 'photo' urlpatterns = [ path('', PhotoList.as_view(), name='index'), path('create/', PhotoCreate.as_view(), name='create'), ] When I hit the localhost:8000, it cannot find my template photo/photo_list.html, but I don't see anything missing. … -
TemplateDoesNotExist at / error in Django
I'm new to Django, and trying to create my first project. I tried to resolve the above mentioned error, spent hours banging my head against the wall, but was unable to correct it.. Given below are the relevant files. I guess it must be a small thing that I am missing, but unable to pin point it. Views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from datetime import timedelta def home(request): if request.GET.get('type') == 'formdata': options = {'fruits': [], 'vendors': [], 'release_version': []} try: options['fruits'] = ['Mango', 'apple', 'banana'] options['vendors'] = ['Amazon', 'flipkart', 'myntra'] options['release_version'] = ['2015','2016','2017','2018'] today = datetime.today() options['end_date'] = today.strftime('%Y-%m-%d') last_week_date = today - timedelta(days=7) options['start_date'] = last_week_date.strftime('%Y-%m-%d') return JsonResponse({'options': options}) except: return JsonResponse({'message': 'An error occured while getting form data'}) return render(request, 'index.html') else: return render(request, 'index.html') Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home') ] The index.html is the template I want the urls.py to point to, and is in the templates/project_name folder in my project. I have also set the TEMPLATES_DIR in the settings.py. I wonder where I am going wrong. Any help is appreciated. -
Django- how to use server time in views when retrieving data from different timezone?
I have set a timezone in America in settings.py. All data are set in American Timezone in database. If today's date in America is 14 march but in Asia it's 15 March. So if I retrieve today's object from Asia it's not showing anything because it is stored in American time which is 14 march and in Asia it's 15. So it is not showing anything. So how to use server time in views.py so that it will retrieve object based on server time no matter where you stay -
Django let's you go back after logout and see the previous pages
I just noticed that, in Firefox, if you go back to the previous pages after logging out, you are still able to see the pages you navigated. As soon as you click to another page you are asked to login, but if you don't click anything you are able to navigate the pages you used while logged in. Has anyone seen this behaviour and was able to solve it? -
Using environment variables for mysql database password and host throws errors
I'm trying to set up a mysql database and secure sensitive information in an .env file. I was able to successfully store the database NAME, but using environment variables for the PASSWORD and HOST throws two different errors: Error for PASSWORD: Exception Type: OperationalError at / Exception Value: (1045, "Access denied for user 'studio413'@'10.0.0.32' (using password: NO)") Error for HOST: AttributeError at / 'NoneType' object has no attribute 'startswith' Putting the actual PASSWORD and HOST directly into the settings.py works perfectly, and I believe I've properly set up the environment variables, as the database NAME works fine. Typing echo $DATABASE_PASSWORD and echo $DATABASE_HOST into my console yields the correct information from my .env file. I'm using PythonAnywhere and followed the instructions for setting up environment variables here: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ If it helps, here is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'studio413$default', 'USER': os.getenv("DATABASE_USER"), 'PASSWORD': os.getenv("DATABASE_PASSWORD"), 'HOST': os.getenv("DATABASE_HOST"), } } If anyone could help me solve this, I would greatly appreciate it! Note: I tried providing the full traceback for each error, but stackoverflow would not let me post them (it thought I was posting spam). -
Testing multiple viewport sizes with Django/Selenium
I'm trying to test characteristics of certain UI elements given different viewport sizes and media defined in CSS. I have a setup function to instantiate a headless Chrome browser with I believe a default viewport size of 800x600: class NewDesktopVisitorTest(StaticLiveServerTestCase): def setUp(self): self.chrome_options = Options() self.chrome_options.add_argument('--headless') self.browser = webdriver.Chrome(options=self.chrome_options) This works well for testing what I would consider the desktop version of a page, but I'd also like to make sure the mobile version renders as I'd expect. I can create a completely separate class with a different setup and specify the viewport size like so: class NewMobileVisitorTest(StaticLiveServerTestCase): def setUp(self): self.chrome_options = Options() self.chrome_options.add_argument('--headless') self.chrome_options.add_argument('--window-size=375,800') self.browser = webdriver.Chrome(options=self.chrome_options) This has the benefit of very cleanly showing where a given test is failing (i.e. desktop or mobile). The trouble is that I want the exact same tests to run against both (and potentially multiple) viewport sizes, and I don't want to have to maintain the exact same tests in multiple classes. Most of my searches for parameterized testing yield solutions for running the same tests against different data sets, but I've yet to find examples of solutions for setting up and running the same tests against multiple starting configurations. I'm hesitant … -
Have to use model name instead of field name when queriyng ManyToManyField from django model
I have the following model: class ShoppingList(models.Model): name = models.CharField(max_length=100, default='Main') owners = models.ManyToManyField(User, through='ListOwner') class ListOwner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) shopping_list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE) is_main_owner = models.BooleanField(default=False) Next, I'm trying to query ShoppingList for the current user. I used this https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships as an example. I expected that right way to do it is to use this construction: @login_required def index(request): shopping_list = ShoppingList.objects.filter(owners__user=request.user)\ .order_by('id').first() # something else but in this case, I get an error: Related Field got invalid lookup: user Everything works fine if use listowner instead of owner in filter() function like this: shopping_list = ShoppingList.objects.filter(listowner__user=request.user)\ .order_by('id').first() Can anybody please explain to me why the first one isn't working (while it is recommended to use it in Django documentation)? -
Integration with paypal redirect issue
I am integrating paypal with my openedx ironwood install. To implement ecommerce capabilities - openedx ironwood uses django oscar shopping cart. It works to the point where one can enter their credit card information and submit the form. However after submitting the form the following error occurs and this is the corresponding address in the address bar: https://http/payment/paypal/execute/?paymentId=PAYID-LZWTHVY60U970153W662623L&token=EC-45D081042G524235T&PayerID=UBRT2SFRKASXL Any idea on how I can fix this? -
Extending UserCreationForm new field doesn't appear in admin pannel
I am adding a new field to django UserCreationForm. Everything is working fine - I can see the new fields in the html form but when I open django admin panel the new field is not there. Any ideas what am I missing? forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserSignupFrom(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) is_worker = forms.BooleanField(required=False) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'is_worker', 'password1', 'password2'] views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserSignupFrom from django.contrib import messages def sign_up(request): if request.method == 'POST': form = UserSignupFrom(request.POST) if form.is_valid(): form.save() messages.success(request, 'account was created') else: form = UserSignupFrom() return render(request, 'login/sign_up.html', {'form': form})``` if you need to see some other files please let me know! -
Wagtail CMS not rendering navigation icons/images
I've recently taken over working on a Django/Wagtail app that has a few bug that needs fixing. One of which is the icons/images in the CMS are not displaying in the menus and throughout the entire CMS, which is making navigation confusing for the users. Anyone have insights as to why fonts etc are loading, but not the icons (see image below for one example) Wagtial CMS Rendering Issue -
How do I pass a boolean for each post in my function view?
My views.py def problems_list(request): queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31']) def is_liked(self): is_liked = False if self.likes.filter(user=request.user.username).exists(): is_liked = True return is_liked context = { 'posts': queryset, 'is_liked': is_liked } return render(request, 'main/problem.html', context) I want each post to have a variable is_liked that is True or False so that I can pass it in my html. -
Is there are difference between working with Django vs Django on Anaconda
I am learning Django and I saw that you can install it regularly, according to the Django documentation. But I also saw that you can work with it in Anaconda. Is there a difference in developing? Or is it all just the same. Thanks -
how to customize django jwt graphql authentication
Hi I'm trying to customize jwt graphql Django default authentication I need to achieve log in with username or email normal Django we customized authentication backend. mutation{ tokenAuth(username:"myemail@email.com" password:"pass") { token } } Authenticate with username mutation{ tokenAuth(username:"myname" password:"pass") { token } } the normal username is working fine. how I can authenticate the user by username or email in jwt graphql I tried this link https://django-graphql-jwt.domake.io/en/latest/customizing.html I don't get any idea about that... Does anyone have any idea about that?? -
How to build Bootstrap collapse (dropdown) plugin in Django-CMS 3.x?
Building plugins in Django-CMS 3.x is wonderfully documented. It would be awesome if I was able to drag some of my custom plugins and nest them into a dropdown (Bootstrap 4 Collapse). Initially, I figured I could just have a placeholder in a custom model and drag other plugins into that placeholder. But that doesn't fly. Anyone have a suggestion on how to get this done? -
CORS fonts Issue Google Cloud Storage with Django application
I just deployed a Django app, using Django Storages which is connected to a Google Cloud bucket of mine. But I am getting these CORS errors in my console (** resembles my domain, just removed it for safety): Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff2' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff2 net::ERR_FAILED Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff net::ERR_FAILED Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.ttf' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**/static/css/fontawesome/webfonts/fa-solid-900.ttf net::ERR_FAILED I followed this SO post and answer: https://stackoverflow.com/a/39758208/10938976 Settings the CORS rules for my bucket like this: [ { "origin": ["*"], "responseHeader": ["Content-Type"], "method": ["GET"], "maxAgeSeconds": 3600 } ] But it does not fix my problem, even after recollecting all my static files, I still get the same error. What is going wrong? -
Django Choice Field initial value ignored when form is rendered
I'm running into an issue where I set the initial value on a Choice field for County but when I render the form, the corresponding option doesn't render as selected. I can't figure out why this isn't working. Does anyone have any ideas? Models.py class State(models.Model): name = models.CharField(max_length=30, db_index=True) abbreviation = models.CharField(max_length=2, unique=True, db_index=True) class County(models.Model): name = models.CharField(max_length=30, db_index=True) state = models.ForeignKey(State, on_delete=models.CASCADE) Forms.py class MyForm(forms.Form): state = forms.ChoiceField(choices=[], required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) county = kwargs.get('county') state_qs = State.objects.all().values('id', 'name', 'abbreviation') state_choices = [ (choice['id'], f"{choice['name']} ({choice['abbreviation']})") for choice in state_qs] self.fields['state'].choices = [('', '---------')] + state_choices county_qs = County.objects.select_related('state').filter(state__id=state).order_by( 'name').values('id', 'name', 'state', 'state__abbreviation') county_choices = [ (choice['id'], f"{choice['name']}-{choice['state__abbreviation']}") for choice in county_qs] initial = None if county: initial = county.id self.fields['county'] = forms.ChoiceField(choices=county_choices, initial=initial)