Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to achieve dynamic filter in django
In my frontend, I have three kinds of filter and when user selects selects those and click on filter then I need to update the results. The problem is user may select any one or two or all the three filters combinedly. But my code just filters only one condition: Here is my code: filter1 = request.POST.getlist("filter1") //Every filters are in arrays filter2 = request.POST.getlist("filter2") //Every filters are in arrays filter3 = request.POST.getlist("filter3") //Every filters are in arrays data = Data.objects.filter(is_approved=True, published=True) //This the model to be filtered if len(filter1) > 0: data = data.filter(intakes__contains=filter1) if len(filter2) > 0: data = data.filter(elevel__contains=filter2) if len(filter3) > 0: data = data.filter(country__in=filter3) How to make this dynamic ? Like it should filter based on more than one selections. Please help -
What do i need to know to develop python AI chat bot?
I am currently developing a social media website with a lot of privacy settings and processes, which may require the users utilizing the application to need guidance through them smoothly and clearly, and I have been wondering to make an AI chat bot to serve as an assistant to the users, This website is made by Python Django MVC framework, What I am looking for is a python library that is executed like NumPy with C++, Fast performance Python AI library. I would how to create an AI chatbot?. Thanks in advance. -
ModuleNotFoundError: No module named 'whitenoise.django'
I'm getting this error (no module named 'whitenoise.django'), even though I ran pip install whitenoise on my project's folder. When I do that, it shows that the requirement is already satisfied. The code where the error appears is in my wsgi.py file. More specifically in this line: from whitenoise.django import DjangoWhiteNoise How do I install it properly? -
Best way to create a custom view and serializer output grouping the results based on a foreying key filter
I am doing some work around the Django rest framework to get an custom output that matches with the charts that i am using. But i am trying to figure out how can i group the serializer by the categories, that are a foreying key field. I don`t know if that would be nice to use filters in the get_query, or if there is a better solution, as there are many categories. Thats what i have made so far: my models: class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) class Asset(models.Model): category = models.ForeignKey(Category, related_name='categories', on_delete=models.CASCADE) ticker = models.CharField(max_length=255, unique=True) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) total_today_brl = models.FloatField() Here is the serializer: class PortfolioAssetSerializer(serializers.ModelSerializer): category = serializers.CharField(source='asset.category.name') x = serializers.CharField(source='ticker') y = serializers.FloatField(source='total_cost_brl') class Meta: model = models.PortfolioAsset fields = ( 'category', 'x', 'y', ) And here the view: class PortfolioAssetList(generics.ListAPIView): serializer_class = serializers.PortfolioAssetSerializer def get_queryset(self): return models.PortfolioAsset.objects.all() # return models.PortfolioAsset.objects.filter(asset__category__name="Fundos Imobiliários") def list(self, request, *args, **kwargs): response = super(PortfolioAssetList, self).list(request, *args, **kwargs) response.data = { "name": "category", "data": response.data } return response The output thath i could get with that code was that one: { "name": "category", "data": [ { "category": "category 1", "x": "ASSET1", "y": 10373.4 … -
How to duplicate Django models with OneToOneField relations
Start with the following models using django==3.2.12: from django.db import models class Root(models.Model): pass class Leaf(models.Model): root = models.OneToOneField(Root, related_name='leaf_data', on_delete=models.CASCADE) Run the following in the shell: >>> from myapp.models import Root, Leaf >>> root = Root() >>> root.save() >>> leaf = Leaf(root=root) >>> leaf.save() >>> root <Root: Root object (1)> >>> leaf <Leaf: Leaf object (1)> >>> new_root = Root() >>> new_root.save() >>> new_root <Root: Root object (2)> >>> root.leaf_data <Leaf: Leaf object (1)> >>> leaf = root.leaf_data >>> leaf.pk = None >>> leaf.root = new_root >>> leaf.save() >>> leaf.root <Root: Root object (2)> >>> root.leaf_data <Leaf: Leaf object (2)> Why does the original root.leaf_data reference change? I would expect that by setting leaf.pk = None and leaf.root = new_root that the original root/leaf structure would remain intact. I'm trying to create a full duplicate from the original. -
Python/Docker ImportError: Couldn't import Django but it's installed
I am trying to run a microservices program through my manager.py file that uses docker, but when I run the program using docker-compose up I get an ImportError that tells me that Django is not installed even though it is. I have tried to use the venv library to create and install Django using my virtual environment vegatestnet, have also tried to change my Windows path variable to point to the project, and finally, I have tried to even use import sys print(sys.path) to find where my PYTHON_PATH is but no dice. I have also tried to use these links to help me: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?, ModuleNotFoundError: No module named 'django' while running server in virtual environment, and Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file and I have tried their solutions but I still get this error. Here is the directory structure that I am working with: -veganettest ... -posts (folder) -profiles (folder) ... producer.py (my producer file) -static_cdn (folder) -static_project (folder) ... -veganettest (folder) -vegatestnet (virtual envoirment folder) admin (my admin file) consumer.py (my consumer … -
the problem is still return object not title and how to add in reference models
class Interest(models.Model): title = models.CharField(max_length=200) def _str_(self): return self.title I have trying use str to return the title but unfortunately it return back object 1 -
Apply Bulma css to Django drop down menu
How do I apply css from bulma to my Django field which is a drop down menu using widget=forms.Select. Bulma CSS: from the bulma.io site, their example implementation: <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Dropdown button</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Dropdown item </a> <a class="dropdown-item"> Other dropdown item </a> <a href="#" class="dropdown-item is-active"> Active dropdown item </a> <a href="#" class="dropdown-item"> Other dropdown item </a> <hr class="dropdown-divider"> <a href="#" class="dropdown-item"> With a divider </a> </div> </div> </div> This is what I tried: forms.py: class PostModelForm(forms.ModelForm): STATUS=[ ('live', 'Live'), ('draft', 'Draft'), ] status = forms.CharField(label='Status', widget=forms.Select(choices=STATUS)) class Meta: model = Post fields = ( 'status', ) def __init__(self, *args, **kwargs): super(PostModelForm, self).__init__(*args, **kwargs) self.fields['status'].widget.attrs.update({'class': 'dropdown-menu','id': 'dropdown-menu', 'role': 'menu'}) models.py class Post(models.Model): status = models.CharField(default='draft', max_length=10) post.html <form method="post"> {{ form.status.errors }} <p class="title">Status</p> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Select status</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> {{ form.status }} </div> {% csrf_token %} <div class="control"> <button type="submit" class="button">Submit</button> </div> </form> Further info I kept the form short for the question, but I have successfully implemented other … -
Django - Upload multiple files using filepaths provided in an excel file
Hope everyone is doing well. I'm trying to figure out how I can upload files from a file path provided in an excel file. Basically I'm allowing the user to upload multiple documents at once but the document name has to be different as such I'm using an excel upload file. How would I go about: Checking if the file exists (I.E File path is accurate) Getting the file to save to model Currently for 1 I'm using: error_list = [] i = 1 for record in df_records: my_file = Path(record['file_path']) try: my_abs_path = my_file.resolve(strict=True) except FileNotFoundError: error_list.append(f"Error in row: {i}, file path incorrect or file does not exists") I'm still looking for a solution, if I find it before someone answers I will post the answer. :) Thanks in advance, Tom -
Wrong table names format - Django
I'm having an issue with the table names format of my Django project. Here is a sample of a model I have: class WalletHistory(models.Model): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE, related_name='wallet_history') free_amount = AmountField(default=None, blank=True, null=True) locked_amount = AmountField(default=None, blank=True, null=True) flexible_amount = AmountField(default=None, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True, blank=True) The app associated with this model is called core so the table name is supposed to be core_wallet_history. But Django names my table core_wallethistory instead: it doesn't split the class names with underscore. I've changed nothing in the Django settings. -
Django messages not displaying properly but only on one page
I have a generic CreateView where users can submit a problem about an item. When a problem has not been submitted about an item, a submission template is show, when a user has submitted a problem, a template with the message history for that problem is shown. class PhotoProblemView(LoginRequiredMixin, CreateView): form_class = PhotoProblemMessageForm def get_template_names(self): if PhotoProblem.objects.filter(photo=self.kwargs.get('pk')).count() <= 0: return ['photo/photo_problem_create.html'] else: return ['photo/photo_problem_message.html'] def get_success_url(self): if PhotoProblemMessage.objects.filter(problem__photo_id=self.kwargs.get('pk')).count() <= 1: messages.success(self.request, "Your issue has been reported. Please allow 1 business day for a follow up.") return reverse('photo_problem', kwargs={'pk': self.kwargs['pk']}) else: return reverse('photo_problem', kwargs={'pk': self.kwargs['pk']}) def get(self, *args, **kwargs): if not Photo.objects.filter(id=self.kwargs['pk'],user=self.request.user).exists(): raise Http404 return super().get(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['photo'] = Photo.objects.get(id=self.kwargs['pk']) try: context['photo_problem'] = PhotoProblem.objects.get(photo_id=self.kwargs['pk']) except PhotoProblem.DoesNotExist: pass context['messages'] = PhotoProblemMessage.objects.filter(problem__photo_id=self.kwargs.get('pk')).order_by('created') return context def form_valid(self, form): try: problem = PhotoProblem.objects.get(photo_id=self.kwargs.get('pk')) except: problem = PhotoProblem.objects.create(photo_id=self.kwargs.get('pk')) problem.save() if problem.resolved == True: messages.error(self.request, "This issue has been resolved, you can no longer send messages. Please contact us if you need more help.") return super(PhotoProblemView, self).form_invalid(form) self.object = form.save(commit=False) self.object.problem = problem self.object.user = self.request.user self.object.save() return super(PhotoProblemView, self).form_valid(form) The issue is that when Django renders the message history template, it also is rendering messages stacked on top of each … -
Setup React, Python and Neo4j in Docker
I'm trying to set up a Docker container running React on the frontend, Django on the backend and Neo4j as the database. At the moment all three components are running correctly, but I just can't get Django to connect to the Neo4j database. I've probably read all the tutorials on the internet and tried all the things but it always comes up with some error and the database is unreachable or denies access. I have also worked through this tutorial and created the models accordingly. However, I always get an error when I run "python manage.py install_labels". As it looks I either can't connect to the database or the request is rejected. Has anyone of you ever set up a similar environment or can help me? Maybe Django is just not that suitable for it .... Basically I just want a React frontend and a Python backend working with a Neo4j database. And the whole thing please in a Docker image. Are there any better alternatives for the backend? Thanks in advance for your help! In the following you can see all of my files that are important in my opinion. My Dockerfiles look like this: # Django Dockerfile FROM … -
How do I deploy a monolithic Django/React app?
I’m trying to find a way to deploy my app that uses Django on the backend and React front end, and also uses the Spotify API. The project is based on this tutorial by Tech With Tim I’ve seen some tutorials that suggest splitting it up and deploying them as two apps, where the backend proxies API requests to the backend as necessary, however since my React app is served with Django, I don’t think this method is conducive to how my app is set up. I've tried to deploy with Heroku but I haven't been successful. I'm not sure if its relevant, but I used webpack. Here's my folder structure: Any help? I’d be much obliged. -
Adding instance name of FK to upload_to folder
I'm trying to save files in a specific folder depending on a foreign key of the model. This is the model where files are uploaded: class PersonVisual(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='visual') file = models.FileField(upload_to=upload_to_people_instance_folder) class Meta: verbose_name_plural = "people visuals" This is the function for upload_to, like I saw in other SO questions: def upload_to_people_instance_folder(instance, filename): clean_name = f"{instance.person.first_name}_{instance.person.last_name}" return f"/people/visual/{clean_name}/{filename}" That did what was expected, but I get the following error: SuspiciousFileOperation at /admin/others/person/1/change/ Detected path traversal attempt in '/people/visual/firstname_lastname/filename.jpg' So thats clearly not the way to go, maybe Im missing something? -
Which Python Library is suited to develop an AI chat bot?
I am currently developing a social media website with a lot of privacy settings and processes, which may require the users utilizing the application to need guidance through them smoothly and clearly, and I have been wondering to make an AI chat bot to serve as an assistant to the users, This website is made by Python Django MVC framework, What I am looking for is a python library that is executed like NumPy with C++, Fast performance Python AI library. I would like to know which library is most suitable to perform this task?. Thanks in advance. -
how to connect Django-Rest-Framework to Azure Cosmos DB(MongoDb)
I used these configuration but it is not connecting to azure DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'cloud_db', ---db name 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'db.documents.azure.com', 'port': 443, 'username': 'db', 'password':master_key, 'authSource': 'cloud_db', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } I'm getting this error [2022-02-16T22:28:54.401Z] Result: Failure [2022-02-16T22:28:54.401Z] Exception: ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: [2022-02-16T22:28:54.401Z] 'mysql', 'oracle', 'postgresql', 'sqlite3' Can Anyone Please help me to solve this issue, please help me with the configuration? I have: host:https://db.documents.azure.com:443/ master_key:ACCOUNT_KEY database_id:database id DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': '', 'port':'', 'username': '', 'password':'', 'authSource': '', 'authMechanism': 'SCRAM-SHA-1' }, 'LOGGING': { 'version': 1, 'loggers': { 'djongo': { 'level': 'DEBUG', 'propagate': False, } }, }, } } -
Save data from ChoiceField to database Django
I'm new to Django and I have built a Form that shows a single select field to chose from. The data in the field are calculated on the go by the Form. I now need, once the data is being submitted, to be save on the database. The only problem is that, for some reason, I got an IntegrityError error NOT NULL constraint failed: manager_playlist.user_id Below my view, form and model in Django views.py def playlist(request): if not is_user_already_auth_spotify(request): messages.error(request, "You're not authenticated with Spotify, please authenticate here") return redirect('/members/account/' + request.user.username) if request.method == "POST": form = ChoosePlaylistForm(request.POST, request=request) if form.is_valid(): form.save() messages.success(request, "Playlist successfully chosen") return HttpResponseRedirect('account') else: pass else: form = ChoosePlaylistForm(request=request) return render(request, 'show_playlist.html', {"playlist_choose_form": form}) forms.py class ChoosePlaylistForm(ModelForm): playlists = forms.ChoiceField(choices=()) class Meta: model = Playlist fields = ('playlists',) def __init__(self, *args, request=None, **kwargs): super(ChoosePlaylistForm, self).__init__(*args, **kwargs) self.request = request self.fields['playlists'].choices = self.generate_selection() def generate_selection(self): sp_auth, cache_handler = spotify_oauth2(self.request) spotify = spotipy.Spotify(oauth_manager=sp_auth) s_user = spotify.current_user() u_playlists = spotify.user_playlists(s_user['id'], limit=10) choices = [] for playlist in u_playlists["items"]: if playlist["owner"]["id"] == s_user['id']: playlist_choice = (playlist["id"], playlist["name"]) choices.append(playlist_choice) else: pass return choices model.py## class Playlist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) playlists = models.CharField(max_length=50, null=True, blank=True) # playlists are the … -
Checking if something exists and adding or getting an object from django
I'm scrapping a shop from Woocommerce, and i'd like to take the products brand name, and compare if there's already name like this in the database and if so put the id of it in our base and if not, create an instance of a productProducer for page in range (99, 100): parameters = {'per_page': 1, 'page': f'{page}', 'stock_status': 'instock', 'status': 'publish'} products = wcapi.get("products", params=parameters).json() for product in products: print(product) name = product['name'] slug = product['slug'] description = product['description'] id = product['id'] price = product['price'] link = product['permalink'] for brands in product['images']: brands_name = brands['name'] for image in product['images']: src = image['src'] print(product['categories']) parsed_categories = [] for category in product['categories']: parsed_categories.append(dir[str(category['id'])]) print(parsed_categories) db_product = Product.objects.create(name=name, slug=slug, product_producer_id=1, unique_id=int(id), description=description) db_product.product_category.set(parsed_categories) ProductInStore.objects.create(product=db_product, store_id=1, price=price, currency='PLN', url=link) ProductImage.objects.create(product=db_product, url=src) I have a dir with mapping keys and values for parsing categories outside. Models look like this: class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) filename = models.FileField(upload_to='ecommerce_product_img/', null=True, blank=True) url = models.CharField(max_length=200, null=True,blank=True) class ProductProducer(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) Id like to check if brands_name already exists in productProducer_name and if not, create a new instance of ProductProducer, then also … -
Django updating value in a loop
Please keep in mind, that I just started learning Django and MySQL. I created a script that can read my transactions from my bank statements and added them to a MySQL table which contains the following fields: id,amount,creditordebit,bookingdate ,partner ,category I'm trying to create an interactive site to loop over the newly added data and update the category field based on the transaction type/partner. I want to loop over them one by one and categorize them using forms.ChoiceField. So far I have created the forms.py and the forms.ChoiceField and choices list, but I am having trouble creating a view and template for this. I have tried to use the QuerySet iterate() but I could not get the next item by id, it jumped straight to the last id. Is this even possible with Django only or do I need to also include some JavaScript? Thanks! -
Django Cors Allow Access-Control-Allow-Headers
I'm trying to make a simple API using Django. I have setup a django server, and then on my own html file I send requests using $.getJSON. So far it's been working using the django cors headers package. Now I've been trying to send a request header to my django server, but I'm getting this error in the Chrome console: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/?q=example+query' from origin 'http://localhost:63342' has been blocked by CORS policy: Request header field Example-Header is not allowed by Access-Control-Allow-Headers in preflight response. I'm not sure what's the problem, I have django-cors setup correctly and I am able to make requests, I'm just not allowed to set request headers. Setup: INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:63342" ] <script> $.ajaxSetup({ beforeSend: function(request) { request.setRequestHeader("Example-Header", 'Example-Value'); }, }); $.getJSON("http://127.0.0.1:8000/api/?q=example+query", function (data) { console.log(data); }); </script> @cache_page(60 * 60 * 24 * 7) def ExampleAPI(request): if request.method == 'GET': print(request.headers['Example-Header']) # Print Header Value print(request.GET.get('q')) # Print URL Query Parameter Value return JsonResponse([{"Example-Response": "Example-Response-Value"}], safe=False) So what am I doing wrong? Does django-cors not support this? I tried reading the docs but I could not find anything. Thanks. -
MQL4 WebRequest POST Json to Django API using Django rest framework, getting \x00 at the end of body
I am using Django only for few weeks so there might be some mistakes. I have an API using Django rest framework, which seems to work well. Using postman every thing is ok I send data using WebRequest in Mql4 to the api char data[]; data = {...} int r = WebRequest("POST", "http://127.0.0.1/api/symbol/","Content-Type: application/json",5000, data,res_data, res_headers); The data given to WebRequest is fine but the function add \x00 at the end of body. Here is my post data when it arrive to Django rest framework {'Content-Length': '982', 'Content-Type': 'application/json', 'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*', 'Host': '127.0.0.1', 'Accept-Language': 'fr,en', 'Accept-Charset': '*,utf-8', 'Connection': 'Keep-Alive', 'Proxy-Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'User-Agent': 'MetaTrader 4 Terminal/4.1353 (Windows NT 6.1; x86)'} b'{"name": "GOLDs","date_market": "2022-02-01T00:00:00.000000Z","period": "M1","open_price": 1797.64,"close_price": 1870.91,"low_price": 1788.33,"high_price": 1879.12,"bollinger_band":[{"period":"M1","moving_average_period":20,"standard_deviation":1.5,"high":1936.06829,"low":1717.61271,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2,"high":1972.47755,"low":1681.20345,"moving_average":1826.8405},{"period":"M1","moving_average_period":20,"standard_deviation":2.5,"high":2008.88681,"low":1644.79419,"moving_average":1826.8405}],"moving_average":[{"period":"M1","moving_average_period":50,"type": "0","value":1569.6854},{"period":"M1","moving_average_period":100,"type": "0","value":1399.8002},{"period":"M1","moving_average_period":200,"type": "0","value":1245.38985}],"MACD_zerolag":[{"period":"M1","fast_EMA_period":12,"slow_EMA_period":26,"signal_EMA_period":9,"histogram_value":-0.01794,"signal_value":0.09465,"MACD_value":0.07671}]}\x00' so I get the following error : POST /api/symbol/ - 400 {'Content-Type': 'application/json', 'Vary': 'Accept', 'Allow': 'GET, POST, HEAD, OPTIONS'} b'{"detail":"JSON parse error - Extra data: line 1 column 982 (char 981)"}' if a send the same data removing the \x00 with Postman every thing goes well. Is there a misconfiguration client side with mql4 ? Or can I remove the received data to remove this \x00 ? Here is my models.py … -
Django dropdown select by text
I have a simple django dropdown form. I want to grab the text instead of the value. <select name="doctors" required="" id="id_doctors"> <option value="" selected="">---------</option> <option value="3">some text</option> </select> On selection I want to use the some text in the backend. if 'bookAppointment' in request.POST: print(request.POST['doctors']) this prints out the value 3 is there a way to just get some text out. -
How to change the default error message of username in Django
I wanna change the default error message of username of User in models.py. My simple custom user model is like this. class User(AbstractUser): nickname = models.CharField(max_length=10, unique=True, null=True) image = models.ImageField(upload_to='users/', null=True) I did put the below code in models.py, but it seems it doesn't work. Why is this wrong? User._meta.get_field('username').error_messsages = { 'unique': _('New message'), } -
Django Querset Aggregate on boolean Or
In the Django queryset docs, the following aggregate operation is performed: Book.objects.all().aggregate(Avg('price')) I'm wondering if there's a way to do something similar, but with the or operation. Instead of taking the average on a field with numbers it would take the or of all boolean values for a given attribute -
Initialize search query into a form and submit in Django
I want that anytime someone do a search, I want to initialize the search word into the form and submit into the database. It will be initialed to the voucher field which is a foreign to the voucher model in the registration model class TrackingWarehouse(generic.ListView): model = Voucher context_object_name = 'warehouse_list' template_name = 'warehouse-tracking.html' def get_queryset(self, **kwargs): # new query = self.request.GET.get('q', default='') object_list = Voucher.objects.filter( Q(name__iexact=query) ) return object_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = Registerform(initial={ 'voucher': self.request.GET.get('q', default='') }) return context class RegistrationFormView(generic.CreateView): template_name = 'formnew.html' form_class = Registerform model class Voucher(models.Model): name = models.CharField(max_length=120, null=True, blank=True) class RegistrationForm(models.Model): voucher = models.OneToOneField(Voucher, on_delete=models.CASCADE) year = models.ForeignKey(Year, null=True, blank=True, on_delete=models.CASCADE) choose_certification = models.CharField(max_length=120, choices=OFFERED_COURSES) full_Name = models.CharField(max_length=200,) Date_of_birth = models.CharField(max_length=100) nationality = models.CharField(max_length=120) email = models.EmailField()