Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a special function when a model instance is created?
I'm making a system wherein when the user creates a log he gains points from how it. How do I go about in trying to make this? I tried making a signal.py function but it's giving me an error of 'DPRLog' object has no attribute 'Points'. Am I doing it right? I just want to add points whenever I create a log so I placed it as signal.py class. Can anyone help me out? Thanks Heres my models.py: from django.db import models from profiles.models import User from django.urls import reverse # Create your models here. class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' class Manager(models.Model): manager = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.manager.full_name class Member(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=True) def __str__(self): return self.member.full_name class Job(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(Member, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False, null=False) description = models.TextField() datePosted = models.DateTimeField(auto_now=True) file = models.FileField(null=True, blank=True, upload_to='job_files') def __str__(self): return self.title def get_absolute_url(self): return reverse('job-detail', kwargs={'pk': self.pk}) class DPRLog(models.Model): STATUS_CHOICES = ( ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED'), ('COMPLETED', 'COMPLETED'), ) … -
How to give suggestions in the field entry form value from DB
I am doing basic project for small school in small town as charity non-profit (i am not professional devoloper). It is quite basic web for teacher to find student info ( grades and background). I choiced student code as there are students with exactly the same name and surnames so I thought code would be easier to distinct. This everything works good however i want teacher while typing studentcode in the entry field to get studentfullname as suggestion right in the field entry so they can choice from suggestions ( and click OK button) and avoide choicing wrong student. What i did so far: In models.py class ABC(models.Model): name = models.CharField(max_length=150) class Student(models.Model): studentcode=models.CharField(max_length=200) studentfullname=models.CharField(max_length=500) class Meta: managed=False db_table='class09' in forms.py i have : from django import forms from .models import ABC class ABCForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = ABC fields = ('name',) in views.py : def index(request): if request.method == "POST": form = ABCForm(request.POST) if form.is_valid(): formps = form.save(commit=False) name = formps.name studbackground=Student.objects.get(studentcode=name) context={'background':studbackground ,} return render(request, 'vasagrad/back.html',context) else: form = ABCForm() return render(request, 'vasagrad/index.html', {'form': form}) index.html i have : <form method="POST" class="ticker_area" > {% csrf_token %} {{ form}} <button class = "ticker_button" type="submit">OK</button> </form> I … -
RecursionError in django
I am trying to save M2M field in my choice model. and it giving me this Error(can't even find where the traceback is! File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 846 , in __init__ raise ValueError('"%r" needs to have a value for field "%s" before ' File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\Dell\PycharmProjects\AdmissionSystem\Admission\users\models.py", line 155, in __str__ return self.clg_id File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 535 , in __get__ return self.related_manager_cls(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 846 , in __init__ raise ValueError('"%r" needs to have a value for field "%s" before ' File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\Dell\PycharmProjects\AdmissionSystem\Admission\users\models.py", line 155, in __str__ return self.clg_id File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 535 , in __get__ return self.related_manager_cls(instance) RecursionError: maximum recursion depth exceeded models.py class choice(models.Model): stud_id = models.ForeignKey(student, on_delete=models.CASCADE) clg_id = models.ManyToManyField(college) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() def __str__(self): return self.clg_id class student(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) class college(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) it also gives __str__ return non string type(type student) error when i do return self.stud_id instead of return self.clg_id i just want to have each student get choice of each college only once. how … -
name the dict in a list and send as response
I have a result as this [ { "Total": 54063120.8235, "Percentage": 126.1001 }, { "Total": 1464405, "Percentage": 0 } ] but I want a result in the following way [ Income:{ "Total": 54063120.8235, "Percentage": 126.1001 }, taxes:{ "Total": 1464405, "Percentage": 0 } ] What change shall I do? I am saving my list as result = [Income, taxes] -
How to show one is online when he redirects to an URL in Django python?
am trying to show an user online in my django website platform when he redirects to an URL. Can any online tell me the way to write a code for this . -
Django rest_auth token based social authentication
I'm using Django 2.2 and allauth + rest_auth to enable REST based authentication of the user. Also using Angular 8 in front-end. Also using django-oauth2-provider for token generation. As per the rest_auth documentation, I enabled the Google authentication. urlpatterns = [ path('login/google/', GoogleLoginView.as_view()) ] from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLoginView(SocialLoginView): adapter_class = GoogleOAuth2Adapter The token is generated on frontend using angularx-social-login When I send the token using POST request to the /login/google/ endpoint, it gives error as django.urls.exceptions.NoReverseMatch: Reverse for 'socialaccount_signup' not found. 'socialaccount_signup' is not a valid view function or pattern name. The configuration is like ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_VERIFICATION = ACCOUNT_EMAIL_VERIFICATION -
Importerror from runserver command
(Sorry I'm new at this so I apologize if the question isn't worded well) I tried to run python manage.py runserver after setting up for a project without error, however it wasn't successful and it displayed the following error: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'. In response to the error, I tried to use use a separate command to import: from django.utils.encoding import python_unicode_compatible . However, this gave an error as well: from: can't read /var/mail/django.utils.encoding. Might anyone know what this error means and what I may do to fix it? Thank you so much! -
how to add a simple user fillable form in blog post detail page?
I have built a blog application. it has a page that shows the added posts and if you click on each one it will take you to a post detail page. i want to add a small form to the post detail page that users and none users could fill it.so whenever a post is made in the admin page there would be a new fillable name and email submit form for it inside the detail page. please help me with the code -
TabError: inconsistent use of tabs and spaces in indentation (in python Django shell)
*** from django.db import models class post(models.Model): title = models.CharField(max_length=120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title -
How do I make a webpage be different for a superuser and a normal user on django?
Let me explain a little, I'm trying to make a website just for practicing, in which you have two sides, customer-side, and admin-side, so I want to make certain pages display certain functions when you are logged in as an admin, and to not display said functions to normal users, such as edits and stuff. How do I do that? I hope I explained it properly. Thanks. -
How to send foreground and background push notification to android using django push notification package
Iam using django-push-notification package in django project , In android it the json response should be in the format : { "data": { "title" : "You have a notification", "body" : "The body of the notification", "id" : 1234, "backgroundImage" : "assets/notifications/background.png", }, "notification" : { "alert" : "You have a notification", "title" : "You have a notification", "body" : "The body of the notification", "sound" : "default", "backgroundImage" : "assets/notifications/background.png", "backgroundImageTextColour" : "#FFFFFF" } } So that only android can get the foreground and background notifications. I tried the code : try: fcm_device = GCMDevice.objects.all() fcm_device.send_message("new-notification-out",title="title-out",\ extra={"data": { "title-data" : "title-in", "body" : "new-notification-in" }, \ "notification" : { "alert" : "You have one new notice", "title" : "title-notify",\ "body" : "new-notification" }}) except: pass But not getting the payload "data","notification" in android side, How can I send the payload accurately from backend side ? -
Django rest framework nested serializer create method
I have created a nested serializer, when I try to post data in it it keeps on displaying either the foreign key value cannot be null or dictionary expected. I have gone through various similar questions and tried the responses but it is not working for me. Here are the models ##CLasses class Classes(models.Model): class_name = models.CharField(max_length=255) class_code = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.class_name class Meta: ordering = ['class_code'] ##Streams class Stream(models.Model): stream_name = models.CharField(max_length=255) classes = models.ForeignKey(Classes,related_name="classes",on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.stream_name class Meta: ordering = ['stream_name'] Here is the view class StreamViewset(viewsets.ModelViewSet): queryset = Stream.objects.all() serializer_class = StreamSerializer Here is the serializer class class StreamSerializer(serializers.ModelSerializer): # classesDetails = serializers.SerializerMethodField() classes = ClassSerializer() class Meta: model = Stream fields = '__all__' def create(self,validated_data): classes = Classes.objects.get(id=validated_data["classes"]) return Stream.objects.create(**validated_data, classes=classes) # def perfom_create(self,serializer): # serializer.save(classes=self.request.classes) #depth = 1 # def get_classesDetails(self, obj): # clas = Classes.objects.get(id=obj.classes) # classesDetails = ClassSerializer(clas).data # return classesDetails I have tried several ways of enabling the create method but like this displays an error {"classes":{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}}. Any contribution would be deeply appreciated -
How to manage multiple users at server side of system using Django
I am creating a Vehicle Tracking and Management System in Python Django. In my project, there are 3 different users who have different dashboards. How to create a skeleton of this project -
AdminInline and unknown IntegrityError UNIQUE constraint failed
Django Version: 3.0.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: store_hoursofoperation.day Hello, I'm trying to resolve this error, but I don't know how to proceed. I want the Store model to contain multiple HoursOfOperation. However, this error occurs whenever I add another weekday on any store -- Store A has Monday hours, Store B will error if I add Monday hours. I am using the default admin to include the HoursOfOperation within the Store model. How do I stop the HoursOfOperation.day from being unique? admin.site.register(HoursOfOperation) class HoursOfOperationInline(admin.TabularInline): model = HoursOfOperation extra = 0 @admin.register(Store) class StoreAdmin(admin.ModelAdmin): inlines = [ HoursOfOperationInline ] WEEKDAYS = [ (1, ("Monday")), (2, ("Tuesday")), (3, ("Wednesday")), (4, ("Thursday")), (5, ("Friday")), (6, ("Saturday")), (7, ("Sunday")), ] class Store(models.Model): name = models.CharField(max_length=250) summary = models.CharField(max_length=250) address_line1 = models.CharField(max_length=100) address_line2 = models.CharField(max_length=50) phone = models.CharField(max_length=12) website = models.CharField(max_length=50) status_storefront = models.BooleanField( help_text="Is the storefront open to customers?" ) status_takeout = models.BooleanField( help_text="Is takeout available for customers?" ) status_delivery = models.BooleanField( help_text="What is the delivery service? [No, Yes, Custom]" ) status_delivery_service = models.CharField( max_length=20, blank=True, null=True ) anchor_id = models.CharField(max_length=30) hours = models.Many @property def storefront(self): return "Yes" if self.status_storefront else "No" @property def takeout(self): return "Yes" if self.status_takeout … -
django cannot access default admin section
I am trying to access the django default admin section and I get a 404 error "not found" I can access the default django splash page that tells me I am in debugging mode If I try to access via nginx, I get a nginx bases 404 error 'not found' in browser but my logs are clean. If I try from command line with links http://127.0.0.1/admin I get 'connection refused' (secret) kermit@tuna:~/www/src/exchange $ cat /etc/nginx/sites-available/default upstream django { server unix:///var/run/uwsgi/exchange.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # Default server configuration # server { access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; listen 80 default_server; listen [::]:80 default_server; # SSL configuration # listen 443 ssl default_server; listen [::]:443 ssl default_server; root /home/kermit/www/src/exchange; index index.html index.htm index.php index.nginx-debian.html; server_name tuna.tra.com; location / { try_files $uri $uri/ =404; include /etc/nginx/uwsgi_params; } # pass PHP scripts to FastCGI server # location ~ \.php$ { include snippets/fastcgi-php.conf; } # Django media location /media { alias /home/kermit/www/src/exchange/media; # your Django project's media files - amend as required } location /static { alias /home/kermit/www/src/exchange/static; # your Django project's static files - amend as required } # Finally, send all … -
Trying to make a web app that uses a map matching algorithm with arcpy. Can I use ArcMap or do I need ArcGiS Server?
My client used ArcMap 10.5 to make a map matching algorithm and requested of me to make a web application where users could upload the information necessary to make it work; which in this case is a series of GPS markings, the road network data for the area where the GPS markings come from and a few other user-chosen parameters. I am currently designing the app with Django since I can just take the algorithm as a function and import it to the app. The algorithm itself uses arcpy to locate the GPS points and correlate them to a point on a street by taking previous points and comparing the speed of travel at the instant of measurement with the calculated speed to arrive from said previous point to the correlated point in the selected street. However, a big problem in the design has been the fact that ArcMap 10.5 uses Python 2 for its Arcpy library. On top of that, in the virtual environment I use for coding, I can't import Arcpy successfully; I'm currently using Powershell and pipenv. Investigating I found that there is a way to import arcpy using pipenv... while using ArcGiS Pro. Which uses Python … -
get what was type in a type="text" after submit, to output what was typed in
index.html get the "text" after "submit" do sth...which is to display an output = what was typed in index.html <form action="" method="GET"> Question: <input type="text" name="search"><br/> <input type="submit" value="Submit" /> </form><br/><br/> Output: {{ questions }} this code get the "search" then render it out as output views.py from django.shortcuts import render from django .http import HttpResponse def home(request): return render(request, 'index.html') def index(request): if request.GET.get('search'): search = request.GET.get('search') questions = search return render(request, 'index.html', {'questions': questions}) urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('', views.home ), url(r'^$', views.index, name='index') ] -
Django rest framework, update object after creation
I have a DRF API that takes in the following model: class Points(models.Model): mission_name = models.CharField(name='MissionName', unique=True, max_length=255, blank=False, help_text="Enter the mission's name" ) # Some irrlevant feid url = models.URLField(help_text='Leave Empty!', default=" ") date_added = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'date_added' And it's serializer: from rest_framework.serializers import HyperlinkedModelSerializer from .models import Points class PointsSerializer(HyperlinkedModelSerializer): class Meta: model = Points fields = ( 'id', 'MissionName', 'GDT1Latitude', 'GDT1Longitude', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'url', 'date_added' ) And the view: class PointsViewSet(ModelViewSet): # Return all order by id, reversed. queryset = Points.objects.all().order_by('-id') serializer_class = PointsSerializer data = queryset[0] serialized_data = PointsSerializer(data, many=False) points = list(serialized_data.data.values()) def retrieve(self, request, *args, **kwargs): print(self.data) mission_name = self.points[1] assign_gdt = GeoPoint(lat=self.points[2], long=self.points[3]) gdt1 = [assign_gdt.get_lat(), assign_gdt.get_long()] assign_uav = GeoPoint(lat=self.points[4], long=self.points[5], elevation=self.points[6]) uav = [assign_uav.get_lat(), assign_uav.get_long(), assign_uav.get_elevation()] area_name = f"'{self.points[-2]}'" main = MainApp.run(gdt1=gdt1, uav=uav, mission_name=mission_name, area=area_name) print('file created') return render(request, main) I want to update the URL field of the file to contain a constant pattern and format in the end the mission_name field. object.url = f'127.0.0.1/twosecondgdt/{mission_name}' How can that be achieved and where should I store such code, the views.py or serializers.py? -
how to reverse url in django template syntax
for example, I can reverse a url in this way: {% url 'home:index' %} but if I need to compare a url in a if sentence, like this: {% if request.path == url %} and I want to replace the url with a reverse one but I can't do this: {% if request.path == {% url 'home:index' %} %} So is there another way can solve this? Thanks a lot ! -
Django + AWS Secret Manager Password Rotation
I have a Django app that fetches DB secret from AWS Secret Manager. It contains all the DB parameters like username, password, host, port, etc. When I start the Django application on EC2, it successfully retrieves the secret from the Secret Manager and establishes a DB connection. Now the problem is that I have a password rotation policy set for 30 days. To test the flow, at present, I have set it to 1 day. Every time the password rotates, my Django app loses DB connectivity. So, I have to manually restart the application to allow the app to fetch the new DB credentials from the Secret Manager. Is there a way that secret fetching can happen automatically and without a manual restart of the server.? Once way possibly is to trigger an AWS CodeDeploy or similar service that will restart the server automatically. However, there will be some downtime if I take this approach. Any other approach that can seamlessly work without any downtime. -
Include Object and Object's Foreign Keys in One Query Django
I have the following models: class Document(models.Model): name = models.CharField(max_length=30, null=True, blank=True) reference = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.Name class Subdocument(models.Model) document = models.ForeignKey(Document, null=True, default=None) pdf = models.FileField(upload_to='media') Ultimately I want to show both the name from Document and the pdf from Subdocument in the same <li> in my template within a for loop. So it could be something like: {% for item in something %} <li class="list-group-item"> {{ item.Name }} {{ item.pdf }} </li> {% endfor %} My issue is because they are in separate models, I'm not sure how to get fields from both. So what query, or queries could I run in my view in order to make this possible? Any other approach is welcome, this is just to illustrate my end goal. Thank you! -
Model as a field of another model Django
I'm designing a payment system for a website, but I have trouble. A person can do a Payment and that Payment has a payment type, for example, debit card, credit card or PayPal. So, I need the possibility to add new payment options. The problem is I don't know how to link these two tables, I know that I need a third table with only the payment_id and the payment_type_id assigned. Is there a way to generate this with Django? class PaymentType(models.Model): """Payment option available""" name = models.CharField(unique=True, max_length=255) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return self.name class Payment(models.Model): class PaymentStatus(models.TextChoices): DONE = '1', "DONE" PENDENT = '2', "PENDENT" CANCELED = '3', "CANCELED" status = models.CharField(max_length=10, choices=PaymentStatus.choices, default=PaymentStatus.PENDENT) # payment type created_on = models.DateTimeField(auto_now_add=True) -
Hide a django model field and generate it myself on form submit
I have a model with the following Fields: alert_text, next_run (next time alert will pop out) the next_run is auto filled by me (I dont want to user to fill it) so I hide it like so: #admin.py class AlertForm(forms.ModelForm): class Meta: model = Alert fields = '__all__' class AlertAdmin(admin.ModelAdmin): form = AlertForm fields = ['alert_text'] admin.site.register(Alert,AlertAdmin) The problem is that now I can't find a way to add it to the model when created. and I get an Error: 'AlertForm' has no field named 'next_run'. this is the model.py: class Alert(models.Model): alert_text= models.CharField(max_length=200) next_run = models.DateTimeField() Will appreciate any help here couldn't find a solution anywhere :( -
Django: ImportError: cannot import name 'get_user_model' from 'django.contrib.auth.models'
I have a problem using Djangos Default user from django.contrib.auth.models but trying to use it with my custom User model, using from django.contrib.auth.models import AbstractUser. Following those articles: Django Doc Medium SimpleIsBetter 1 SimpleIsBetter 2 So here is my User model: from django.db import models from django.contrib.auth.models import AbstractUser # from django.conf import settings from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def __str__(self): return "{} {}".format(self.first_name, self.last_name) and here is my Profile model: from django.db import models from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.contrib.auth.models import get_user_model User = get_user_model() # https://medium.com/swlh/best-practices-for-starting-a-django-project-with-the-right-user-model-290a09452b88 from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and in my settings.py I added AUTH_USER_MODEL = 'mysite.User' settings.py: AUTH_USER_MODEL = 'mysite.User' INSTALLED_APPS = [ 'mysite.apps.MysiteConfig', 'django_countries', 'djmoney', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] … -
Django Form - Select foreign key from bootstrap modal pop up
I have created a js/ajax modal pop up in a form to help select an option for a foreign key field in the form. I am lost on how to pass the selected variable back to the form and close the modal. Here is my code : views.py def worker_wizard_popup(request, pk): data = dict() shift = Shift.objects.get(id=pk) skilled = EmployeeSkill.objects.filter(skill_id=shift.skill.id).values_list('employee_id', flat=True) on_other_shifts = ShiftWorker.objects.filter(shift_date=shift.date, employee_id__in=skilled).order_by('employee__first_name') on_other_shifts_ids = on_other_shifts.values_list('employee_id', flat=True) time_off = TimeOff.objects.filter(start_date__lte=shift.date, end_date__gte=shift.date, employee_id__in=skilled).exclude(Q(start_date=shift.date, start_time__gte=shift.shift_start)|Q(end_date=shift.date, end_time__lte=shift.shift_start)).order_by('employee__first_name') time_off_ids = time_off.values_list('employee_id', flat=True) available = User.objects.filter(id__in=skilled, is_active=True).exclude(Q(id__in=on_other_shifts_ids)|Q(id__in=time_off_ids)|Q(admin=True)).order_by('first_name') context = { 'shift': shift, 'on_other_shifts': on_other_shifts, 'time_off': time_off, 'available': available } data['html_form'] = render_to_string('events/includes/partial_availability_wizard.html', context, request=request, ) return JsonResponse(data) Here is the form where I want the chosen FK to pass to the selected option of the Employee field. <div class="col-lg-6 mb-4 bg-default"> <div class="card"> <div class="card-header">Add Worker</div> <div class="card-block"> {% bootstrap_form_errors form %} <form method='POST'> {% csrf_token %} <button type="button" class="btn btn-info btn-md js-worker-wizard mb-2" data-url="{% url 'events:worker_wizard' pk=shift.id %}"><span class="fas fa-hat-wizard fa-lg"></span> Shift Wizard</button> {% bootstrap_field form.employee %} {% bootstrap_field form.shift_date %} {% bootstrap_field form.shift_start %} {% bootstrap_field form.shift_end_date %} {% bootstrap_field form.shift_end_time %} {% bootstrap_field form.call_location %} {% bootstrap_field form.pay_rate %} {% if request.tenant.preferences.request_confirm == True %} {% bootstrap_field form.request_confirm %} {% …