Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF and generic relations: how to obtain content_object field from API response?
I have implemented Generic Relations in Django DRF following the official guide and it works well, apart from the fact that I cannot seem to obtain the field content_object from my API response. Basically, I have a model called Document that can either be related to a model called Folder or a model called Collection. class Document(models.Model): limit = models.Q(app_label='folders', model='folder') | models.Q( app_label='collections', model='collection') title = models.CharField(max_length=500) # Field necessari per la Generic Relation content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True, blank=True, limit_choices_to=limit) object_id = models.PositiveIntegerField(null=True, blank=True) content_object = GenericForeignKey( 'content_type', 'object_id') category = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.title class Folder(models.Model): ... documents = GenericRelation(Document) def __str__(self): return self.title class Collection(models.Model): ... documents = GenericRelation(Document) def __str__(self): return self.title Here are my serializers: class ContentObjectRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, Folder): serializer = FolderSerializer(value) elif isinstance(value, Collection): serializer = CollectionSerializer(value) else: raise Exception('Unexpected type of object') return serializer.data class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Document fields = ('id', 'title', 'content_type', 'object_id', 'category') class FolderSerializer(serializers.ModelSerializer): documents = DocumentSerializer(many=True, read_only=True) class Meta: model = Folder fields = ("id", "title", "description", "documents") depth = 1 (Collection serializer is essentially the same ad the Folder serializer, with its own fields). I was … -
How i can integrate BigBlueButton into my Django website
I'm trying to use an API called BigBLueButton in my website, and after a little researches, i figured how to install it in my project using the command pip install django-bigbluebutton. I add it to my INSTALLED-APP in setting.py. Until this step, everything is OK and i have no errors. But i don't know how use its models and its views and how to show it in my website. Does anyone have an idea of the next steps? Thank you everyone. -
"BulkIndexError at /admin/books/address/add/" Django_rest_framework + ElasticSearch
I am trying to implement Elastic Search with django rest framework. I have implemented it without nested fields(Foreign Keys). But now stuck while trying to work with nested fields. I am following this documentation django-elasticsearch-dsl-drf. From django admin panel I am able to create City and Country model but when I create Address model I get this error: ('1 document(s) failed to index.', [{'index': {'_index': 'address', '_type': '_doc', '_id': '7', 'status': 400, 'error': {'type': 'illegal_argument_exception', 'reason': 'The [standard] token filter has been removed.'}, 'data': {'id': 7, 'street': '20', 'house_number': '155', 'appendix': 'sonething', 'zip_code': '123', 'city': {'name': 'Lahore', 'info': 'this is my city', 'location': {'lat': Decimal('31.504828100000000'), 'lon': Decimal('74.323542500000000')}, 'country': {'name': 'Pakistan', 'info': 'this is my country', 'location': {'lat': Decimal('31.504828100000000'), 'lon': Decimal('74.323542500000000')}}}, 'location': {'lat': Decimal('31.5048281'), 'lon': Decimal('74.3235425')}}}}]). Thanks in advance for helping and your addition to my knowledge. I am sharing my files with you for better understanding. Models.py from django.db import models from six import python_2_unicode_compatible @python_2_unicode_compatible class Country(models.Model): """Country.""" name = models.CharField(max_length=255) info = models.TextField(null=True, blank=True) latitude = models.DecimalField(null=True, blank=True, decimal_places=15, max_digits=19, default=0) longitude = models.DecimalField(null=True, blank=True, decimal_places=15, max_digits=19, default=0) class Meta(object): """Meta options.""" ordering = ["id"] def __str__(self): return self.name @property def location_field_indexing(self): """Location for indexing. Used in Elasticsearch … -
Django / DRF - Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`
everyone. Working with DRF gave me this error: models.py: class TestTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) class UsersAnswers(models.Model): test_taker = models.ForeignKey(TestTaker, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) serializers.py class UsersAnswersSerializer(serializers.ModelSerializer): class Meta: model = UsersAnswers fields = "__all__" class TestTakerSerializer(serializers.ModelSerializer): users_answers_set = UsersAnswersSerializer(many=True) class Meta: model = TestTaker fields = "__all__" And I get: Got AttributeError when attempting to get a value for field `users_answers_set` on serializer `TestTakerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `TestTaker` instance. Original exception text was: 'TestTaker' object has no attribute 'users_answers_set'. I tried to add "source" parameter to users_answers_set, but nothing changed. Thank you. -
pysolr is taking time first time after the solr restart
pysolr is taking time first time after the solr restart. Scenario is like this. 1)Restart Solr server 2)Execute the query directly in solr is taking 4 sec 3)when we are trying to execute the same query using pysolr, it is taking 300 seconds or more for the first time. After refreshing it is taking only less than 2 sec. When I check the pysolr code the time is taking in the below code. resp = requests_method(url, data=bytes_body, headers=headers, files=files, timeout=self.timeout, auth=self.auth) 4)Can anybody help me in getting the out faster first time also. I think this abnormal because executing the query directly in Solr is taking very few seconds. -
How to calculate average of some field in Dango models and send it to rest API?
I want to count the average of ratings ( in Reviews model ) and send it to my API. Models.py from django.db import models from adminuser.models import Categories from accounts.models import UserAccount as User from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) class Reviews(models.Model): rating = models.SmallIntegerField( default=0,validators=[MaxValueValidator(5),MinValueValidator(1)]) comment = models.CharField(max_length=500) item = models.ForeignKey(Gigs , on_delete=models.CASCADE) buyer = models.ForeignKey(User ,default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render from .models import Gigs,Reviews from .serializers import GigsSerializer,ReviewsSerializer from rest_framework.generics import GenericAPIView from rest_framework.mixins import ListModelMixin, CreateModelMixin , RetrieveModelMixin , DestroyModelMixin, UpdateModelMixin from rest_framework.permissions import AllowAny # Create your views here. #List and create (pk not required) class GigsListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): username = self.kwargs['user'] return Gigs.objects.filter(seller=username) serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) class GigsListCategorywise(GenericAPIView, ListModelMixin ): def get_queryset(self): SearchedCategory = self.kwargs['category'] return Gigs.objects.filter(category=SearchedCategory) serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) class GigsListAll(GenericAPIView, ListModelMixin ): queryset = Gigs.objects.all() serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , … -
how can i access a static django image in javascript
i want to access the django static folder via javascript. I have stored a folder structure and pictures in the static folder. I get the folder and the picture name via an Ajax and now I want to display the picture using javascript. I used django tag to write all picture urls into an array and then read them out. <script> var ImagesURL = [ "{% static "/A/A_ol1.png" %}", "{% static "/A/A_ol2.png" %}", "{% static "/A/A_ol3.png" %}", "{% static "/A/A_ol4.png" %}", "{% static "/A/A_ol5.png" %}", "{% static "/A/A_ol6.png" %}", ... ]; </script> that works pretty well too. it's just too static for me. Now that I have more and more pictures and a more complex structure of the folders I would prefer to use the ajax, so that I can put together the url from the names and folders passed ... is there a trick? -
Cannot set a very simple object attribute to an object with a many:many relationship
I'm learning django and cannot seem to just literally add a message to an automation. I have a POST method and I should be able to add a message to an automation (both Message and Automation classes have a many to many relationship). This is how the automation is logged just before trying to add the message: before {'_state': <django.db.models.base.ModelState object at 0x7fbd47a27370>, 'id': 9, 'name': 'test bobbie automation', 'description': 'a test bobbie automation', 'account_id': 34, 'date_created': datetime.datetime(2021, 8, 27, 8, 55, 52, 723100, tzinfo=<UTC>)} It has no messages, but the class denotes a many:many relationship between messages and automations, so I see no reason why it cannot be added. What am I doing wrong here? I’ve tried all of these but to no avail: # automation.messages.set(msg) # automation.messages.append(msg) # automation.messages.add(msg) # does not work # automation['messages'] = msg automation.messages.set(msg) Where the latest attempt fails with TypeError: 'Message' object is not iterable. View: @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'customer'], own_account_only=True) def automation_add_message(request, pk, automation_id): account = Account.objects.get(id=pk) automation = Automation.objects.get(id=automation_id) if request.method == 'POST': msgId = request.POST.get('message_id') msg = Message.objects.get(id=msgId) print('before', automation.__dict__) # automation.messages.set(msg) # error here @todo # automation.messages.append(msg) # automation.messages.add(msg) # does not work # automation['messages'] = msg # also fails … -
JQuerie user variable between {} [duplicate]
The value : termid is a value received from a form but I can figure out the use him between. {% url 'terminals_update_view' site.id termid %} the site.id is from the django form and works well <script type="text/javascript"> $(document).ready(function () { $("button.add-comment-button3").click(function (e) { termid = $(this).val(); console.log(my_button); $.ajax({ success: function (data) { $('#table_body').html('').load("{% url 'terminals_update_view' site.id termid %}"); } }); }); }); </script> -
Having a problem while trying to code through the book: "Django for Beginners" by William S. Vincent
The error message I am getting is: AttributeError: module 'django.contrib' has no attribute 'staticfilespages' whenever I run the command python manage.py runserver in Windows PowerShell I'm assuming the problem is in this code because it's the only place I can find django.contrib, but Visual Studio Code isn't pointing out any problems. from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')) ] -
Django auto increment in form
Lets say I have this model.py: class Order(models.Model): delivery = models.BooleanField() I have this form.py: class OrderForm(ModelForm): class Meta: model = Order fields = ["delivery"] And I have this views.py: def get_order(request): if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): order_instance = form.cleaned_data["delivery"] return HttpResponseRedirect("/end") else: form = OrderForm() return render(request, "order.html", {"form": form}) And the HTML page show form page. With this code my program will tell me that he is not happy because I am trying to use delivery (a boolean) for a id field because Django automatically create a id field for each model. This field is supposed to auto increment but with form it doesnt seem to work. So how can I force him to auto increment ? -
Why my django form create a new object for the wrong model
I'm creating a list with hierarchical data base Title -> Category -> Subcategory by using proxy (according to this video). User first see a table with titles name and status, then he can click on one of titles to go to the next page that has a table of categories name and status and then he can click on one of these categories to go to the next page with table of subcategories name and status. I want to create a form that will add a new name and a new status for my category or subcategory. But whenever I submit the form, it doesn't matter if it's TitleForm or CategoryForm or SubcategoryForm, I always get a new Title object but never Category or Subcategory object. I've checked my code several times but I couldn't find any issue, everything seems correct. Could someone explain me what the problem is and how can I fix it? models.py from django.db import models from .managers import TitleManager, CategoryManager from model_utils.fields import StatusField from model_utils import Choices class Node(models.Model): name = models.CharField(max_length=70) STATUS = Choices("Na bieżąco", "Porzucone", "Wymaksowane", "Planowane", "W trakcie", "Obejrzane") status = StatusField(choices_name='STATUS') parent = models.ForeignKey( 'self', on_delete=models.CASCADE, related_name='children', null=True, blank=True, ) … -
Django Rest Framework : How to define a ModelSerializer representing a Model A, when A depends itself of other models B and C?
Let's say we have three Models : ModelA, related to ModelB and ModelC. ModelA is defined as : class ModelA(models.Model): field_b = models.ForeignKey(ModelB, on_delete=models.CASCADE) field_c = models.ForeignKey(ModelC, on_delete=models.CASCADE) other_field = models.CharField(max_length=30) class Meta: constraints = [ models.UniqueConstraint(fields=['field_b', 'field_c'], name='unique_modelA') ] How to generate a ModelASerializer instance from instances of ModelB and ModelC ? Then, will there be a serialized representation of field_b and field_c into ModelASerializer ? The UniqueConstraint will it be checked when calling .is_valid() onto ModelASerializer instance ? I tried the following : class ModelASerializer(serializers.ModelSerializer): field_b = ModelBSerializer(read_only=True) field_c = ModelCSerializer(read_only=True) other_field = serializers.CharField(required=False) class Meta: model = ModelA fields = ('field_b', 'field_c', 'other_field',) validators = [ UniqueTogetherValidator( queryset=ModelA.objects.all(), fields=['field_b', 'field_c'], message='A Model A instance for this couple of ModelB and ModelC instances already exists.' ) ] def create(self, validated_data): """ Create and return a new `ModelA` instance, given the validated data. """ return ModelA.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `ModelA` instance, given the validated data. """ instance.other_field= validated_data.get('other_field', instance.other_field) instance.save() return instance But I cannot find any way to create the serializer : model_b = ModelB() model_c = ModelC() model_b.save() model_c.save() other_field = "Dummy content" First try model_a_serializer = ModelASerializer(model_b, model_c, other_field) … -
Getting "Error processing tar file(exit status 1): open /myenv/include/python3.6m/Python-ast.h: no such file or directory" while docker-compose build
So I am pretty new to docker and django. Unfortunately while running the below command on my linux machine which i am connected using my physical windows machine using putty: docker-compose build I am getting an error: Error processing tar file(exit status 1): open /myenv/include/python3.6m/Python-ast.h: no such file or directory 'myenv' is the environment I have created inside my folder. I am getting a container started on port 9000. The app doesn't have anything yet just a simple project so i just expect to see the 'congratulations' screen. I don't know where I am going wrong. My final goal would be to run the docker url in my windows browser and see the screen of docker container. This is my docker-compose.yml file: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:9000 ports: - 202.179.92.106:8000:9000 the IP: 202.179.92.106 is my public IP. I did the above binding so as to access the docker container from my windows machine. Would request additional inputs for the port binding as well if correct/incorrect. Below is my Dockerfile: FROM python:3.6.9 RUN mkdir djangotest WORKDIR djangotest ADD . /djangotest RUN pip install -r requirements.txt Please help me out peeps! -
How to pass a JSON data from a form in ReactJS to Django View inside of a variable?
I want to receive data from a Reactjs frontend form (JSON format) into my django view, where the json data would be stored inside of a variable, which then later i could insert into bigquery using the insert_rows_json method. Is it possible? Thanks in advance cheers! -
field_name = ordering[0].lstrip('-') throws IndexError: tuple index out of range in DRF rest_framework\pagination.py
I am getting error IndexError: tuple index out of range while using CursorPagination of DRF. my code- class CursorSetPagination(CursorPagination): page_size = 10 page_size_query_param = 'page_size' ordering = '-created_at' class WalletCreditViewset(viewsets.ReadOnlyModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] pagination_class = CursorSetPagination serializer_class = WalletCreditSerializer def get_queryset(self): queryset = PaymentOrder.objects.filter(user=self.request.user) return queryset The errors comes when the entry in the database table for a particular user cross the value of page_size. Ex- if some user have 5 payment order then there will be no error but when the same user cross 10 payment order then this error occurs. -
How can I upload new webpages to a django app?
I am quite new to django so I am sorry if I have overlooked something simple. This is my current website: https://www.michealnestor.com I am trying to remake it using react and django, and a lot of it is different, however I want to keep the functionality of being able to run my js apps from the website: https://www.michealnestor.com/projects EXAMPLE: https://www.michealnestor.com/projects/sortingalgorithms/ . I want to be able to upload project folders, with html, css and js in them from the admin page, and then be able to open these projects from my website. I am not sure how to do this though. I have tried manually placing such a folder in a templates folder in my app, and I have managed to use a view to load the html file, but this file can't seem to find the css and js. Maybe I am going about this the wrong way, in any case I would appreciate some guidance! -
I want to make social registration without token validation
When registering via google or facebook, this code checks it with the user token, I want to make sure that the code does not check it and can register and save any user even if its token is not correct GOOGLE_CLIENT_ID is google accounts secret code SOCIAL_SECRET is facebook accounts secret code a long id token comes to auut_token which I take from https://www.googleapis.com/auth/userinfo.email, but I need to be able to enter any token in the field and it will register it anyway. I would really appreciate your help My serializers.py from rest_framework import serializers from . import google, facebook from .register import register_social_user import os from rest_framework.exceptions import AuthenticationFailed class FacebookSocialAuthSerializer(serializers.Serializer): """Handles serialization of facebook related data""" auth_token = serializers.CharField() login = serializers.CharField() def validate_auth_token(self, auth_token): user_data = facebook.Facebook.validate(auth_token) try: user_id = user_data['id'] email = user_data['email'] first_name = user_data['first_name'] provider = 'facebook' return register_social_user( provider=provider, user_id=user_id, email=email, first_name=first_name ) except Exception as identifier: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) class GoogleSocialAuthSerializer(serializers.Serializer, ): auth_token = serializers.CharField() email = serializers.EmailField def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) try: user_data['sub'] print(user_data['sub']) except: raise serializers.ValidationError( 'The token is invalid or expired. Please login again.' ) from phrasebook.settings import … -
About innerHTML can't display pictures
The text can be displayed normally. Here is my code: <div id='container'> </div> <script> document.getElementById("container").innerHTML = "{{ article.content }}"; </script> The result appears like this on the web page: <p>&nbsp; &nbsp; detail: x_1 1</p><p style="text-align: center;"><img src="/media/uploads/images/xx_20210827151909_960.jpg" alt="xx.jpg" width="1137" height="710" style="width: 1137px; height: 710px;"/></p> They are not displayed as web page elements. (The path of the img src is right. I use: return render(request, 'news/article.html',{'article': article,'username':username}) to return article, article is the object returned by article.objects.get (PK = PK). content is an attribute of article.) -
Django Download zip file containing multiple url content with images
i have following code class getData(APIView): permission_classes = [AllowAny] file_loc = "csv/1 პრიორიტეტი - 1 პრიორიტეტი.csv" def get(self, request, *args, **kwargs): data = {} with open(self.file_loc, 'r', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: code = row['ISBN'] url = row['ყდის ფაილი'] data[code] = url file2 = open(self.file_loc) reader = csv.reader(file2) lines = len(list(reader)) some = 0 while some != lines: for k,v in data.items(): print(k, 'Da', v) response = HttpResponse( content=requests.get(v).content, content_type='image/jpeg', headers={"Content-Disposition": "attachment; filename={}".format(k+'.jpg')}, ) some+=1 return response with the following code i have keys and values for dictionary data, keys are image names and values are url of image. all im trying to do is when someone sends get request to that value(url), download all images with keys(imageNames). the problem i have is it send only one response and dont go through data items the best solution would be save those images with its names to hard drive and on GET request download zip file containing all the data. any ideas? -
Django smtp connection with office 365 Outlook
We are receiving the following error using the Office 365 SMTP server to send mails from the Django application. smtplib.SMTPAuthenticationError: 535, b'5.7.139 Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your administrator. [PN2PR01CA0065.INDPRD01.PROD.OUTLOOK.COM]' following setup did in the Django setting.py EMAIL_HOST=smtp.office365.com EMAIL_USE_TLS=True EMAIL_PORT=587 # also tried port 25 EMAIL_USER=test@example.com EMAIL_PASSWORD=test And following the steps for setting up the Outlook 365 SMTP relay account (Steps) and also checked the Authenticated SMTP for the admin account. -
nslookup from csv in django and display ip address on webapp
web app to nslookup from 1 csv and display their ip address on the page the table should contain id location website ip address other ip address port 1 page should also nslookup individual ip address of hostname entered by user -
how can I install django website on localhost with bash export
I'm new to django programming, I have downloaded the discord website from git hub https://github.com/python-discord/site. I am trying to install this website for the last 5-6 hours. I searched for an answer everywhere, unfortunately I can't find a clear answer. I will write my steps so far: Downloaded the source code Started venv, started new project and then copied all files to the folder. Added conf folder and inside secret.json now i am stuck at 4: Add export DJANGOPROJECT_DATA_DIR=~/.djangoproject (without the backticks) to your ~/.bashrc (or ~/.zshrc if you're using zsh, ~/.bash_profile if you're on macOS and using bash) file and then run source ~/.bashrc (or source ~/.zshrc, or source ~/.bash_profile) to load the changes. I added the line: export DJANGOPROJECT_DATA_DIR=~/Desktop/website/site-main (this is my website folder path) at the end of the .bashrc file. But I get nothing beside: 'source' is not recognized as an internal or external command, operable program or batch file. I changed the command to set for windows but nothing happen. enter image description here raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable -
Migration not being created in database
I connected my app to my database in my settings.py and then ran migrations and my model 0001_initial.py file was created but when i try to apply those migrations to the database and create a table it says no migrations to apply and it doesn't create the table. I dont know why Machine 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Appear', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Show', models.CharField(max_length=100)), ('Media', models.CharField(blank=True, choices=[('TV', 'TV'), ('Radio', 'Radio'), ('Youtube', 'Youtube'), ('Podcast', 'Podcast')], max_length=30, null=True)), ('Episode', models.IntegerField()), ('Date', models.DateField(max_length=100)), ('Time', models.TimeField()), ('Producer', models.CharField(max_length=100)), ('Producer_Email', models.EmailField(max_length=254)), ], ), ] why is the table not being created. -
Django ModelForm not getting instance data
I have a model form that have multiple choice fields. using AJAX to update form choic fields upon changed field. Model: class Student(models.Model): CLASSROOM = 0 GROUPROOM = 1 HOMEROOM = 3 STUDENT_RECORD_TYPES = [ (CLASSROOM,_("Classroom")), (GROUPROOM,_("Group")), (HOMEROOM,_("Home Edu")), ] school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='student_records') grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="student_records") record_type = models.PositiveSmallIntegerField(_("Record Type"),choices=STUDENT_RECORD_TYPES,default=0) class Meta: constraints = [ models.UniqueConstraint( fields=['school','grade', 'record_type'], name='unique_school_grade_record' ), ] def __str__(self): return "Record ID: {}".format(self.pk) Views.py: def update_students(request,pk): updated_table=None student_record = get_object_or_404(Student,pk=pk) if request.POST: form = StudentForm(request.POST or None,instance=student_record) if form.is_valid(): form.save() messages.success(request,_("Student record Updated Successfully!")) #Getting data for view updated_table = update_students_table(request) else: messages.error(request,_("Invalid Input, Please check!")) else: form = StudentForm(request.GET or None,instance=student_record) context = {} # load form template context['form'] = form form_template_path = "components/forms/student_update.html" html_form = loader.render_to_string(form_template_path, context, request) context['form'] = html_form return JsonResponse(context) Forms.py: class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' self.fields['school'].widget.attrs['class'] += ' select2' #the issue stands here #self.data.get('school') returns none even if its exist in form data if self.data.get('school'): self.fields['grade'].queryset = Grade.objects.filter(school=self.data.get('school')) else: self.fields['grade'].queryset = Grade.objects.none() class Meta: model = Student fields = '__all__' the strange behavior drives me crazy because when I reselect the school it updates the grade choices normally (with …