Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display relation data in Django view page?
I have relation between TestForm and Customer and there are ForeignKey of customer in TestForm, but i want to display data from Customer, please let me know how i can display. I want to display name from Customer model... Here is my models.py file... class TestForm(models.Model): name=models.CharField(max_length=225) brand=models.ForeignKey(Customer, related_name='customer_data', on_delete=models.CASCADE, verbose_name='Customer') class Customer(models.Model): name=models.CharField(max_length=225) here is my view.py file... def myview(request, id): datas=TestForm.objects.select_related('customer').get(pk=id) template_name='test.html' context={'datas':datas} return render(request, template_name, context) here is my test.html file.. <p> {% for a in datas.customer_data.all %} {{a.name}} {% endfor %} </p> -
django ordering results are changed when i update one record
I used postgresql and rest_framework.filters.OrderingFilter library in my viewset: ... querset = myModel.objects.all().order_by('-id') filter_backends = (OrderingFilter,) ordering_fields = ('fields1', 'fields2') for example: i have five record ordering by fields2 desc: record3 record2 record1 record4 record5 when I update record2 fields3 and still ordering by fields desc, the ordering results got changed: record2 record1 record3 record4 record5 Why is this happening? -
Query problem how can i add or operator? with query dict
Hope You Are Good My Problem is i want to find properties by cities and if we get none we want to find properties with location but how can i achive this i want to add or operator something to get that result but the problem is how can i do that? here is my following code (That doesn't work): query = {} if city: newCity = City.objects.filter(name=city.lower()).first() if newCity: query["city"] = newCity query["location__icontains"] = city.lower() # if not query: queryset = Property.objects.filter(**query).order_by('-id') I want if properites with city doesn't found try with location! Thanks -
NameError at /admin/notebook/series_num/add/ [closed]
Would you guys please help me here. Why i get error ? NameError at /admin/notebook/series_num/add/ name 'model_num' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/notebook/series_num/add/ Django Version: 3.1.1 Exception Type: NameError Exception Value: name 'model_num' is not defined Exception Location: D:\PythonDjango\django_doc_mysite\notebook\models.py, line 16, in __str__ Python Executable: D:\PythonDjango\VENV\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\PythonDjango\\django_doc_mysite', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'D:\\PythonDjango\\VENV', 'D:\\PythonDjango\\VENV\\lib\\site-packages'] Server time: Wed, 16 Sep 2020 13:42:23 +0800 I created 2 database in the models.py and registered 2 databases in the admin.py I added data to Brand successfully but i got error when I add data to the database of series_num -
Django - Last Updated By and Update Date not working
Hi I need someone's advice. I created a form add organizations and a form to edit organizations. These are working fine. However, I have Last Updated By and Update Date fields on the model - These are not picking up the datetime and user information when editing the organization. views.py @login_required() def organization_edit(request, pk): org = Organization.objects.get(org_id=pk) form = OrganizationEditForm(instance=org) # Update Org if request.method == 'POST': form = OrganizationEditForm(request.POST, instance=org) if form.is_valid(): form.organization_code = form.cleaned_data['organization_code'] form.company_name = form.cleaned_data['company_name'] form.legal_name = form.cleaned_data['legal_name'] form.business_registration_no = form.cleaned_data['business_registration_no'] form.vat_registration_no = form.cleaned_data['vat_registration_no'] form.industry_distribution = form.cleaned_data['industry_distribution'] form.industry_education = form.cleaned_data['industry_education'] form.industry_healthcare = form.cleaned_data['industry_healthcare'] form.industry_manufacturing = form.cleaned_data['industry_manufacturing'] form.industry_retail = form.cleaned_data['industry_retail'] form.industry_services = form.cleaned_data['industry_services'] form.effective_start_date = form.cleaned_data['effective_start_date'] form.effective_end_date = form.cleaned_data['effective_end_date'] org = form.save(commit=False) org.last_updated_by = request.user org.save() return redirect('organizations_settings') context = { 'form':form, 'org':org, } return render(request, 'settings/edit_organization.html', context) models.py class Organization(models.Model): org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False) organization_code = models.CharField(max_length=20) company_name = models.CharField(verbose_name="Company Name", max_length=60) legal_name = models.CharField(verbose_name="Legal Name", max_length=100) industry_distribution = models.BooleanField(verbose_name="Distribution", default=False) industry_education = models.BooleanField(verbose_name="Education", default=False) industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False) industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False) industry_retail = models.BooleanField(verbose_name="Retail", default=False) industry_services = models.BooleanField(verbose_name="Services", default=False) business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True) vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True) created_date = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created … -
Django/Templates/CSS: Fit a Plotly graph inside a responsive grid
I am using Django and trying to embed Plotly plots into my HTML templates. For testing I copied the simple examples into my views.py. This is the 2nd plot: # Plot 2 animals = ['giraffes', 'orangutans', 'monkeys'] fig2 = go.Figure([go.Bar(x=animals, y=[20, 14, 23])]) plot_div2 = plot(fig2, output_type='div', include_plotlyjs=False) All plots are included by the context dict. context = { 'plots': { 'test1': plot_div1, 'test2': plot_div2, }, } In my template home.html there is a responsive Grid (12 cols). The graphs are plotted side by side (each graph is inside a 6-col element). So one plot looks like this: <div class="p-relative col-6 pd-5 border-box elevation-1 primary"> <div class="p-relative border-box w-full"> {{plots.test1|safe}} </div> </div> Parent element CSS: position: relative; grid-column-end: span 6; padding: 1.25rem; box-sizing: border-box; box-shadow: ... ; background: ...; Child element CSS: position: relative; box-sizing: border-box; width: 100%; The Problem: The plot's height looks okay, but the plot's width is bigger than the container width. Because the plots should be displayed inside a responsive grid it would make no sense to resize the plots using pixels. The attached pictures shows the problem. Plot overflow (Picture) -
Get multiple objects of reverse foreign_key relation inside values()
I have two django models as below: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Entry(models.Model): entry_id = models.Autofield(primary_key=True) blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='blog') headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() I'm trying to get the backward relation using related_name. I want to get the entire data of the 'Entry' by using related_name 'blog'. There are multiple entry's for each blog. How can I achieve the following output: {'name': '', 'tagline': '', 'all_blogs':[{'blog': '','headline': '','body_text': '','pub_date': '', 'mod_date': ''},]} I tried this: response = Blog.objects.filter( name=name, blog__pub_date=date ).values( 'name', 'tagline', all_blogs=Entry.objects.filter(entry_id=F(blog__entry_id)).values() ) return response But it is throwing field error saying I cannot use "blog" field inside F() expression. Thanks for the response. -
how to calculate data fields that are filled in a certain id, implementing the count formula in excel in django?
ini adalah contoh kasus dalam pengisian baris data excel yang nantinya akan saya coba adaptasikan ke dalam penyimpanan data di django. Models.py class Quality_Model(models.Model): name = models.ForeignKey(Members, blank=True, null=True, on_delete=models.CASCADE) year = models.IntegerField(default=0,blank=True) jan = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) feb = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) mar = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) apr = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) mei = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) june = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) july = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) ags = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) sept = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) oct = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) nov = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) des = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) avg = models.DecimalField(max_digits = 5,decimal_places = 2,default=Decimal(0),blank=True,null=True) Views.py @login_required(login_url = settings.LOGIN_URL) … -
Django CreateView - How to leave some blank fields in the form
I have a CreateView class where I am passing a ModelForm. In this form, I made a checkbox. In the template, I am hiding some fields. If the user tick the checkbox, I remove the hidden attribute from those fields and make them Required. Otherwise, If the user doesnt tick the checkbox, I remove their attribute required and hide them. When I try to submit it with the checkbox unticked, it keeps redirecting me on the form (form invalid). If I tick the box and all the elements are fulfilled, it works well and redirect me on the main page of course. In the model, all the fields that could be hidden are having a default value... Could someone explain how I could leave these fields blank please? I will attach below all the code which could be useful if you wanna check it.. View.py: class QualityCreateView(LoginRequiredMixin, CreateView): model = Quality form_class = QualityForm def form_valid(self, form): if form.is_valid(): print('Valid!') else: print('not valid!') return super().form_valid(form) def get_success_url(self): return reverse('teamleaderworkspace:quality') #Checking if kwargs['instance'] is None means that the code works with both CreateView and UpdateView. def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) if kwargs['instance'] is None: kwargs['instance'] = Quality() kwargs['instance'].team_leader … -
TypeError: Object of type Asia/Kolkata is not JSON serializable
I am trying to use timezone_field, but it shows it is not serializable and shows error. Please need your help. I have provided code in below.. Thanks in advance. Models.py from django.db import models from timezone_field import TimeZoneField # Create your models here. class Member(models.Model): tz = TimeZoneField(default='Asia/Kolkata') def __str__(self): return self.tz serializers.py from . models import Member from rest_framework.serializers import ModelSerializer class Member_Serializer(ModelSerializer): class Meta: model = Member fields = '__all__' views.py from . models import Member from . serializers import Member_Serializer from rest_framework.generics import ListCreateAPIView # Create your views here. class MemberListView(ListCreateAPIView): queryset = Member.objects.all() serializer_class = Member_Serializer error: Object of type Asia/Kolkata is not JSON serializable Request Method: POST Request URL: http://localhost:8000/a/ Django Version: 3.1.1 Exception Type: TypeError Exception Value: Object of type Asia/Kolkata is not JSON serializable -
Form onSubmit is not updating the page
**first time asking qn on stack overflow so i apologize if i didn't do it right hah...and I am a beginner in React so this question might sound silly haha! So guys, my problem is that whenever I click on submit, it doesn't show any change and also the text on the form where you type title and content is still there. I tried using 'onSubmit' but it doesn't make any changes in my database and doesn't refresh the page either. So I used 'onSubmitCapture' and when I do so, doesn't show the change, doesn't empty the 'title' and 'content' that I typed in but in my Django Admin I can see that it added a new article or updated an existing one if I edited it. So, if i refresh it manually, i can see that it updated it, both while creating and updating an article. I couldn't find a solution for this because most problems are with the React app being refreshed every time the form is submitted. I was wondering if there us a way that I can empty the input fields and update the page too. This is the code...I was watching a tutorial on a … -
Django annotation on (model → FK → model) relation
Galaxies across the universe host millions/billions of stars, each belonging to a specific type, depending on its physical properties (Red stars, Blue Supergiant, White Dwarf, etc). For each Star in my database, I'm trying to find the number of distinct galaxies that are also home for some star of that same type. class Galaxy(Model): ... class Star(Model): galaxy = ForeignKey(Galaxy, related_name='stars') type = CharField(...) Performing this query individually for each Star might be comfortably done by: star = <some_Star> desired_galaxies = Galaxy.objects.filter(stars__type=star.type).distinct() desired_count = desired_galaxies.count() Or even, albeit more redundant: desired_count = Star.objects.filter(group__stars__type=star.type).values('galaxy').distinct() This get a little fuzzier when I try to get the count result for all the stars in a "single" query: all_stars = Star.objects.annotate(desired_count=...) The main reason I want to do that is to be capable of sorting Star.objects.order_by('desired_count') in a clean way. What I tried so far: Star.annotate(desired_count=Count('galaxy', filter=Q(galaxy__stars__type=F('type')), distinct=True)) But this annotates 1 for every star. I guess I'll have to go for OutRef, Subquery here, but not sure on how. ps: This is just an analogy for the unattractive models and fields within my code. I'd be inclined to think that all the galaxies host every type of star as we classify them, or … -
How to get value of <h1> and <p> tag(which changes dynamically time to time) from html to Django in views.py and print in def
SO I want to print the value of restName (which is in )in vscode console after positive. When I click on the submit button it should be get printed in the console in def. Views.py def home(request): if request.method == 'POST': if request.POST.get('form2'): print("Positive") restName=str(request.POST.get('restName')) print(restName) return render(request,'rest.html') else: print("Negative") rests= Restaurent.objects.all() for rest in rests: print(rest) return render(request,'home.html',{'rests':rests}) HTML CODE <div class="container-fluid"> <div class="container-fluid " > <div class="row "> {% for rest in rests %} <form action="home" method="post" > {% csrf_token %} <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3" > <div class="card" style="width: 18rem;"> <img src="{{rest.RestImg.url}}" class="card-img-top" alt="..."> <div class="card-body"> <!-- I want RestName and RestAddr send to Rest Def in views.py --> <h5 class="card-title" name="restName">{{rest.RestName}}</h5> <p class="card-text" name="restAddr">{{rest.RestAddr}}</p> <input type="submit" name="form2" > </div> </div> </div> </form> {% endfor %} </div> </div> </div> -
Django ImportError: Couldn't import Django When Use Docker
I am getting an error in console while trying to use docker. How to fix it but when I test With localhost it just work. error PS C:\Users\Test\Desktop\Projects\Testadmin\master> docker-compose up Creating network "master_default" with the default driver Creating master_web_1 ... done Attaching to master_web_1 web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 8, in <module> web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 10, in <module> web_1 | raise ImportError( web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? master_web_1 exited with code 1 docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED l RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ manage.py #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'master.settings') try: from django.core.management import execute_from_command_line except ImportError as … -
Django object of type 'type' has no len()
we can't get the http response as json. Error we encountered: TypeError at /ui/subfix/3 object of type 'type' has no len() Request Method:GETRequest Code sample: @api_view(('POST',)) @csrf_exempt @renderer_classes(JSONRenderer,) def project_image_alternative_form_submit_ajax(request, object_id): project_image = ProjectImage.objects.filter(pk=object_id).first() response_json = { 'message': 'Image ...', } return Response(response_json, status=status.HTTP_200_OK) -
I want to add First name and last name field
My form only gives me username, email, password1, password2, i wanna have First name and Last name on this firl too. My form: <div class="col-12"> <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> -
OperationalError at / no such table: posts_post
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error "OperationalError at / no such table: posts_post". -
name 'AuthUserUserPermissions' is not defined
I'm really confused.I want to create and insert data to auth_user_user_permissions, but it seems it not working. I also already imported . Please explain and help me from django.contrib.auth.models import User, auth, Permission current_code AuthUserUserPermissions.objects.create(permission_id=id, user_id=user.id) -
How to write log records to existing error log file
The error log that my django error's get written to is highly accessible. As a result, within my code, I'd like to use this same file for my logging. My configuration looks like this. Settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/opt/python/log/djangoerrors.log' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } Within my view, I've got this: import logging logger = logging.getLogger(__name__) def myview(request): ... some code ... logger.error('hello. This should be logged to the error file.') Unfortunately, this text isn't being written to my djangoerrors.log file. Can you see what I'm missing? Thanks! -
How to filter table using daterangepicker?
I used AdminLTE's Date Range Picker for my web application. What I need to do is to flter the datatable I have using the said date range. But the output of the picker is all integer type, wherein my datatable date and time is alphanumeric. Date range picker: The dates in my table: I have no idea how to convert the 'month' integer to string in able to filter the table. I am using django default 'datetime.now' on saving the data. How do I use this date range picker for filtering? -
Content Aggregator
I am web scraping data from skysports of all the top european football table standings. I was able to get the dataframe with pandas but I can not find a solution to display the tables on html besides using csv files. Is there another way or do I have to use a different technology? Please and thanks page = [ 'https://www.skysports.com/premier-league-table', 'https://www.skysports.com/la-liga-table', 'https://www.skysports.com/bundesliga-table', 'https://www.skysports.com/serie-a-table', 'https://www.skysports.com/ligue-1-table' ] league = [ "epl", "liga", "bund", "serie", "ligue", ] for pag, leag in zip(page, league): response = requests.get(pag) soup = BeautifulSoup(response.text, 'html.parser') top_col = soup.find('tr', attrs={'class': 'standing-table__row'}) columns = [col.get_text() for col in top_col.find_all('th')] last_df = pd.DataFrame(columns=columns) last_df contents = soup.find_all('tr', attrs={'class':re.compile('standing-table__row')}) for content in contents: teams = [tea.get_text().strip('\n') for tea in content.find_all('td')] first_df = pd.DataFrame(teams, columns).T first_df.columns=columns last_df = pd.concat([last_df,first_df], ignore_index=True) -
MultiValueDictKeyError : file attachement
Hi there i'm trying to send an email with a file as attachement but i get an MultiValueDictKeyError error this is my view: def postuler_save(request): name = request.POST.get('name', '') mail = request.POST.get('mail','') numero = request.POST.get('numero','') etablissement = request.POST.get('etablissement','') email= EmailMessage("message from:" + "" + name, "phone number:" + ""+ numero + "mail:" + ""+ mail+"etablissement" + ""+ etablissement,EMAIL_HOST_USER,[mail]) email.content_subtype = 'html' file = request.FILES['file'] email.attach(file.name, file.read(), file.content_type) email.send() return HttpResponseRedirect("/") this is the traceback Traceback (most recent call last): File "C:\Users\WD\Miniconda3\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('file'), another exception occurred: File "C:\Users\WD\Miniconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\WD\Miniconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\WD\Desktop\weserveit\gestion\views.py", line 32, in postuler_save file = request.FILES['file'] File "C:\Users\WD\Miniconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /postuler_save Exception Value: 'file' -
Django Rest framework Simple JWT Custom Authentication
I am new to django and having trouble with authentication. I have different users(customer, admin, operator). So i want to authenticate according to the type of user when they hit a specific URL. I am using simple jwt to create tokens but cannot authenticate the username and password in the specific api view. -
What is the purpose of the UID within this Django Sign Up Function
I am learning how to create a django sign up page and I am at the point of creating an email verification. I am trying to use the code snippet here: def usersignup(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() return HttpResponse('We have sent you an email, please confirm your email but I do not know what purpose the uid serves. Why is encoding the user model object in the verification email necessary? -
I am importing Django select2 widget and getting Uncaught typeError
I am trying to import a Django Select2 widget, but keep getting an Uncaught typeError: adapter is not a function. I can't seem to find this issue online, but previously I was running the urls below in my widgets.py https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css I want to upgrade to most recent version of select2 (4.0.13), but can't seem to get it to work. How can I fix this? class Select2Mixin(): class Media: css = { 'all': ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css",) } js = ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.js", 'js/customselect2.js') def update_attrs(self, options, attrs): attrs = self.fix_class(attrs) multiple = options.pop('multiple', False) attrs['data-adapt-container-css-class'] = 'true' if multiple: attrs['multiple'] = 'true' for key, val in options.items(): attrs['data-{}'.format(key)] = val return attrs def fix_class(self, attrs): class_name = attrs.pop('class', '') if class_name: attrs['class'] = '{} {}'.format( class_name, 'custom-select2-widget') else: attrs['class'] = 'custom-select2-widget' return attrs class Select2Widget(Select2Mixin, forms.widgets.Select): def __init__(self, attrs=None, choices=(), *args, **kwargs): attrs = attrs or {} options = kwargs.pop('options', {}) new_attrs = self.update_attrs(options, attrs) super().__init__(new_attrs) self.choices = list(choices) class Select2MultipleWidget(Select2Mixin, forms.widgets.SelectMultiple): def __init__(self, attrs=None, choices=(), *args, **kwargs): attrs = attrs or {} options = kwargs.pop('options', {}) new_attrs = self.update_attrs(options, attrs) super().__init__(new_attrs) self.choices = list(choices) I also call this into my html file <html> <head> <!--Importing CSS stylesheets--> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" /> <link …