Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
flask-socketio 400 (BAD REQUEST) & Invalid session
i use example app(https://github.com/miguelgrinberg/Flask-SocketIO/tree/master/example) statrt on local windows ok, but on server centos failed error 400, i use gunicorn + nginx + eventlet. logs: 2019-12-19 16:20:41,694 - INFO: 30bd9dce92f245698ae73dfec9fc0197: Sending packet MESSAGE data 0 - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] 2019-12-19 16:20:41,730 - INFO: 30bd9dce92f245698ae73dfec9fc0197: Received packet MESSAGE data 0/test, - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:52] 2019-12-19 16:20:41,731 - INFO: 30bd9dce92f245698ae73dfec9fc0197: Sending packet MESSAGE data 2/test,["my_response",{"data":"Connected","count":0}] - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] 2019-12-19 16:20:41,731 - INFO: 30bd9dce92f245698ae73dfec9fc0197: Sending packet MESSAGE data 0/test - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] 2019-12-19 16:20:41,732 - INFO: 30bd9dce92f245698ae73dfec9fc0197: Received request to upgrade to websocket - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:105] 2019-12-19 16:21:12,524 - WARNING: Invalid session 30bd9dce92f245698ae73dfec9fc0197 - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/server.py:370] 2019-12-19 16:21:13,708 - INFO: 64aaa335d03e48adbca4d6db461ba372: Sending packet OPEN data {'sid': '64aaa335d03e48adbca4d6db461ba372', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000} - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] 2019-12-19 16:21:13,709 - INFO: 64aaa335d03e48adbca4d6db461ba372: Sending packet MESSAGE data 0 - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] 2019-12-19 16:21:13,744 - INFO: 64aaa335d03e48adbca4d6db461ba372: Received request to upgrade to websocket - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:105] 2019-12-19 16:21:44,711 - WARNING: Invalid session 64aaa335d03e48adbca4d6db461ba372 - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/server.py:390] 2019-12-19 16:21:44,712 - WARNING: Invalid session 64aaa335d03e48adbca4d6db461ba372 - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/server.py:370] 2019-12-19 16:21:46,801 - INFO: da4cbf9a20ba4bfc9cd731644bd4bf6f: Sending packet OPEN data {'sid': 'da4cbf9a20ba4bfc9cd731644bd4bf6f', 'upgrades': ['websocket'], 'pingTimeout': 60000, 'pingInterval': 25000} - [in /home/venv/py37sio/lib/python3.7/site-packages/engineio/socket.py:95] Then i dont use nginx+gunicorn, run python3 app.py is ok. But just use … -
Django dynamic url resolve in javascript code
I have this code in my javascript. let link = <a class='${!questionnaire.exam ? 'ajax-btn' : ''} card__item ${!questionnaire.active ? 'card__item--inactive' : ''}' href="{% url '${questionnaire.id}' %}"></a> But the url of the <a>tag does not resolve correctly after I insert this code in my html with javascript. -
Making a drag and droppable text box with toolbar when click
I am trying to make a web app with Django and Nodejs. It would have a function that allow user to add text box onto an empty canvas, like the way you would add a textbox in powerpoint, when the user click it, there will be a toolbar show up that allow user to change the font size, text's font, color, inline, bold, italics, etc... Is there any javascript library for this? -
Config ckeditor links in django settings
Default value for links protocol in ckeditor is 'http://'. Here we have also 'https://', 'ftp://' and others. I need to change default value from 'http://' to 'https://'. Tried to use next config CKEDITOR_CONFIGS = { 'default': { ... 'linkDefaultProtocol': 'https://' }, } but it does not works. What I do wrong ? -
What's the most efficient way to increase a PositiveIntegerField in a view in Django?
I have a model with this field in models.py: vote_submissions = models.PositiveIntegerField() In the view, I originally just did a basic object.vote_submissions += 1 object.save() return HttpResponseRedirect(reverse('index')) as I am still learning the in's and out's of Django. From what I understand I should use F() expression? I have this in my views.py and it works (not tested yet). from django.db.models import F Category.objects.filter(id=object.id).update( vote_submissions=F('vote_submissions') + 1) return HttpResponseRedirect(reverse('index')) Is this the most efficient and safest way to do these kind of updates? Thank you. -
How to pass data to a serializer using Requests module in Django?
I want to create a registration form that allows me sign up. Instead of saving the form usually (by using Django forms), I have created an API that obtains all the data from the form and save it to the model. I have tried this method but I am not getting any results: models.py: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True, related_name = 'profile') address = models.TextField() phoneno = models.IntegerField() views.py: def signup(request): if request.method == 'POST': user_form = UserForm(request.POST) register_form = RegisterForm(request.POST) if user_form.is_valid() and register_form.is_valid(): username = request.POST.get("username", ""), first_name = request.POST.get("first_name",""), last_name=request.POST.get("last_name",""), email=request.POST.get("email",""), password=request.POST.get("password2",""), address=request.POST.get("address",""), phoneno=request.POST.get("phoneno","") payload = { 'username': username, 'first_name': first_name, 'last_name': last_name, 'email':email, 'password':password, "profile" : { 'address': address, 'phoneno': phoneno, } } response = requests.post('http://127.0.0.1:8000/sign_api/',data=payload) serializer = UserSerializer(data=payload) if serializer.is_valid(): serializer.save() return redirect("login") else: user_form = UserForm() register_form = RegisterForm() return render(request, 'users/register.html', {'user_form': user_form, 'register_form': register_form}) class RAPI(APIView): permission_classes = [AllowAny] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() content = {'status': 'You are registered'} return Response(content, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('address','phoneno','department', 'salary') class UserSerializer(serializers.ModelSerializer): profile = RegisterSerializer() class Meta: model = User fields … -
bonjour. j'ai un probleme avec l'affichage d'une image dans mon app django [closed]
J'utilise filedfield l'image s'upload corectement mais ne s'affiche pas. rendu html " width="240"> methode utiliser dans les templates -
How does django know which registered model to look through when displaying custom headings using list_display?
Take the following example class Adult (models.Model): age = models.IntegerField() class Minor (models.Model): age = models.IntegerField() Now I register both of them @admin.register(Adult,Minor) class AdultAdmin(admin.AdminModel): list_display = ('age') class MinorAdmin(admin.AdminModel): list_display = ('age') Now when viewing the entries via the admin page, will the distinction be made according to the class names, or will django go through all models in a specific order to see if that model has the mentioned field. If it's the former, then does that mean that the class name has to be in a specific format - the model name followed by the word 'Admin' ? -
Problem when get id from data-url in django 2.2
this is my script: views.py from profil.models import dayah def index(request): dayah = profil_dayah.objects.all return render(request,'index.html', { 'dayah' : dayah }) index.html {% for dayahs in dayah %} <button type="button" class="btn btn-primary see-details" data-toggle="modal" data-target="#exampleModalLong" data-url="{% url 'details' dayahs.id %}">Detail</button> {% endfor %} get_id.js $(".see-details").on('click', function (){ var url = $(this).data('url') console.log(url); }) the result of console.log should be /details/1 int 1 is the id from {{ dayahs.id }} but my real result is : /details/(%3FP4%5Cd/) why the result like that? i want the result is /details/1 in the console.log -
Django Creating constraints on serializers
I'm trying to extend Django's Poll app. Each poll will have 2 choices and either an image for each choice or a color for each choice, but not both. My models look like this: class Question(models.Model): question = models.CharField() created_at = models.DateTimeField(auto_now_add=True) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE) img = models.ImageField() class ChoiceColor(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE) color = models.CharField(max_length=7) I have a View that looks like this: class CreateQuestionView(CreateAPIView): serializer_class = CreateQuestionSerializer With the following serializers: class ChoiceImageSerializer(serializers.ModelSerializer): class Meta: model = ChoiceImage fields = ('image',) class ChoiceColorSerializer(serializers.ModelSerializer): class Meta: model = ChoiceColor fields = ('color',) class ChoiceSerializer(serializers.ModelSerializer): choice_image = ChoiceImageSerializer(many=False) choice_color = ChoiceColorSerializer(many=False) class Meta: model = Choice fields = ('choice', 'choice_image', 'choice_color') class CreateQuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True) class Meta: model = Question fields = ('question', 'choices') How do I create this constraint on my serializers? Also Am I designing this efficiently or is there a better way to do this? -
I would like to merge the duplicates in the excel sheet
I have 4 fields, Primary phone(p1), secondary phone(p2), primary email(e1), secondary email(e2). If p2 field is empty, then the p1 value of new row should go to p2. [][1 I am able to merge P number field, but unable to merge p email and se email Please find the below code: def merge_or_delete_contact(self, contact, contact_list): query_params = self.query_params(contact) if len(query_params): old_contact = contact_list.contacts.filter(query_params).exclude(id=contact.id).first() if old_contact: old_contact.secondary_phone_number = contact.primary_phone_number old_contact.secondary_email = contact.primary_email old_contact.name = contact.name if contact.name else old_contact.name contact.delete() old_contact.save() return old_contact return contact def query_params(self, obj): query = Q(secondary_phone_number=obj.primary_phone_number) if obj.secondary_phone_number: query = query | Q(primary_phone_number=obj.secondary_phone_number) if obj.primary_email: query = query | Q(primary_email=obj.primary_email) if obj.secondary_email: query = query | Q(secondary_email=obj.secondary_email) return query -
Automatically render None as null in template?
I am rendering a template with message bundled in the context. Sometimes the message will be None: def context_test(request): context = { 'message': None, } return render(request, 'testapp/context_test.html', context) I want to alert the message on front-end only if it is not None. So far I am doing it like this: <!DOCTYPE HTML> <html> <head> </head> <body> </body> <script> let message = "{{ message }}" {% if message %} alert(message) {% endif %} </script> </html> However, I would like to replace the Django's if clause with pure Javascript, like so: <!DOCTYPE HTML> <html> <head> <style> </style> </head> <body> </body> <script> let message = "{{ message }}" // or {{ message }} ? if (message) { alert(message) } </script> </html> In order for this to work, I would need message equal to null (or other falsy value) in the script. Can it be done in a clean way, without an additional conversion in the script like if {message === 'None'} message = null? In other words, can I somehow tell Django to automatically render context's None as null in the template? -
why output isn't displaying though server launched successfully? [closed]
I have tried and made some changes also still it's not working. below there link is there in which coding images are there plz help me. https://photos.app.goo.gl/VEAcLyf6a4j1Qvg89 -
What is wrong with my Gulp Watch task with Docker?
I'm trying to run a gulp watch task in my dockerfile and gulp isn't catching when my files are getting changed. Quick Notes: This set up works when I use it for my locally hosted wordpress installs The file changes reflect in my docker container according to pycharm's docker service Running the "styles" gulp task works, it's just the file watching that does not It's clear to me that there's some sort of disconnect between how gulp watches for changes, and how Docker is letting that happen. Github link **Edit: It looks possible to do what I want, here's a link to someone doing it slightly differently. gulpfile excerpt: export const watchForChanges = () => { watch('scss-js/scss/**/*.scss', gulp.series('styles')); watch('scss-js/js/**/*.js', scripts); watch('scss-js/scss/*.scss', gulp.series('styles')); watch('scss-js/js/*.js', scripts); // Try absolute path to see if it works watch('scss-js/scss/bundle.scss', gulp.series('styles')); } ... // Compile SCSS through styles command export const styles = () => { // Want more than one SCSS file? Just turn the below string into an array return src('scss-js/scss/bundle.scss') // If we're in dev, init sourcemaps. Any plugins below need to be compatible with sourcemaps. .pipe(gulpif(!PRODUCTION, sourcemaps.init())) // Throw errors .pipe(sass().on('error', sass.logError)) // In production use auto-prefixer, fix general grid and flex … -
django assets versioning for a global template
while creating a project i am facing cache issue with my js file because it's not loading new changes each time. So i want to load my static file using versioning. for example /assets/js/custom.js?v=12345. I belongs to PHP background so we use just time() function there to create a current timestamp and uses as version. But in Django I have not found any solution. If I try to create timestamp from view and pass it in template by appending in dictionary So i have to do it in each functions/pages which is not a good solution because my header/footer file is same in all pages.. -
How to make variables work from another file [closed]
I am new in Djnago and I have an app that contains students grades. In views.py my app takes students name and gives its grades fo certain years and i put my code inside reqest function. However the data about students grades is quite large and i want to put it in another file and import to views.py . Is that possibe to do it? What I need to do? So far created grades.py file : y18=['anna':[100,78,35], 'bill':[78,91,59] ] view.py from django.shortcuts import render from .forms import ChildForm from grades import y18 def home(request): stock = ChildForm() if request.method == "POST": student = ChildForm(request.POST) if student.is_valid(): data = student.save(commit=True) name = data.name context={ 'name':name, } else: student = ChildForm() return render(request,'equity/kids.html',{'student':student}) return render(request,'equity/garden.html',context) return render(request,'equity/kids.html',{'student':student) How to make it work and diplay a certain student grade. I do not know how to import in home(request)function to make it work. I will appreciate yout help and any tips -
django: Getting error AttributeError: 'NoneType' object has no attribute 'split' even when I am able to access the page
I am getting below error while running command. However, page is opening but on command prompt below error is coming. I referred other stackflow pages where similar error is there but it didnt helped. python manage.py runserver Error: Performing system checks... System check identified no issues (0 silenced). December 19, 2019 - 13:04:14 Django version 2.1.5, using settings 'first_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [19/Dec/2019 13:04:19] "GET / HTTP/1.1" 200 2786 [19/Dec/2019 13:04:19] "GET /static/css/mystyle.css HTTP/1.1" 200 68 Not Found: /favicon.ico [19/Dec/2019 13:04:19] "GET /favicon.ico HTTP/1.1" 404 2211 Traceback (most recent call last): File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\socketserver.py", line 799, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [19/Dec/2019 13:04:19] "GET /favicon.ico HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52848) Traceback (most recent call last): File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\wsgiref\handlers.py", line 180, … -
HttpRequest after form method in django?
I'm new in django, and I can't to figure out how to redirect site to main page after submit. I read here, and in others places that I need to return HttpResponseRedirect in method. But my form looks that: @login_required #@staff_member_required def hero_detail_create_view(request): #creating by form form = HeroCreateModelForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) slugCreate = str.lower(form.cleaned_data.get('name') + "-" + form.cleaned_data.get('nickname')) obj.slug = slugCreate.replace(" ","") obj.user = request.user obj.save() form = HeroCreateModelForm() template_name='form.html' context = {'form':form} return render(request, template_name, context) It's creating a hero. And I need to redirect to main page after submit. How can I do that? I can't just add second return. I tried create new method to redirect, and put in instide this, but of course it didn't wokrs. My form html: {% extends "base.html" %} {% block content %} {% if title %} <h1>{{ title }}</h1> {% endif %} <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> {% endblock %} -
Enumerating django admin items with float numbers
I am going to enumerate Category items in django admin for example I have a Category in django admin like that Category Category --> Parent Category --> Parent --> SubParent but I should enumerate them like this 1.0 Category 1.1 Category --> Parent 1.2 Category --> Parent --> SubParent I was going to do class Category(models.Model) order_number = models.FloatField(primary_key=True) but it did not work because I have many categories in database and I should set default value for this field. If I do this It may effect on other relations. primary_key=True does not take null=True value. That's why How can I solve this? Thank you beforehand! any help would be appreciated! -
how to display details from dropdown selection in django
Here when i select Chief Instructor's name from dropdown , i want to display its email,mobile number & kos_no in the html fields, How to fetch data and display models.py class InstructionCourse(models.Model): title = models.TextField(blank=True, null=True) resume = models.TextField(blank=True, null=True) chief_instructor_name = models.ForeignKey(MemberShip, on_delete=models.SET_NULL, blank=True, null=True,related_name='chief_auther_ofinst') views.py def Add_InstructionCourse(request): if request.method == 'POST': add_inst = InstructionCourse() add_inst.title = request.POST['title'] add_inst.resume = request.POST['resume'] add_inst.chief_instructor_name_id = request.POST['chief_instructor_name'] add_inst.save() messages.success(request,'Instruction course added successfully!') return HttpResponseRedirect(reverse('koscientific:instruction_course')) member_name_list = MemberShip.objects.all() context = { 'member_name_list':member_name_list, } return render(request, 'instructioncourse/add_instruction_course.html', context) add_instruction_course.html <div class="form-group row"> <label class="col-sm-2 col-form-label control-label">Chief Instructor's name:</label> <div class="col-sm-10"> <select required id="send_1" style="width:auto" name="chief_instructor_name" class="form-control select2_demo_1"> <option value="" selected="" disabled=""></option> {% for each in member_name_list %} <option value="{{ each.id }}">{{ each.name }} | {{each.kos_no}}</option> {% endfor %} </select> </div> </div> </div> <div class="row" id="send_1_2"> <label class="col-sm-3 col-form-label"> Chief Instructor's E-mail</label> <div class="col-sm-9"><input type="text" class="form-control"></div> </div> <div class="hr-line-dashed"></div> <div class="row"><label class="col-sm-3 col-form-label">Kos Number</label> <div class="col-sm-9"><input type="text" class="form-control"></div> </div> <div class="hr-line-dashed"></div> <div class="row"><label class="col-sm-3 col-form-label">Chief Instructor's mobile No</label> <div class="col-sm-9"><input type="text" class="form-control"></div> </div> <div class="hr-line-dashed"></div> -
ModuleNotFoundError: No module named 'onbytes'
I have a Django app that I created and am trying to deploy onto Google Cloud Platform. When I try to go to the given link after running gcloud app deploy, I get a 502 Bad Gateway error. Looking at the logs, I see this error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> I looked this up and from this stackoverflow post, I tried running the command locally: gunicorn --log-file=- onbytes.wsgi:application However, I get the error: ModuleNotFoundError: No module named 'onbytes' Nothing comes up when I look this up on google. I tried running pip3 install onbytes but that failed to yield anything. Anyone know what's going on? -
django use forms to update admin user
i have a form used to sign up and i would like to use that for to fill out the user information in the admin page forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') position = forms.CharField(max_length=30, required=False, help_text='Optional.') store = forms.CharField(max_length=30, required=False, help_text='Optional.') #making it only allow @gmail.org emails def clean_email(self): data = self.cleaned_data['email'] if "@gmail.com" not in data: # any check you need raise forms.ValidationError("Must be a valid email.") return data class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'position', 'store', 'password1', 'password2', ) exclude = ('user',) i have then tired to add it to the admin user with this admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Category, Employee, Manager from .forms import SignUpForm admin.site.site_header = "Employee Management System" class ProfileInline(admin.StackedInline): form = SignUpForm can_delete = False verbose_name_plural = 'SignUpForm' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('username', 'first_name', 'last_name', 'email', 'first_name', 'last_name', 'is_staff', 'position', 'store') list_select_related = ('SignUpForm', ) def get_inline_instances(self, request, obj=None): if not … -
The responseMessages is not displaying in Django-Swagger integration
I am using Django REST Swagger to document my API but don't know how to list all possible response messages errors or otherwise that an API endpoint provides. enter image description here I have included the responseMessages in description of API. The question might be similar but I have a constraint of not making major changes in the previous code-base. Also I'm using the following snippet in urls.py schema_view = get_swagger_view(title="Swagger Docs") -
How to add other pages from Bootrsrap to Django CMS project?
I try follow this tutorial https://www.youtube.com/watch?v=Pkrm2nucaKA it only works for 1 page themes from bootstrap But other pages like about.html store.html and so on doesn't work when i try to put them in same folder as base.html to templates folder so what is way to connect the pages to the django project? if i press the menu button and pages are not attached i get error saying page is not found and i working with divio app for this I also could not get the page numbers thing working and also i get this ugly looking buttons and i need help to change them if someone knows https://imgur.com/0Pr4btW -
Show a drop down in django form
I am creating a django form which consists of a field that is related with another model via Foreign Key. Originally it is showing a dropdown of all the instances from the related model but I want to show only those fields which are connected with the user for that I am using this code. Forms.py class OutwardDocketForm(forms.ModelForm): class Meta: model = OutwardDocket fields = "__all__" exclude = ["created_by"] def __init__(self, *args, **kwargs): super(OutwardDocketForm).__init__(*args, **kwargs) print("self") self.fields['sending_location'].queryset = Receiver_client.objects.filter(emitter=self.request.user.id) But It doesn't seem to be working as it still shows the complete dropdown as opposed to what is required Models.py class OutwardDocket(models.Model): transaction_date = models.DateField(default=datetime.now) dispatch_date = models.DateField(default=datetime.now) sending_location = models.ForeignKey(Receiver_client, on_delete=models.CASCADE, related_name='receiver_location') class Receiver_client(models.Model): name = models.CharField(max_length=500, default=0) city = models.CharField(max_length=500, default=0) address = models.CharField(max_length=500, default=0) emitter = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client') How can I show the dropdown which is related to the particular user?