Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fill automatically a foreign key on a form of multiple pages in Django? (function based view)
I'm developing a website where the user have to compile a form to start an equipment purchase procedure. In my django website I've created several models with the Foreign Key referred to the principal model which is called MAIN. In particular I have these two models: MAIN and SPECIFICATIONS. SPECIFICATIONS has a foreign key which is ID_request and it connects to the MAIN model. models.py class MAIN(models.Model): ## attributes class SPECIFICATIONS(models.Model): ID_request = models.ForeignKey(MAIN, on_delete=models.CASCADE) Spec = models.CharField(max_length=100, blank=False) CliReas = models.CharField(max_length=100, blank=False) rif = models.IntegerField(default=0, null=False) MinMax = models.CharField(max_length=20, blank=True) I'm structuring the form into two pages, where in the first one the user has to compile some fields of the MAIN model. In the second one I would like to make the user fill 'Spec', 'CliReas', 'rif', 'MinMax' fields, but I want also the ID_request be automatically set to that of the previously entered device. Can you suggest me how I can do it? I'm using function-based views: views.py def new_2_4(request): form = SpecForm() if request.method=='POST': form1 = SpecForm(request.POST) if form1.is_valid(): form1.save() return redirect('/') context={'form1': form1} return render(request, 'new_2_4.html', context) And forms.py class SpecForm(ModelForm): class Meta: model = SPECIFICATIONS fields = ['ID_request', 'rif','Spec', 'CliReas', 'MinMax'] Thank you in … -
Requests in Django from different site
I am very new to Django, I am trying to request informations from another side to display them on my own. My site works and outside of Django I can request. I have no idea how to request and display the informations in Django neither where to do this in the project. Please help. -
User.save() got an unexpected keyword argument 'update_fields' while login
I am developing a blog website and i was working on editing profile information and made some changes in profile template and after making changes to template and suddenly get this error while login it was working before editing templates and now registration is also not working and i am not able login using admin panel User.save() got an unexpected keyword argument 'update_fields' Models.py class User(AbstractUser): profile_image = models.ImageField(("Profile Image"), upload_to='ProfileImage', max_length=None, blank = True,null = True) profile = models.TextField(("Profile"),blank = True) def save(self): super().save() img = Image.open(self.profile_image.path) if img.height > 400 or img.width > 400: new_img = (400, 400) img.thumbnail(new_img) img.save(self.profile_image.path) def __str__(self): return self.username' Views.py class userLogin(View): def get(self,request): return render(request,"account/login.html") def post(self,request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] #try: user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect('/') else: messages.error(request, "Invalid username or password.") return render(request,'account/login.html') I dont know what happened suddenly i didnt change anything other than things is teamplate -
Problem with updating and saving object in django-rest-framework
I have a problem with updating and saving object based on frontend input in Django-rest-frameweork. Everything seems to work fine, because this piece of code accually creates an object. The problem is whenever I want to save FE CartItem.amount = 10 this code returns value of 1. I am 100% sure I'm putting correct int value into the url. I am getting user_id, token, product_id and amount from this url: path('add-to-cart/<int:user_id>/<str:token>/<int:product_id>/<int:amount>/', add_item_to_cart, name="add-to-cart"), Then I use this function to either create of update an object: @csrf_exempt def add_item_to_cart(request, user_id, token, product_id, amount): if validate_user_session(user_id, token): user = CustomUser.objects.get(id=user_id) product = ProductStock.objects.get(id=product_id) if product.quantity < amount: return JsonResponse({'error':"You are trying to order more then we can provide!"}) try: existing_item = CartItem.objects.get(user=user, product=product) updated_amount = existing_item.amount + amount if updated_amount > product.quantity: existing_item.save(amount=product.quantity) return JsonResponse({'success':"Product updated in the database!"}) else: existing_item.save(amount=updated_amount) return JsonResponse({'success':"Product updated in the database!"}) except ObjectDoesNotExist: cart_item = CartItem(user=user, product=product, amount=amount) cart_item.save() return JsonResponse({'success':"Product created in the database!"}) else: return JsonResponse({'error':"You need to be logged in for that action!"}) Here are ProductStock and CartItem objects: class CartItem(models.Model): name = models.CharField(max_length=50, blank=True, null=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) product = models.ForeignKey(ProductStock, on_delete=models.CASCADE, blank=True, null=True) amount = models.IntegerField(default=0, blank=True, null=True) size = … -
Excluding a custom field from admin create object
Like here, I want to make a field only visible when editing the already existing object: I have a straight forward admin: @admin.register(Store) class StoreAdmin(admin.ModelAdmin): from = StoreAdminForm ... and I have a form with an extra field: class StoreAdminForm(forms.ModelForm): img = forms.ImageField() ... Now I want to exclude img when creating a new object. I tried extending the StoreAdmin class by: def add_view(self, request, extra_content = None): self.exclude = ("img",) return super().add_view(request) but this has no effect - I guess this just does not work on manually created fields? -
Correct approach to big model with no user accounts
I want to create django+react app that does not utilize user accounts in any way but it collects a lot of user input in a single page. Is there any way to allow user to look into his input a day later? Can i just store the object in cookies? Or can I save sessionid and load model when user refreshes website? Also- it will be like a big form saved to a single object. Is it good idea to create such a big model? For example- user provides whether or not does he have a windows in his room. If so he writes which wall is it on, it's height, width, distance from left corner, width of sill. Should it be a new model called, idk WindowConfig or something like that? It will be more readable but on the other hand it complicates serializers. -
Python requests verify certificat in production
I'm beginner in Django, python and I have an application in Django 2.2 and it communicates with vCenter REST API. Where I have two servers Server 1: 10.125.65.70 Server 2 : 10.126.80.80 I development I use verify = False But I can't use that in production. I would like to create an if condition, which checks if we want to establish a connection with or without certificate verification. I can't use this verify='/path/to/public_key.pem' because In production I use two different certificates between Vcsa(Server). import requests import os import json from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) os.environ["REQUESTS_CA_BUNDLE"] = os.path.join("/etc/ssl/certs/") req = requests.Session() req.verify = False class VmwareApi: def __init__(self): self.ip = "" self.user = "" self.password = "" self.arg1 = "" self.ses = "" self.params = "" def session(self): try: a = req.post( "https://" + self.ip + "/api/session", auth=(self.user, self.password), timeout=1, verify=False, ) self.ses = str(a.json()) except requests.exceptions.Timeout: return "ConnectTimeoutError" return req def param_loader(self): if self.params: self.params = json.loads(self.params) def vapirequestget(self): try: VmwareApi.param_loader(self) myreq = req.get( "https://" + self.ip + self.arg1, params=self.params, verify=False, headers={"vmware-api-session-id": self.ses}, timeout=1, ) return myreq except requests.exceptions.Timeout: return "ConnectTimeoutError" -
form.instance doesn't populate field
I have the following form for creating a user: class CreateAccount(UserCreationForm): class Meta: model = USER fields = ['first_name','last_name','username','email','employee_id','is_active','is_staff'] and it's view: class CreateAccountView(CreateView): model = USER form_class = CreateAccount template_name = 'createaccount.html' def form_valid(self, form): form.instance.employee_id = Employee.objects.get(username=self.kwargs.get('username')) return super().form_valid(form) def get_success_url(self): return reverse('People') I used form.instance to pass it an employee object, but it doesn't work and I get 'This field is required. ' error, I used it in the exact same way in my other apps and it worked fine, does anyone have any idea what seems to be different here? -
Django - Generic Relations
I have a website with different kinds of activities: Lessons ; Exercises ; Quizzes. So far, each type of activity corresponds to a specific Model and a table in the database. I would like to create an ordered path through these activities. For instance: Lesson 1 then Exercise 1 then Lesson 2 then Quizz 1 etc. I am considering to create a model named Activity that would store the following data: A number: the number of the activity in the path ; A One-To-One relationship to one given activity (lesson, exercise, quizz etc.). (1) I have seen that Django offers a GenericForeignKey to handle many-to-one relationship to different kinds of models, like many comments associated to a single lesson or a single exercise. Is there something similar for Generic OneToOne relationship? (2) I would like to track the progress of my users. To do so, I am considering having a many-to-many relationship called "done_activities" built in my User model and linked to my Activity model. Do you think this is an efficient way of approaching the problem ? -
How to update integer field in DRF
In my project there is video module, related to this module user can add vodeo bookmarks, class VideoBookmark(BaseModel, SoftDelete): video = models.ForeignKey(Video, on_delete=models.CASCADE) sort_order = models.PositiveSmallIntegerField(null=False, blank=False) name = models.CharField(max_length=254, null=True, blank=True) description = models.CharField(max_length=254, null=True, blank=True) duration = models.DurationField(default=timedelta()) start_time = models.DurationField(default=timedelta()) end_time = models.DurationField(default=timedelta()) mobile_thumbnail_image = models.ImageField(upload_to='video_bookmark_mobile_thumbnail', height_field=None, width_field=None, null=True, blank=True) web_thumbnail_image = models.ImageField(upload_to='video_bookmark_web_thumbnail', height_field=None, width_field=None, null=True, blank=True) def __str__(self): return str(self.name) Bookmark3 is in the order of "2" and when trying to add bookmark2 in the order of "2" the order of bookmark3 should be changed to the order of "3".I don't know how to implement this, Can you suggest a way to implement this? -
Circular Import error in Django occurs only when i import geemap package
I am trying to use geemap in combination with django to build a web app for plotting satellite data. I have installed the geemap package in my django project. My projects name is CustomMaps, and the directory structure is as below. enter image description here The code for my CustomMaps.urls.py is as below from django.contrib import admin from django.urls import path from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('plotmap/', include('PlotMap.urls')), ] The code for my PlotMap.urls.py is as follows from django.urls import path from django.conf.urls import include, url from .views import hello urlpatterns = [ path('hello/', hello, name = 'hello'), ] And my PlotMap.views.py is as follows from django.http import HttpResponse from django.shortcuts import render import geemap as gm #import pandas as pd def hello(request): map = gm.Map() return render(request, "PlotMap/hello.html", { "m" : map}) But I am getting the following error on running the project Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Internship\Django App\MyProject\lib\site-packages\django\urls\resolvers.py", line 604, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in … -
get MongoDb ObjectId in Django Serializer
I am creating a Django server using django_rest_framework and mondogb(djongo). I want to use mongoDb generated ObjectId as primary key. How to get the mongoDb ObjectId from serializer class? This is my user model class User(AbstractUser): name = models.CharField(max_length=255) description = models.TextField(default='', blank=True) profile_pic = models.ImageField(upload_to='static/profile_pics/', blank=True) username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] This is my user serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'name', 'description', 'profile_pic'] extra_kwargs = { 'password': {'write_only': True} } views.py class GetUserView(APIView): def get(self, request): data = UserSerializer(User.objects.filter(id=request.id)).data return Response(data) This returns a json object { 'id': '<id>' eg: 1 or 2 or 3 etc.. 'name': '<user-name>', 'username': '<username>', 'description': '<description>', 'profile_pic': '<profile_pic>' } But I want to get below mentioned id(mongoDb ObjectId) { 'id': 621343a45048323e635c4ae6 ... } -
Initial value of django form field with django tag value
I have created a django form. This form is used to update the values of an existing object. That's why I want to show initial values which are taken from django variables inside django tags. Here is the django form. class RevisionStatusForm(forms.ModelForm): """ Update Revision""" class Meta: model = Revision widgets = { 'status': forms.Select(attrs={'required': True}),} fields = ['status','remark'] on my HTML template, here is how it currently looks: <td>{{revisionstatusform.remark}}</td> Here is how I want it to work: <input type="text" name="remark" value="{{revision.remark}}">. I want to show revision.remark variable value inside input field created from django forms. I don't know how to do it. Can anyone help? -
How to get the authentificated user information in Model Serializer in Django Rest?
I have a LinkList object, which has owner property - the username of the User it belongs to. I am trying to have LinkLists be linked to the user that made the create request, however self.context['request'].user and CurrentUserDefault don't work in my create method, so I cannot create an instance of the LinkList object. The error I am getting: NOT NULL constraint failed: llists_linklist.owner_id Here is the serializer: class LinkListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="lists-detail") owner = serializers.ReadOnlyField(source='owner.username') links = LinkSerializer(many=True) class Meta: model = LinkList fields = ['url', 'owner', 'name', 'public', 'links'] def create(self, validated_data): links = validated_data.pop('links', []) instance = super().create(validated_data) for item in links: instance.links.add(link=item) return instance The model: class LinkList(models.Model): owner = models.ForeignKey( User, related_name='lists', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=250) public = models.BooleanField(default=False) links = models.ManyToManyField( Link, related_name='linklists') def __str__(self): return "%s - %s" % (self.owner, self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) -
html iterate through dictionary in django and button download
i am working on an app on django 2 pbl: i used defaultlist but not working nothing on my output , my button download is not working : i received this error :"AttributeError at /views.download_my_pdf 'str' object has no attribute 'read' " I want to download my home page to pdf what i did wrong please? Django views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.http import HttpResponse from wsgiref.util import FileWrapper def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df =results1(file_directory,file_directory2) return render(request,"results.html", {"results":results,"output_df":output_df,}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) for x in date_index: if time>2h: results_list["List of samples better"].append(sample_id) if len(u_index) > 1: results_list["List of Samples "].append(sample_id) output_df = output_df.append(row_to_add, ignore_index=True) else: results_list["List of Samples not in the listing file"].append(sample_name[0]) except: print('The template name isnt good: {}'.format(sample_id)) return results_list, output_df.to_html() def download_pdf(request): filename = 'faults.pdf' … -
I want to check filtered field at drop-down in django-admin
When the classification field is checked, I want to filter only the values according to the classification filed so that it can be checked in the dropdown. and I installed django-clever-selects. i usually the choicefields were written in the models.py, but django-clever-selects seemed to be usually put in and used at helpers.py, so I did. when i checked in the account_classification field at models.py in admin (tuple content of helpers.py 'expenses'), i want to check only the filtered field in the account_category field (tuple content of helpers.py CATEGORY). In the form of the picture below. enter image description here # models.py class AccountBook(TimeStampedModel): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False) account_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)], null=False, verbose_name="금액") # 금액 account_reference = models.CharField(max_length=200, null=True, verbose_name="참조내용") account_manager = models.CharField(max_length=10, null=False, verbose_name="담당자") account_recoder = models.CharField(max_length=10, null=False, verbose_name="기록자") # account_classification = models.CharField(choices=EXPENSES, max_length=100, null=True, blank=True, verbose_name="분류") # 분류 - 저장시킬 필드 # account_category = models.CharField(choices=CATEGORY, max_length=100, null=True, verbose_name="범주") # 범주 - 저장시킬 필드 # forms.py class AccountBookForm(ChainedChoicesForm, forms.ModelForm): account_classification = ChoiceField(choices=[('', (u'Select a classification'))] + list(EXPENSES)) account_category = ChainedChoiceField(parent_field='account_classification', ajax_url=reverse_lazy('ajax_chained_category'), empty_label=(u'Select category')) class Meta: model = AccountBook fields = ["branch", "account_classification", "account_category", "account_amount", "account_reference", "account_manager", "account_recoder"] views.py class SimpleChainView(FormView): form_class = AccountBookForm template_name = '/' success_url = '/' … -
Can we merge multiple pdf in django with weasyprint?
https://weasyprint.org/ I have two different pdfs and want to merge than using weasyprint so that whenever the user downloads the pdf it should download the pdf which consists of the both the pdf in single one -
The connection to postgresql on django is not working and some issues were found after migrating
`DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'todoDB', 'USERNAME': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', } }` command prompt error Traceback (most recent call last): django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "admin" -
How to get highest bid for every item in an auction bidding site Django
So I have a Django auctions app, which has 3 models: Users, Listings, Bids. When a user tries to place a bid on some listing, I want to check if the new_bid field in Bid model is bigger than start current_bid field in Listing model and if the new_bid is <= 0, it should return a message. This is what I've done so far but when I click on 'Place bid' button, it does not implement this (it does not show any message for any of the above scenario and my count does not increase) meaning that the form is not submitting. Why is this not working? VIEWS.PY def listing_detail(request, listing_id): try: detail = get_object_or_404(Auction, pk=listing_id) except Auction.DoesNotExist: messages.add_message(request, messages.ERROR, "This is not available") return HttpResponseRedirect(reverse("index")) bid_count = Bids.objects.filter(auction=listing_id).count() context = {'detail': detail, 'bid_count': bid_count, 'bidForm': BidForm()} return render(request, 'auctions/details.html', context) @login_required def make_bid(request, listing_id): if request.method == 'POST': form = BidForm(request.POST) if form.is_valid: each_listing = Auction.objects.get(pk=listing_id) highest_bid = Bids.objects.filter(pk=listing_id).order_by('-new_bid').first() new_bid = form.cleaned_data.get['new_bid'] if new_bid <= 0: return render(request, 'auctions/details.html', {"message": "Input an amount greater than 0"}) # messages.add_message(request, messages.SUCCESS, "Input an amount greater than 0") elif new_bid <= highest_bid.new_bid: messages.add_message(request, messages.ERROR, "Amount is low, please increase the bid") else: … -
Attribute Error when Running Django Rest API
I have created a simple project called djangowallet and inside that project, I have created an app called wallet with a model wallet and just one field called raddress. I have created the serializer, views and URLs and when I runserver it gives the following error. PS C:\Users\Ahmed\djangowallet> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 448, in check for pattern in self.url_patterns: File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, … -
How can we send bulk_email in django using different from_emails?
I have 1 Django app and i want to send bulk_email to multiple users, so normally it will send from only 1 from_email. Now how can I send bulk_email from different from_email when I select 1 email from the dropdown list? -
How to mock instance attribute of django form
I'm doing a unit test where I'm mocking a Django form, but I'm having some trouble because I need to mock two things from the form: An instance attribute (token) A method (is_valid) I'm using the form in a view, importing it like this: from profiles.forms import PaymentForm And I have tried the following to mock it: @patch('profiles.forms.PaymentForm') def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class): payment_form_class.is_valid.return_value = True payment_form_class.cleaned_data = {'token': 1} This approach does not work, is_valid returns false. @patch('profiles.forms.PaymentForm') def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class): payment_form_class.return_value.is_valid = True payment_form_class.return_value.cleaned_data = {'token': 1} This neither. I'm using Django and unittest. I have successfully mocked the is_valid with a helper function of our code base, but it does not seem to work with instance attributes. Any idea how to solve this? -
Calculate age from date of birth using django orm query
I am calculating age using python code like age = datetime.date.today().year - patient_table.dob.year - ((datetime.date.today().month, datetime.date.today().day) < (patient_table.dob.month, patient_table.dob.day)) i return correct age. but i need this result using Django orm query how i can do this? i tried like, PatientTable.objects.filter(is_active=True,is_deleted=False).annotate(age=datetime.date.today().year - F('dob__year')) but it getting wrong age. -
How can I loop salary amount against each employees?
I want my python to print the name of employees one by one (in a loop) and let me add the salary amount against each employee and in the last create a dictionary (key-value) for me, the key is employee name and value is amount and I also want to print out the total amount of salary means the sum of all the salaries. How can I do that That is what I did so far: employees = ["abc", "def", "ghi", "jkl", "mno", "pqr"] n=0 amonut= 0 try: for employee in employees: employee = employees[n] amount= int(input(amount)) total = sum(amount) n=n+1 print(total) except: print("You can only type integer for amount") I have no idea how to create a dictionary in the last -
Django filter search with dropdown
In Django, while taking entry from the user, I have created a dropdown from which user can select the field, but that dropdown can be longer. What I want is, it should also contain a filter search box where the user will enter the keyword and the fields related to that keyword will appear in front. Here is the screenshot of the current UI:- This is the code for selecting the "Annual Work Plan":- <div id="div_Select_Annual_Work_Plan" class="form-group col-md-4"> {{ form.Select_Annual_Work_Plan.label_tag }} {{ form.Select_Annual_Work_Plan }} {{ form.Select_Annual_Work_Plan.errors }} {% if form.Select_Annual_Work_Plan.help_text %} <p class="help">{{ form.Select_Annual_Work_Plan.help_text }}</p> {% endif %} </div> Inside forms.py, the field for "select annual work plan" is described as follows:- Select_Annual_Work_Plan = forms.ModelChoiceField(queryset=annual_work_plan.objects.none().order_by("Annual_Work_Plan_ID"), label='Select Annual Work Plan', ) Please let me know, in case any other piece of code is needed. I am new to Django and didn't find any solution on the internet.