Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django docker error table not exist
I had a existing Django Rest project with an existing MySQL database (named libraries) which I wanted to Dockerize. My dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt My docker-compose: version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" Steps: I ran: docker-compose build - build was successful I ran: docker-compose up - had to run this command twice and then I could access my API by hitting localhost:8000 However, whenever I hit any API endpoint I get an error Table "XYZ" does not exist. All the tables are already present. Why this happens? -
How to pull other serialized data from different Serializer classes?
I'm trying to pull the permissions data into my UserSerializer. I have a Many To Many relationship with User to Group with a through table called GroupUser. I'm able to pull the group_id and the group_name, but I can't seem to populate the data for permissions into my User Serializer. So far I've tried using permission = serializers.ReadOnlyField(source='group.permissions') but that doesn't work. Any suggestions? Here's my code: class GroupSerializer(serializers.ModelSerializer): users = GroupUserSerializer(source='groupuser_set', many=True) permissions = PermissionSerializer(source='permission_set', many=True) class Meta: model = Group fields = ('id', 'name', 'users', 'permissions', 'role', ) class GroupUserSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField(source='group.id') name = serializers.ReadOnlyField(source='group.name') class Meta: model = GroupUser fields = ( 'id', 'name', ) class UserSerializer(serializers.ModelSerializer): tests = TestSerializer(source='test_set', many=True) groups = GroupUserSerializer(source='groupuser_set', many=True) class Meta: model = User fields = ( 'id', 'username', 'groups', 'tests', ) I want my data to look like this: { "id": 1, "username": "user", "groups": [ { "id": 2, "name": "employee" "permission": "Access-Denied" } ], "tests": [] }, but I have it without "permissions" -
Dynamically updating db_table to use one model for several database tables
I thought I ran into a roadblock with Django that would require writing raw SQL to resolve instead of using Django's ORM. I asked about it on SO and was informed it is possible to create dynamic classes or to assign db_table dynamically to the model. The issue is that I have several dozen tables that are similar. They do all have about five fields that are in them all. The remaining hundred, or so columns, are unique. (Basically each table represents industry data and a year; even within the same industry the data can vary from year to year). I was informed that Django models are pretty "loose" in that you could only identify these common columns and the model doesn't care about the rest of the columns, so you could do a Table.objects.all() and get everything in the table. My concern was I was going to need to build several dozen mostly redundant models, and have to add new ones annually which is really inefficient. I was leaning towards writing the query in raw SQL so I could dynamically specify the table name until I was informed of these things. Came across these SO questions, but I am … -
Running two databases on heroku with django
I have two databases that my Django application needs access. One is a shared database owned by a separate app with the Django app only having read access. The second is entirely owned by the Django app. For local development I am ok but I'm not sure how to configure things so that Heroku uses the second database. Currently I have the shared database promoted to DATABASE_URL and the secondary database is at HEROKU_POSTGRESQL_BLUE_URL. In my settings I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'main_database_name', 'USER': 'username', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, 'secondary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'secondary_database_name', 'USER': 'username', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } Please ask any more questions if you need me to clarify. Thanks! -
How to get objct information from Ajax response in JSON
I'm working on a site that needs to parse an Ajax response which looks something like this: {"comments": "[{\"model\": \"modelhandler.comment\", \"pk\": 4, \"fields\": {\"user\": 2, \"description\": \"hello this is a comment but I don't know if it's working yet.......\", \"replyto\": null, \"uploaded\": \"2018-01-10T20:35:40.856Z\", \"updated\": \"2018-01-10T20:35:40.856Z\"}}]"} I tried getting data from this response like this: success: function (data) { var json = JSON.parse(JSON.stringify(data)); $.each(json, function(key,value) { alert(value.comments); }); } This however alerts me undefined Here the comments field has 1 comment in it but I might have more than 1. How would I go about retrieving data from a Json response like this? EDIT: I logged data object and I got this: Object comments : "[{"model": "modelhandler.comment", "pk": 4, "fields": {"user": 2, "description": "hello this is a comment but I din't know if it's working yet.......", "replyto": null, "uploaded": "2018-01-10T20:35:40.856Z", "updated": "2018-01-10T20:35:40.856Z"}}]" __proto__ : Object in Google Chrome using console.log() also the json is generated by a django view like this: def obtain_comments(request, *args, **kwargs): begin = int(request.GET['begin']) end = int(request.GET['end']) n_comments = end - begin all_split = Comment.objects.order_by('-uploaded')[:end] data = { 'comments': serializers.serialize('json',all_split), } return JsonResponse(data) -
Django - Filter GTE LTE for alphanumeric IDs
I am trying to serve up our APIs to allow filtering capabilities using LTE and GTE on our ID look ups. However, the IDs we have are alphanumeric like AB:12345, AB:98765 and so on. I am trying to do the following on the viewset using the Django-Filter: class MyFilter(django_filters.FilterSet): item_id = AllLookupsFilter() class Meta: model = MyModel fields = { 'item_id': ['lte', 'gte'] } But the issue is, if I query as: http://123.1.1.1:7000/my-entities/?item_id__gte=AB:1999 or even http://123.1.1.1:7000/my-entities/?item_id__lte=AB:100 it won't exactly return items with ID's greater than 1999 or less than 100 since the filter will take ID as a string and tries to filter by every character. Any idea how to achieve so I can filter on IDs so I get items exactly greater / less than the numeric ID (ignoring the initial characters) ? -
Backend not Found for Facebook
I cant seem to get it to work guys, after reading similar questions my issue is not due to not specifying key and secret nor is it because i forgot to add '-oauth2' after facebook. please help?? All i see on the browser is Backend not Found. Maybe it is just because my django or python versions are too new?? I use python 3.6 and django 2.0... here is my project's settings.py SECRET_KEY = '<my_secret_key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app', 'django_filters', 'cuentas', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] # python social auth settings SOCIAL_AUTH_FACEBOOK_KEY = '<facebook_app_id>' SOCIAL_AUTH_FACEBOOK_SECRET = '<facebook_app_secret>' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.11' AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) -
PK2 as a context for a User Detail View
In my app I have two kind of users, Employees and candidates that are both part of MyUser model, with different attribute is_candidate, is_employee (True, False) My view EmployeeDetailView ( I need to change the name) is supposed to serve both, and while for employee users I am ok, for candidate user I am having an issue acceding to the User detail view because of pk2 that is not found, the PK1 is found. I In general I am having trouble to understand how to deal with multiple key arguments like Pk1 and pk2 I do not know how to define PK2 in my context my model is : class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') applicant = models.ManyToManyField(MyUser, related_name="applicant") def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk}) the view of my page with the link: class RecruitmentPage(generic.ListView): #import pdb; pdb.set_trace() model = Project template_name = "recruitment_index.html" def get_object(self, queryset=None): return get_object_or_404(Project, id=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(RecruitmentPage, self).get_context_data(**kwargs) current_project_id = self.kwargs['pk1'] applicant_list = Project.objects.get(id = current_project_id).applicant.all() app_with_resp = [] app_without_resp = [] for i in applicant_list: if len(i.response_set.all())>0: app_with_resp.append(i) else: app_without_resp.append(i) context['current_project_id'] = current_project_id context['applicant_list'] = … -
Django authentication view SetPasswordForm
I'm trying to modify password reset confirmation default template by adding styling to forms. My scripts: forms.py from django.contrib.auth.forms import SetPasswordForm class PasswordResetConfirmForm(SetPasswordForm): new_password1 = forms.CharField( label="New password", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'New password', }), ) new_password2 = forms.CharField( label="New password confirmation", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm New Password', }), ) views.py from django.contrib.auth import views as auth_views class ConfirmPasswordResetView(auth_views.PasswordResetConfirmView): form_class = PasswordResetConfirmForm template_name = 'registration/password_reset_confirm.html' password_reset_confirm.html {% extends 'base.html' %} {% block content %} {% if validlink %} <div class="mx-auto" style="width: 400px;"> <form method="post" style="background-color: #f0ebbe; padding: 20px;">{% csrf_token %} <h1>Change password</h1> <div class="form-group"> {{ form.new_password1 }} </div> <div class="form-group"> {{ form.new_password2 }} </div> <button type="submit" class="btn btn-primary">Change password</button> </form> </div> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} Problem is that, class and placeholder attributes are not passed to inputs in the template. What can be the problem? -
Why does Python Request's JSON decoder return the concatenation of top-level keys
I am using the Requests library to decode a JSON response as follows: Payload Being Decoded: { "objectOne": { "desc": "one" }, "objectTwo": { "desc": "two" } } Code: from django.http import HttpResponse import requests class ApiService: @staticmethod def say_something(self): resp = requests.get('http://127.0.0.1:9501/polls/test/') return HttpResponse(resp.json()) Output: objectOneobjectTwo I followed the simple example from the official documentation: JSON Response Content In addition I wrapped the response in [] brackets to see if the response must be in a JSON array but it just returns an array with 'objectOneobjectTwo' as the 1st and only element. -
how to use integer variable as subscript in Django template
I have a for loop in a Django template: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.i.activity_name }} {% endfor %} where this fails to output anything. The problem lies in the use of i. I know this, because this: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.0.activity_name }} {% endfor %} outputs what it is supposed to output. Why can't I use i in the way I want and how do I make this work? -
django-filter access foreign keyed entries
The problem I'm using the django-filter package to filter through my results. Suppose my models look like the following: class Material(models.Model): id name class Test1(models.Model): id materialTested = models.ForeignKey(...) TestResult class Test2(models.Model): id materialTested = models.ForeignKey(...) TestResult I am trying to filter using the package using results from both Test1 and Test2. The reason the tests are their own models is because multiples of the same test (or none) can be run for the same materials Current Progress I currently have it set up to filter using a single test by defining the following filter: class Filter1(django_filters.FilterSet): class Meta: model = Test1 fields = {'TestResult':['gte','lte']} -
django create N number of forms in template
I was wondering if it was possible to write a more generic form to use as a template so that during the render it will create as many forms as necessary? If not how would one write code to create N number of forms, where the number is Dependant on the result of some query set? I know the code below doesn't work I am leaving it in as more sudo code forms.py: class OptionalSFRForm(forms.Form): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=sfrs_models.ProtectionProfile.objects.all()) def Custom(QueryPP): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=QueryPP.Optional_SFR.objects.all()) models.py class ST_Title(models.Model): Selected_SFR = models.ManyToManyField(sfrs_models.SFR, related_name='Selected_SFR') AttachedPPs = models.ManyToManyField(sfrs_models.ProtectionProfile, related_name='ST_PPs') sfrs.models.py class ProtectionProfile(models.Model): Optional_SFR = models.ManyToManyField(SFR, related_name='Optional') template: {% for AttachedPPs in ST_Title.AttachedPPs.all %} <form action="{% url 'SecurityTarget:stview' ST_Title.id %}" method="post" id="conformanceform"> {% csrf_token %} {{OPTSFRS.Custom(AttachedPPs)}} </form> -
What is the purpose of manage.py in Django startproject?
I come from a JS background, and decided to start a Python project to learn the basics of creating/deploying an app in Python, and I do not see any concise explanations of what the purpose of manage.py is, so I decided to give it an ask. -
Django form for hidden input fields
I have two models, Post and Attachment. Attachment has a foreign key to Post. I have a PostCreateView with PostForm. While writing a post, you may upload images using jquery-fileupload (AJAX). If files are uploaded the following lines are appended to <form>. <input type="hidden" name="attachments" value="1" /> <input type="hidden" name="attachments" value="2" /> <input type="hidden" name="attachments" value="3" /> The values(1, 2 and 3) are PK for Attachment model in order to make a relationship between Post and Attachment when I save a post. I was able to get a list in view: def form_valid(self, form): attachments = self.request.POST.getlist('attachments') However, I'd like to declare the form field in PostForm for the following validations: PKs must be integers. Attachment's foreign key must be null with those PKs. A post may have NO attachment, so the attachment hidden input tag does not exist at first. That's why it could be hard to have a form field. These are appended by AJAX/jQuery. If it is diffcult, I'd like to know the best practice which method shoud be overridden in CreateView. Thank you. -
Django Rest Framework admin extend model
I am trying to extend Django Rest Framework admin model. This is the code that I have: from django.contrib import admin from .models import * from markdownx.admin import MarkdownxModelAdmin def process_topics(_, __, queryset): from person.tasks import calculate_factors for object in queryset: calculate_factors(object) process_topics.short_description = "Process topics manually" class ObjectAdmin(admin.ModelAdmin): list_display = ('pk', 'sender', 'note',) actions = [process_topics, ] # admin.site.register(Object, ObjectAdmin) admin.site.register(Object, MarkdownxModelAdmin) I would like to use ObjectAdmin to extend MarkdownxModelAdmin class. -
GeoDjango GDAL error in terminal
I have an application which I wrote some months ago which included geodjango but I now visited the project today and ran the project in my terminal and got this error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. . I since dont know how to figure it out. any help will be appritiated and further codes would be supplied on request -
django many to many modelform view
I'm newbie with django. I want to show all models in view. For example if this code is launched, it doesn't show the Author model. from django.db import models from django import forms #Models class Author(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class Peoples(models.Model): name = models.CharField(max_length=30) book = models.ManyToManyField(Book, blank=True) def __str__(self): return self.name #ModelForm class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name', 'birth_date'] class BookForm(forms.ModelForm): class Meta: model = Book fields = ['name', 'authors'] class PeoplesForm(forms.ModelForm): class Meta: model = Peoples fields = '__all__' #View def test(request): if request.method == 'POST': form = PeoplesForm(request.POST) else: form = PeoplesForm() return render(request, 'test/form.html', {'form': form} ) How diplay all models wich have servals manytomany relations ? Thanks a lot. -
Which technologies can I authorize users of my Django app to call an API Gateway endpoint?
so I'm developing a Django-based webapp and hosting it on AWS Elastic Beanstalk. Right now, users log in and are authenticated by Django's default Session based auth system. I also have a Chrome Extension, and an AWS Lambda function as part of the same system. The Chrome Extension, when installed, will periodically send requests to the AWS Lambda function via AWS API Gateway. When a request reaches API Gateway, I want to only allow Django-authenticated (authorized?) requests to pass. In the Lambda function, I would like to find out which user sent the request and process the data as required. My understanding is that I'll need to move away from session-based authentication to a public/private key encryption of some sort. I have seen AWS Cognito mentioned, OAuth2, OpenID, and JWT. I am struggling to compare these technologies as they seem to serve slightly different purposes in some cases. I see words like "authentication" and "authorization" being used and I don't fully understand the different meanings. Can anybody help me understand which technologies I can use and in what ways in order to achieve my use-case? -
django form raising keyerror when values are left to default
I have a form which is not connected to any kind of model. class NumberForm(forms.Form): quantity = forms.IntegerField(widget=forms.NumberInput(), initial=0, required=True) I create a formset out of this and then simply add up all the numbers entered by the user. This works so long as a value is entered in every input. When I leave one of the inputs on the initial value I get a keyerror trying to access cleaned_data, no matter what I set the initial value to. For example, if I manualy change all inputs to 1 I do not get a keyerror, but if I set initial=1, all values are set to 1 in my template, but when I try to submit my form once again a key error is raised. What is going on here? -
'AsgiRequest' object has no attribute 'user'
Automat-0.6.0 Django-2.0.1 asgi-redis-1.4.3 asgiref-1.1.2 attrs-17.4.0 autobahn-17.10.1 channels-1.1.8 constantly-15.1.0 daphne-1.4.2 hyperlink-17.3.1 incremental-17.5.0 msgpack-python-0.5.1 pytz-2017.3 redis-2.10.6 six-1.11.0 twisted-17.9.0 txaio-2.8.2 zope.interface-4.4.3 Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.0.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Traceback: File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/channels/handler.py" in process_exception_by_middleware 243. return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner 212. if not self.has_permission(request): File "/home/praveen/project/channels-examples/multichat/my_project/lib/python3.5/site-packages/django/contrib/admin/sites.py" in has_permission 186. return request.user.is_active and request.user.is_staff Exception Type: AttributeError at /admin/ Exception Value: 'AsgiRequest' object has no attribute 'user' -
The latest version of Python 3 is python-3.6.4 (you are using Python-3.6.4, which is unsupported) [on hold]
-----> Python app detected ! The latest version of Python 3 is python-3.6.4 (you are using Python-3.6.4, which is unsupported). ! We recommend upgrading by specifying the latest version (python-3.6.4). Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing Python-3.6.4 ! Requested runtime (Python-3.6.4) is not available for this stack (heroku-16). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Django validation in model clean() with M2M fields can not work on creation
How do you handle model validation that implies M2M fields? For example, class Object1 objects_2 = models.ManyToManyField(Object2) def clean(): # any operation implying objects_2 field. # for example: if self.objects_2.exists() ... This will work for un update, but at object creation, I will encounter this error: "<Object1>" needs to have a value for field "id" before this many-to-many relationship can be used.. I understand this error, but how would you do to make a proper validation in that case? My current workaround is to remove the objects_2 field from the form if the user is creating an Object1 instance, and force the user to edit the Object1 instance to change that field. Awful right? Thanks for your help. -
Django rest Docker with MySQl
I am trying to dockerize my Django rest project. I am using MySQL database instead of default SqlLite. My Dockerfile looks like following: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt and Docker-compose: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" I did not run docker-compose run web python manage.py migrate docker-compose build is successful However docker-compose up fails eventually saying Can't connect to local MySQL server. I am guessing that I need to install MySQl in my container as well, but do not know how. What am I missing in my Dockerfile? -
How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin?
Question for Django 2.0 with Select2 on the box. How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin? My tours app is: tours/models.py: class Tours(models.Model): country = models.ForeignKey(Countries, on_delete=None, default=None) resort = models.ForeignKey(Resorts, on_delete=None, null=True, default=None) tours/admin.py: @admin.register(Tours) class ToursAdmin(admin.ModelAdmin): list_display = ('country', 'resort',) autocomplete_fields = ('country', 'resort',) And this is my countries app: countries/models.py: class Countries(models.Model): name = models.CharField(max_length=255) class Resorts(models.Model): name = models.CharField(max_length=255) country = models.ForeignKey(Countries, on_delete=models.CASCADE, default=None) countries/admin.py: class ResortsInlineAdmin(admin.StackedInline): model = Resorts @admin.register(Countries) class CountriesAdmin(admin.ModelAdmin): list_display = ('name',) search_fields = ('name',) inlines = [ResortsInlineAdmin,] @admin.register(Resorts) class ResortsAdmin(admin.ModelAdmin): list_display = ('name', 'country',) search_fields = ('name',) Would be nice after choose value in Country field — leave in Resort field only values that relate to this Country (inlines option in countries/admin.py). Similar demo with PHP + jQuery.