Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the 'request' within Class Based View
I'm attempting to subclass the LoginView so that I can change the template_name that is part of LoginView. I've simplified my template_file_name function for the purposes of this example. def template_file_name(request, template_name, page_title): return template_name class CustomLoginView(LoginView): template_name = template_file_name(self.request, 'login.html', "Login") I'm getting this error: NameError: name 'self' is not defined Thanks! -
No 'Access-Control-Allow-Origin' on AWS
I have a Django REST API sitting in AWS ECS, and a VueJS frontend sitting in AWS S3, distributed by AWS CloudFront, trying to reach the backend, using Axios, and I keep getting variations of this error: Access to XMLHttpRequest at 'https://api.example.com/api/v1/auth/login/' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using he Django app django-cors-headers and I have configured it in my settings.py file as, from corsheaders.defaults import default_headers ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # REST 'rest_framework', 'rest_framework.authtoken', # testing 'coverage', # auth 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', # cors 'corsheaders', ... ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'https://example.com', 'https://www.example.com', ) CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = list(default_headers) + ( 'X-CSRFTOKEN', ) CSRF_COOKIE_NAME = "csrftoken" CSRF_TRUSTED_ORIGINS = [ "crowd-scout.com", ] On the frontend side, I've configured Axios as, import axios from 'axios'; export const HTTP = axios.create({ baseURL: "https://api.example.com", withCredentials: true, xsrfHeaderName: "X-CSRFTOKEN", xsrfCookieName: "csrftoken", }) And I'm trying to post data to my Django REST API as, import {HTTP} from '@/common/http' function getToken (form) { … -
Django view not returning HttpResponse Object
Trying to pass a user form for registration, however the view is not returning the user_form object. view def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request, 'account/register.html', {'new_user':new_user}) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form', user_form}) template {% block title%}Create an Account{% endblock %} {%block content%} <h1>Create an Account</h1> <p>Please, sign up using the following form</p> <form method="post"> {{user_form.as_p}} {% csrf_token %} <p><input type="submit" value="Create my account"><p/> </form> {%endblock%} url path('register/',views.register, name='register') error The view account.views.register didn't return an HttpResponse object. It returned None instead. -
the _imagingft c module is not installed amazon linux elasticbeanstalk
I have my app installed on AWS ElasticBeanstalk and it recently started giving me the following error: The _imagingft C module is not installed Traceback: File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/opt/python/run/venv/local/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/opt/python/current/app/grn/views.py", line 256, in get a = ean.save(item['bar'], options=d) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/base.py", line 65, in save output = self.render(options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/codex.py", line 257, in render return Barcode.render(self, options, text) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/base.py", line 105, in render raw = self.writer.render(code) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/writer.py", line 227, in render self._callbacks["paint_text"](xpos, ypos) File "/opt/python/run/venv/local/lib/python3.6/site-packages/barcode/writer.py", line 372, in _paint_text font = ImageFont.truetype(self.font_path, self.font_size * 2) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 855, in truetype return freetype(font) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 852, in freetype return FreeTypeFont(font, size, index, encoding, layout_engine) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 187, in __init__ if core.HAVE_RAQM: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/ImageFont.py", line 44, in … -
How i solve this django project admin operational problem
When I go to project admin, and do some update on the user and save it, it said this, it always like this I have tried it uninstall django and install it again, create the virtualenv again and new project again, and the result is the same, here's the traceback: It said OperationalError at /admin/auth/user/1/change/ no such table: main.auth_user__old Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/user/1/change/ Django Version: 2.0.7 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\user\Dev\trydjango\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 303. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\options.py" in wrapper 575. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\sites.py" in inner 223. return view(request, *args, **kwargs) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\contrib\admin\options.py" in change_view 1557. return self.changeform_view(request, object_id, form_url, extra_context) File "C:\Users\user\Dev\trydjango\lib\site-packages\django\utils\decorators.py" in _wrapper … -
Trouble in getting params pk or id in Django rest framework has_permission
I have trouble in getting the params pk in my url, resources/<int:pk> in the my django rest framework permission. def has_permission(self, request, view): #extract params pk here pass I tried request.POST.get('pk') but it returns nothing. -
Is it possible to return redirect and return render together in django?
I want to refresh the page after returning a render. I can use return redirect to the same page, but I am confused if I can use both return render and return redirect in the same view function. Is there any other way to reload the page other than redirect without affecting the return render? -
Redirect to Admin Panel(Superuser) Login Page from views.py and template in Django
I am trying to keep a link of Django's prebuilds admin pannel on my website. My Project's urls.py: urlpatterns = [ path('', include('diagnosis.urls')), path('admin/', admin.site.urls, name='admin'), ] In Template: <a href="{% url 'admin' %}" class="btn btn-sm btn-primary px-6">Explore Admin Pannel!</a> But it gives errors like: NoReverseMatch at / Reverse for 'admin' not found. 'admin' is not a valid view function or pattern name. How can I fix this? I also tried redirecting to admin in views.py like: if (condition): return redirect('admin') This approach also does not work. How can I redirect in admin pannel from views.py also? -
python3 Django What is the difference
What is the difference BASE_DIR = Path(file).resolve().parent.parent BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) -
How to avoid the user from opening applications in two different tabs in Django
I want to know how can i make the user avoid from opening application from two different tabs , if user opens a new tab without logging out from previous tab or windows i need to show a error i didnt find any solution in django, help is highly appreciated -
I want to update multiple fields at a time in django model form forms
I have tried by filtering with roll number in views.py so I want to update all the marks fields from the form.py module so can anyone suggest me the best way of updating all the marks fields at a time. def marks_view(request, roll_number): return render(request, 'marks_entry.html') modles.py class NurseryResult(models.Model): roll_number = models.PositiveIntegerField(primary_key=True) student_name = models.CharField(max_length=50, blank=False) academic_Year = models.CharField(blank=True, max_length=50) nepali = models.PositiveIntegerField( blank=True) nepali_gpa = models.FloatField( blank=True) nepali_grade = models.CharField( blank=True, max_length=50) english = models.PositiveIntegerField( blank=True) english_gpa = models.FloatField(blank=True) english_grade = models.CharField(blank=True, max_length=25) math = models.PositiveIntegerField(blank=True) math_gpa = models.FloatField(blank=True) math_grade = models.CharField(max_length=50, blank=True) science = models.PositiveIntegerField(blank=True) science_gpa = models.FloatField(blank=True) science_grade = models.CharField(max_length=10, blank=True) oral_nepali = models.PositiveIntegerField(blank=True) oral_nepali_gpa = models.FloatField(blank=True) oral_nepali_grade = models.CharField(max_length=50, blank=True) oral_math = models.PositiveIntegerField(blank=True) oral_math_gpa = models.FloatField(blank=True) oral_math_grade = models.CharField(max_length=50, blank=True) oral_english = models.PositiveIntegerField(blank=True) oral_english_gpa = models.FloatField(blank=True) oral_english_grade = models.CharField(max_length=50, blank=True) hygiene = models.PositiveIntegerField(blank=True) hygiene_gpa = models.FloatField(blank=True) hygiene_grade = models.CharField(max_length=50, blank=True) grade = models.CharField(max_length=10, blank=True) gpa = models.FloatField(blank=True) -
How do I set default image based on gender in django-rest-framework?
I know there are several similar questions here, but none of them seem to resolve my issue. I am using Django-Rest-Framework. I am creating the user-profile simultaneously with the creation of user using signals. As my question is pretty self explanatory, this is my code models.py from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db import models from django.conf import settings from PIL import Image GENDER_SELECTION = ( ('Male', 'Male'), ('Female', 'Female'), ) class CustomUser(AbstractUser): username = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) gender = models.CharField(max_length=20, choices=GENDER_SELECTION) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'gender'] def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') profile_pic = models.ImageField(upload_to='profile/', default='default.png', blank=True) def __str__(self): return f'{self.user.first_name} Profile' def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) uploaded_image = Image.open(self.profile_pic.path) if uploaded_image.height > 300 or uploaded_image.width > 300: output_size = (300, 300) uploaded_image.thumbnail(output_size) uploaded_image.save(self.profile_pic.path) This is what I have tried In models.py # ... def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) if self.profile_pic == 'default.png': if CustomUser.gender == 'Male': self.profile_pic = 'user_default_m.png' return self.profile_pic else: self.profile_pic = 'user_default_f.png' return self.profile_pic else: uploaded_image = Image.open(self.profile_pic.path) if uploaded_image.height > 300 or uploaded_image.width > 300: output_size = (300, 300) uploaded_image.thumbnail(output_size) uploaded_image.save(self.profile_pic.path) -
has_object_permission not working for detail action decorator?
I have an private action decorator for a User View. I want the action to be accessible only for the User in question. # views.py class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = UserSerializer @action(detail=True, permission_classes=[IsSelf]) def private(self, request, pk): user = get_object_or_404(get_user_model(), pk=pk) data = UserPrivateSerializer(user).data return Response(data, status=status=HTTP_200_OK) # permissions.py class IsSelf(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user However, it looks like anyone can go to my private action - even if I explicitly declare IsSelf to be False: class IsSelf(permissions.BasePermission): def has_object_permission(self, request, view, obj): # This has no effect return False What am I missing? -
How to extend djoser create jwt token view
Intro I am using Django rest as my backend api and djoser to handle my authentication system. the goal I want to extend the djoser create jwt token view, to store the jwt token at HttpOnly cookie. Does anyone have an idea how can I do it? Thanks in advance -
Django Rest Framework - Authentication credentials were not provide even with auth header, rest_framework.authtoken
So best I can tell this happened out of nowehere, I just deployed this API and it was working two days ago now that I've come back to it it's not working. I've regenerated fresh tokens, Tried with Curl vs postman and both fail, set cloudflare to dev mode and double checked their documentation (which states headers are pass thru), Verified TokenAuthentication was specified in my auth classes as well as double-checked my AuthenticatedUser default auth level. deleted and regenerated the database to create a fresh superuser I can get a token I just can't do anything past that. Any advice or guidance would be MUCH appreciated. I've checked through the following SO articles already: DRF Token Authentication: { "detail": "Authentication credentials were not provided." } Token Authentication Not Working on Django Rest Framework Authentication credentials were not provided django-rest-auth -
Django TruncHour + annotate Count not inlcuding hours with zero rows
I have a model EventData class EventData(models.Model): id = models.BigAutoField(primary_key=True) created = models.DateTimeField() session = models.ForeignKey(EventSession, on_delete=models.CASCADE) name = models.ForeignKey(EventName, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) value = models.CharField(max_length=200) and a query event_volume = IngestModels.EventData.objects.filter(product=my_product, created__date=selected_date) .annotate(hour=TruncHour('created')) .annotate(event_count=Count('*')) .values("hour", "event_count") that yields results like hour event_count 2021-11-12 00:00:00 2 2021-11-12 01:00:00 2 2021-11-12 02:00:00 7 2021-11-12 05:00:00 5 2021-11-12 06:00:00 9 2021-11-12 09:00:00 10 2021-11-12 10:00:00 1 2021-11-12 12:00:00 9 You'll notice that there are times when no events occurred, so the hour is omitted from the row. I'd really like each hour to be present and 0 in the event_count column if no events occurred. So something like: hour event_count 2021-11-12 00:00:00 2 2021-11-12 01:00:00 2 2021-11-12 02:00:00 7 2021-11-12 03:00:00 0 2021-11-12 04:00:00 0 2021-11-12 05:00:00 5 2021-11-12 06:00:00 9 2021-11-12 07:00:00 0 2021-11-12 08:00:00 0 2021-11-12 09:00:00 10 2021-11-12 10:00:00 1 2021-11-12 11:00:00 0 2021-11-12 12:00:00 9 Any help would be greatly appreciated! I'm using PostgreSQL as my database. -
Django -how to pass value in dynamic url into queryset
I have a dynamic url that will display the same page but with specific data depending on the value that is in the url. I'm trying to set up a View that will return the filtered data based on the value in the url but i don't know how to pass value in the url into the queryset. Views.py: from rest_framework import permissions from .serializers import ProductSerializer,CategorySerializer from .models import Product,Category from rest_framework.response import Response from rest_framework.views import APIView # Create your views here. class ProductViewSet(viewsets.ModelViewSet): queryset=Product.objects.all() serializer_class= ProductSerializer class CategoryViewSet(viewsets.ModelViewSet): queryset=Category.objects.all() serializer_class= CategorySerializer class ProductbyCategory(viewsets.ModelViewSet): categoryid=1 def __init__(self,request,categoryid): self.categoryid=categoryid queryset=Product.objects.filter(categoryid=categoryid) serializer_class= ProductSerializer Urls.py from .views import ProductViewSet,CategoryViewSet,ProductbyCategory from rest_framework import routers from .serializers import ProductSerializer,CategorySerializer from .models import Product,Category router = routers.DefaultRouter() router.register(r'products', ProductViewSet) router.register(r'category', CategoryViewSet) router.register(r'sort-by-category/<int:categoryid>', ProductbyCategory) urlpatterns = [ path('',include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Any help would be greatly appreciated -
ModelChoiceField returns a number instead of its value
I have a simple model for my csv files: class csvModel(models.Model): csvFileName = models.CharField(max_length=50) csvFile = models.FileField(upload_to='tpData/csv/') My script allows a user to upload a file Then, I use a ModelChoiceField that allows a user to select one of the uploaded file: class convertForm(forms.Form): fileToConvert = forms.ModelChoiceField(queryset=csvModel.objects.all(), label="Choose a CSV file to convert") When calling is_valid() I can access the value of the ModelChoiceField (e.g. if my csv file is named test1 I will get test1) def clean_fileToConvert(self): print(self.cleaned_data.get("fileToConvert")) #I get the name of the field (what I want) But when I try to access this value just below the is_valid() , I obtain a number (e.g. 48 for a file, 49 for the following etc.) form2 = convertForm(request.POST) if form2.is_valid(): print(request.POST.get("fileToConvert")) #I get 48 I even tried to return self.cleaned_data.get("fileToConvert") in the clean function but it does not work, I don't know how to access to the selected file name, url etc. -
How to reset a model field when creating a new instance via "Save As New"
Say I have a model w/ attribute special_id, I have the Save As New option enabled for the model's Admin, but when it creates the new instance I need to set special_id = None. What is the best way to achieve this? -
Django template different items for different groups. User authentication and group segregations
So I am trying to make a classroom like website but it is only for a course someone I know is running. I want different groups to have a different view for the website. For example group "Guest" can't see menu items group "Student" can see. But it is not quite working... Here's a bit of my code for the menu: {% if user.is_authenticated %} {% for group in user.groups.all %} {% ifequal group.name 'Student' %} <div class="menu"> <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> <button onclick="location.href='http://10.0.0.60:8000/lessons';" class="home en">Lessons</button> <button onclick="location.href='http://10.0.0.60:8000/assignments';" class="home en">Assignments</button> </div> {% endifequal %} {%ifequal group.name 'Guest'%} <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> {%endifequal%} {%else%} <div class="menu"> <button onclick="location.href='http://10.0.0.60:8000/';" class="home en">Home</button> <button onclick="location.href='http://10.0.0.60:8000/news';" class="news en">News</button> <button onclick="location.href='http://10.0.0.60:8000/about';" class="about en">About us</button> </div> {%endfor%} {%endif%} -
How to refer to all child objects with existing queries in self-referencing foreign key?
I have a model that represents an owner. There is a foreign key on this model to itself to represent a parent entity. There is another model called asset with a foreign key to owner. The purpose of the parent foreign key is to emulate a corporate structure, such that a parent “owns” an Asset whose foreign key is itself or a subsidiary: Class Owner(models.Model): parent = models.ForeignKey( “self”, ) Class Asset(models.Model): owner = models.ForeignKey( Owner, ) Is there a way return all assets owned by a parent and all of its subsidiaries by simply referencing the parent (eg Asset.object.filter(owner=parent))? I know I can create a method to return a queryset of all subsidiaries of a parent, and then filter to all assets in that owner queryset, but I am hoping to avoid a large refactor given the existing code base doesn’t have the concept of a parent owner. My first thought is a custom manager, but I don’t think that will change the behavior of existing queries that are all off the default manager. Can I overload filter on this model? If I need to rethink design that is fine, but I think this approach is cleaner and captures … -
Django REST Framework missing imports with Docker
So, recently I've started creating project using Docker for the first time so my knowledge is not very great. When I'm creating venv using python3 -m venv venv, and installing Rest Framework, everything works fine and I'm not having any problems at all. But in my project with Docker, I have no idea why but PyLance detects missing imports with Django and Django REST. It is really annoying, also when I'm making imports from Django, it makes suggestions: But it won't suggest anything when making imports from REST Does anyone know how to fix this issue? I've tried: Opening VSC in different directories Rebuliding Docker image Everything works fine, my requirements file contains REST Framework therefore it works fine. It is all about theese non-sense missing modules. -
Unable to Deploy Django App to Heroku because of PyWin32
So I have gone through the forums in search for an answer but haven't found one that works for me. I am using Windows machine and my Django application works on Localhost but when I try to deploy the same application to Heroku it gives me this error. INFO: pip is looking at multiple versions of anyio to determine which version is compatible with other requirements. This could take a while. remote: ERROR: Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions: none) remote: ERROR: No matching distribution found for pywin32>=223 remote: ! Push rejected, failed to compile Python app. I have removed pywin32 from the requirements.txt file but still when I run the git push heroku master command, I keep getting the same error. I have also tried to copy all my source code into a new folder and deleted the initial git file and re-initialized Git but still nothing seems to be working. Forum Articles I have read that did not help include: Could not find a version that satisfies the requirement pywin32==227 heroku Heroku fails to install pywin32 library Allow me to attach my full error log: Enumerating objects: 268, done. Counting … -
How do I populate my form with the data sent by a user after a GET request in Django?
def index(request): if len(request.GET) == 0: form = FlightSearchForm() else: arr = request.GET.get('arrival_airport') dep = request.GET.get('departure_airport') form = FlightSearchForm({'departure_airport': dep,'arrival_airport': arr}) return render(request, 'app1/index.html', {'form': form}) What I want to do is create a form that would allow users to search for a flight, so I need them to use GET request. The problem is I don't know how to make their search appear in the fields after they go to their specific url (with all the details they searched for). It worked with a POST request in the past, but obviously I can't use it in this case. class FlightSearchForm(forms.Form): def __init__(self, *args, **kwargs): self.departure_airport = kwargs.pop('departure_airport') self.arrival_airport = kwargs.pop('arrival_airport') super.__init__(*args, **kwargs) departure_airport = forms.CharField(max_length=100) arrival_airport = forms.CharField(max_length=100) I tried something like that but it didn't help. Now it shouts that there is a keyerror, which doesn't exist. What can I do about this? -
Django ORM with PostgreSQL return wrong data using icontains
My model is class Seller(models.Model): supplierId = models.IntegerField('Supplier ID', primary_key=True) supplierName = models.CharField('Поставщик', max_length=255, null=True, blank=True) inn = models.CharField('ИНН', max_length=255, null=True, blank=True) ogrn = models.CharField('ОГРН', max_length=255, null=True, blank=True) legalAddress = models.CharField('Юридический адрес', max_length=512, null=True, blank=True) I have 2 records with the same supplierName='Смирнова Ольга Александровна'. sellers = Seller.objects.filter(supplierName__icontains='Смирнова Ольга Александровна') print(sellers.count()) # return 1 sellers = Seller.objects.filter(supplierName__contains='Смирнова Ольга Александровна') print(sellers.count()) # return 2 sellers = Seller.objects.filter(supplierName='Смирнова Ольга Александровна') print(sellers.count()) # return 2 I also try to use supplierName__search, but it returns not normal data too. icontains return wrong data not only in this example. What can i do with it? I need this for correct search on my site.