Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change the default value of a field on a bound form that gets rendered in Django?
In a Django project we have forms that have already been submitted where for some reason the person before me set the default value of a field to be one blank space (' ') and this is affecting some other functionality where we need to copy data (not relevant to go into detail for this question I don't think) Anyway, here is a snippet from models.py where I changed the default value to '': #inside class Meta base64_encoded_activation_key = models.CharField (max_length = 1000, default = '', blank = True, verbose_name = 'Activation Key') Inside views.py def edit_activation(request, id=None): ...... activation = get_object_or_404(ActivationRecord, pk=id) ....... ....... ....... else: # GET request form = ActivationRecordForm(instance=activation) Now, this works fine if I create and submit a new form, but when I go back to an old form then the value is still ' ' (which I guess is expected as the form has been submitted) but I don't know how to fix this to the new default value. -
django the request argument must be an instance of django.http.HttpRequest
I'm importing a service function from django views function and getting this error 'The `request` argument must be an instance of `django.http.HttpRequest`, not `collections.OrderedDict`.' I have used the same implementation in other modules too and those are working fine. from custom_label.services.custom_label_svc import update_label @api_view(["POST"]) @authorize def update_label(request) -> JsonResponse: try: payload = ValidateUpdateLabel(data=request.data) if payload.is_valid(): # call service methods data = update_label(payload.validated_data) << here ... In custom_label > services > custom_label_svc.py file: from basic_files.database_connections import connect_to_postges cursor = connect_to_postges() def update_label(params: dict) -> dict: app_id = params.get('appid') label_name = params.get('label_name') updated_label_icon = params.get('updated_label_icon') sql = "UPDATE label SET icon = %s WHERE appId = %s AND name = %s" % (updated_label_icon, app_id, label_name) cursor.execute(sql) return cursor.rowcount What am I missing here? -
how to filter number of posts per page in Django python
This is views.py file paginator = Paginator( product_list, 5 ) show_on_page = request.GET.get('show_on_page', 5) product_item_list = paginator.get_page(show_on_page) and this is my templates file <div class="show-on-page"> <label class="product-sort-label" for="show-on-page">Tonen op pagina:</label> <select name="show-on-page" id="show-on-page"> <option value="5" selected>5</option> <option value="10">10</option> <option value="20">20</option> </select> I want to add random navigation like when you select 5 from dropdown 5 posts should be displayed per page if 10 it selects 10 posts. Can anyone help me with this? -
How to get queryset i need?
i have 2 models class Task(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='tasks', ) category = models.ForeignKey( to='TaskCategory', on_delete=models.CASCADE, related_name='tasks', blank=True, null=True, ) difficult = models.DecimalField( max_digits=10, decimal_places=2, validators=(MinValueValidator(Decimal('0.01')),), ) class TaskCategory(models.Model): user = models.ForeignKey( to='users.User', on_delete=models.CASCADE, related_name='task_categories', ) name = models.CharField( max_length=255, ) i want to get this query(get top 3 category of most difficults sum and next one to sum of anothers): [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Anothers", "category_sum": "2000.00" } ] i make this queryset, but i dont know how make queryset i want: Task.objects.values('category__name').annotate( category_sum=Coalesce( Sum('difficult'), 0, output_field=DecimalField() ) ).filter( category__isnull=False ).order_by('-category_sum') [ { "category__name": "Food", "category_sum": "12477.00" }, { "category__name": "Shopping", "category_sum": "3214.00" }, { "category__name": "Movie", "category_sum": "2590.00" }, { "category__name": "Sport", "category_sum": "1000.00" } { "category__name": "Home", "category_sum": "1000.00" } ] -
Check overlapping reservation
I am developing a Reservation System in Django. I have a booking model, and in views the logic to make new booking and also to edit bookings. The logic in creating new bookings works perfectly but I am having problems when editing it. Basically, what I need to achieve is: If I edit my reservation but I don't change any data, I want the form to be saved If I edit my reservation and I change some data, I want the form to be saved ONLY if it doesn't overlap with any other reservation. I post some code: models.py class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) renter = models.ForeignKey( Renter, on_delete=models.CASCADE, blank=True, null=True) booking_date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() uid = models.CharField(max_length=200, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) The uid field I created is a sort of logic to have a kind of Unique ID of the reservation in order to check if anything changed when I edit the booking. views.py if request.method == "POST": aircraft = request.POST.get('aircraft') student = request.POST.get('student') instructor = request.POST.get('instructor') renter = request.POST.get('renter') date = request.POST.get('date') start_time = … -
How to add/update objects using serializers in the Django Rest Framework?
I am using Django Rest Framework so that my other Django project can change records in this project's database, and am using serializers to do so. I am using the .save() method, which will add to the database only if none of the existing records share the same primary key as the ones being saved. I would like to "update" these existing records, either by updating them straight or deleting them then creating them again. This is my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import parcelSerialiser @api_view(['POST']) def addItem(request): serializer = parcelSerialiser(data=request.data, many = True) print(request.data) print(serializer.is_valid()) print(serializer.errors) if serializer.is_valid(): serializer.save() return Response(serializer.data) and my serializers.py: from rest_framework import serializers from mainMenu.checkIn.models import Parcels class parcelSerialiser(serializers.ModelSerializer): class Meta: model = Parcels fields = '__all__' -
Code in Django is not working. The form in html does not open the output when clicking on submit
I am working on a simple project where I want to read a pdf using a form in html and then display the contents of the pdf on another page in form of a dictionary key value format. This is the code I have so far. The problem is that when I click on the submit button not even the else condition is executing and nothing happens. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pdf Reader</title> </head> <body> <form enctype='multipart/form-data' action='/analyze' method='POST'> <div class="input-group"> <input type="file" name="inp" class="form-control" id="inputGroupFile04" aria-describedby="inputGroupFileAddon04" aria-label="Upload"> <button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Submit</button> </div> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render import PyPDF2 from io import StringIO def index(request): return render(request,'index.html') def analyze(request): if request.method == "GET": #txt = request.FILES['inp'].read() # get the uploaded file pdfFileObj = open(request.FILES['inp'].read(), 'rb') # pdfFileObj = open((request.GET.get('inp.pdf')),'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pageObj = pdfReader.getPage(0) content = pageObj.extractText() buf = StringIO(content) l = buf.readlines() while '\n' in l: l.remove('\n') i = 0 while i < len(l): for j in range(len(l[i])): if l[i][j:j + 2] == '\n': l[i] = l[i][:-1] j += 1 i += 1 d = {} i = 0 while i < (len(l)): if ":" … -
DJango can't execute an empty query
Im not so familiar with sql command, my sql command comes from csv file and it's all good. Im using multi database in django but I got an error : django.db.utils.ProgrammingError: can't execute an empty query. I also tried this solution but not working can't execute an empty query . Please help me on this.Thank You! Here's my csv file: Name sql James SELECT value AS id from test WHERE name ='James' AND age ='10' AND grade ='80' Ice SELECT value AS id from test WHERE name ='Ice' AND age ='14' AND grade ='85' Mike SELECT value AS id from test WHERE name ='Mike' AND age ='11' AND grade ='88' and more and more query here........ def filter(request): field = {"James","Mike"} number={3265826,61894965} df = pd.read_csv('/pathtofile/grade.csv') for name in field: data = df[df['Name'] == name] sql = data['sql'].values[0] query = sql + ' AND Number =' + "'"+ number +"'" sqldata = test.objects.using("database2").raw(query) cursor = connection.cursor() cursor.execute(sqldata) row = cursor.fetchall() -
PyJWT cant find module with import jwt
after the installation of the PyJWT 2.4.0 i can't import the module jwt it shows me "Import could not be resolved import jwt import datetime from django.conf import settings def generate_access_token(user): payload = { 'user_id':user.id, 'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat' : datetime.datetime.utcnow() } return jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') -
passing session in forms.py in django
I'm working on django project, in which I'm using model as form to generate an image upload page. The problem is there's a foreign key referring to user's profile table which fetches a list of users in a drop down menu. I figured i need to use the session value from logged in user but so far I haven't been able to pass the session through forms. Of course, I've tried couple of solutions found on similar questions but those options didn't work for me here's the code: forms : class ImageForm(forms.ModelForm): class Meta: model = ImageMedia fields = ['id', 'Image', 'ImageTitle', 'ImageContext', 'Uploader'] labels = {'Image' : 'Select Image', 'Image Context' : 'Image Context'} Models : class ImageMedia(models.Model): id = models.AutoField(primary_key = True) Image = models.ImageField(verbose_name="Image Name", upload_to = "ImageSet") UploadDate = models.DateTimeField(verbose_name="Date and time uploaded", auto_now_add=True) Uploader = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=False) ImageTitle = models.CharField(verbose_name="Image Title", null=False, max_length=100) ImageContext = models.CharField(verbose_name="Image Context", max_length=500, null=True) def __str__(self): return self.ImageTitle upload template <body> <div class="container"> <center><div class="card" style="width: 28rem;"> <div class="py-5 text-center bg-secondary text-white"> <div class="card-header"> <h1 class="mb-3">Upload Image</h1> </div> <form name="UploadForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% comment %} {{form.Image}} {{form.ImageTitle}} {{form.Uploader.as_hidden}} {{form.ImageContext}} {% endcomment %} {{form.as_p}} <input type="submit" id="submit" … -
Best way to convert Django ORM query to GraphQL
So I have this webapp, that the frontend side allows the user to build dashboards which in-turn create a GraphQL query. This query is sent the the Backend (Django) and all the backend does is route this request to some external DB that handles the GraphQL and returns a response. The issue: I have a complex logic in the backend, that knows how to create a Django ORM query (Q) per each request, which I would like to combine with the GraphQL query. Basically im trying to convert a Django Q (django.db.models.query_utils.Q) into a GraphQL filter section. Is there a way to do it? Maybe with a different generic lang than GraphQL? or Do I have to resort to write something myself -
Submitting Bulk Forms In Django
I have 5 different forms in forms.py; the forms are all based off of 1 model. The 5 forms are all displayed on the same html page, so as to allow the user to create or register 5 objects into the DB with 1 single button click. In the future, I might need to submit 50 forms in a single click. If I were to do this based on the existing code, I would probably need 50 forms in forms.py and repeat the registration logic in views.py for 50 times. Is there a more efficient way to do this? views.py def register(request): form1 = DetailsForm1() form2 = DetailsForm2() form3 = DetailsForm3() form4 = DetailsForm4() form5 = DetailsForm5() if request.method == "POST": form1 = DetailsForm1(request.POST) if form1.is_valid(): form1.save() form2 = DetailsForm2(request.POST) if form2.is_valid(): form2.save() form3 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form4 = DetailsForm3(request.POST) if form3.is_valid(): form3.save() form5 = DetailsForm5(request.POST) if form5.is_valid(): form5.save() return render(request, "app/registration_completed.html") context = { "form1": form1, "form2": form2, "form3": form3, "form4": form4, "form5": form5 } return render(request, "app/register.html", context) forms.py class DetailsForm1(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', ) class DetailsForm2(forms.ModelForm): class Meta: model = Property fields = ( 'owner', 'address', 'postcode', … -
Web API that itself sends data to client on availability
I am currently working with Django but I am stuck as I don't know if I am pursuing the right model given the nature of my application. Problem Statement: I have to make a REST API for a client such that whenever I get a trigger for a new entry/entries in my Database I have to send those to the client which is supposed to listen to a URL and has asked for data only once and now is open to receive data whenever available to him. It is not sending a GET request now and then. There will be different endpoints of the APIs. One is where I provide him all the new data available to me and in other where it asks for specific data (ex: '/myAPI/givemethis') I can easily implement the second requirement as it is a simple request-response case. I am not sure how to send him data that too on availability without him making a repeated request as client. It appears a Publisher-Subscriber model is better suited for my use case but I don't know how to implement it on Django. I bumped into several concepts like StreamingServices and MQTT but I am not sure … -
Django statics returns 404 error in cPanel Passenger
I used cPanel and deployed a Django application on my server using passenger_wsgi.py. The problem is when I'm trying to access static files (like admin CSS file: static/admin/css/base.css) I'm facing with 404 error. I've already done collectstatic and added PassengerPathInfoFix method to passenger_wsgi.py file but the output log is Not Found: /home/mysite/public_html/static/admin/css/base.css even though the outputted path exists and I can edit it using vim. My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any help would be appreciated. -
Django rest framework URL pattern of CRUD operation in single GenericAPIView class
I have been creating a class view with GenericAPIView in the Django rest framework. and define their URLs but on Django swagger, every URL shows all methods. #views.py class AmenitiesView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView): serializer_class = AmenitiesSerializer queryset = Amenities.objects.all() def get(self, request, *args, **kwargs): many, queryset = True, self.filter_queryset(self.get_queryset()) if 'pk' in kwargs and kwargs['pk']: many, queryset = False, self.get_object() serializer = self.get_serializer(queryset, many=many) return Response({"data": serializer.data, "message": "Successfully Get Amenities", "isSuccess": True, "status": 200}, status=200) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) #urls.py urlpatterns = [ path('amenities/get/', AmenitiesView.as_view()), path('amenities/get/<int:pk>/', AmenitiesView.as_view()), path('amenities/create/', AmenitiesView.as_view()), path('amenities/edit/<int:pk>/', AmenitiesView.as_view()), path('amenities/delete/<int:pk>/', AmenitiesView.as_view()), ] how to define URL with the method, like if 'amenities/get/' is URL so on swagger will show only get method and if URL is 'amenities/create/' so only post method shown on this url. -
subprocess.call() doesn't throw and error when file is not found
I'm trying to run a python script from a Django web service and I'm using the subprocess.call() method and I've put it in a try except block because I need to get the error when something is wrong. I discovered that when the path to the script is not valid is not raising an error it's only displaying it on the console, but I need it to be thrown so I can catch it in the except block. Here is my code. try: row = exec_SQL(f"SELECT [ID], [ProjectPath], [MainFileName] FROM [dbo].[WebserviceInfo] WHERE ProjectName='{project}'") command = f'python {row[1]}\{row[2]} {model} {scenario}' subprocess.call(command, shell=True) except Exception as e: error_message = str(e) This is the path to the file + some arguments that I need. f'python {row[1]}\{row[2]} {model} {scenario} Thanks in advance for your help. -
App runs locally but crashes when deployed to Heroku
My Python Flask app runs locally but when I deploy it to Heroku it successfully builds but crashes when opening the app. I'm relatively comfortable with Python but new to web dev and Heroku etc. Here's my Procfile web: gunicorn app:app From my limited understanding my Procfile is correct(?) as it's telling Heroku to run my app.py file which is what I run when running the app locally. Logs 2022-07-14T09:08:18.969324+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/werkzeug/serving.py", line 740, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: HTTPServer.__init__(self, server_address, handler) 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 452, in __init__ 2022-07-14T09:08:18.969325+00:00 app[web.1]: self.server_bind() 2022-07-14T09:08:18.969325+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/http/server.py", line 136, in server_bind 2022-07-14T09:08:18.969325+00:00 app[web.1]: socketserver.TCPServer.server_bind(self) 2022-07-14T09:08:18.969326+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/socketserver.py", line 466, in server_bind 2022-07-14T09:08:18.969326+00:00 app[web.1]: self.socket.bind(self.server_address) 2022-07-14T09:08:18.969326+00:00 app[web.1]: OSError: [Errno 98] Address already in use 2022-07-14T09:08:18.969552+00:00 app[web.1]: [2022-07-14 09:08:18 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-07-14T09:08:33.000000+00:00 app[api]: Build succeeded 2022-07-14T09:08:49.139858+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Shutting down: Master 2022-07-14T09:08:49.139897+00:00 app[web.1]: [2022-07-14 09:08:49 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-07-14T09:08:49.288295+00:00 heroku[web.1]: Process exited with status 3 2022-07-14T09:08:49.375710+00:00 heroku[web.1]: State changed from up to crashed 2022-07-14T09:08:49.378964+00:00 heroku[web.1]: State changed from crashed to starting 2022-07-14T09:08:59.395728+00:00 heroku[web.1]: Starting process with command `gunicorn app:app` 2022-07-14T09:09:00.585739+00:00 app[web.1]: [2022-07-14 09:09:00 +0000] [4] [INFO] Starting … -
Django Rest Framework Custom Permission not taking effect
I have a permissions.py file that holds a custom permission called CanViewUserRecord. I have assigned this to a viewset called UserRecordView. The permission isn't working though, whenever I call the endpoint attached to the viewset all of the data from the database is returned. Here is the custom permission code: from accounts.models import Staff class CanViewUserRecord(permissions.BasePermission): edit_methods = ("PUT", "PATCH") def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if obj.account_type == "staff": # If user is the manager of staff if obj.staff.manager == request.user.id: return True # If the user is the owner if obj == request.user: return True # Allow admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "manager": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False elif obj.account_type == "admin": # If the user is the owner if obj == request.user: return True # Allow Admins to access if request.user.account_type == "admin": return True return False else: return False elif request.method in self.edit_methods: if obj.account_type == "staff": if ( request.user.account_type == "manager" or request.user.account_type == "admin" ): return True else: return False elif … -
Blog API with DRF getting Anonymous User Error
I am creating a BlogAPI with LoginAPI(using dj-rest-auth). I have created a model for my Post- models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): content = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) Then I have made 2 serializers User and Post - serializers.py from rest_framework import serializers from django.contrib.auth.models import User from .models import Post class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'id', 'email'] class PostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Post fields = ['user', 'content'] My view looks like this- views.py from rest_framework import viewsets, permissions from .serializers import UserSerializer, PostSerializer, CommentSerializer from . import models from rest_framework.response import Response from rest_framework.decorators import action, api_view, permission_classes class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer class PostViewSet(viewsets.ModelViewSet): queryset = models.Post.objects.all() serializer_class = PostSerializer permission_classes = [permissions.AllowAny] def create(self, request): serializer = PostSerializer( data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) print(request.data) print(request.user) serializer.save(user=request.user) return Response(serializer.data) I have kept the permissions_class as AllowAny because then I was not able to test the API. urls.py(inside app) router = routers.DefaultRouter() router.register(r'^users', views.UserViewSet) router.register(r'^posts', views.PostViewSet) urlpatterns = [ path('', include(router.urls)), re_path(r'^posts/(?P<pk>\d+)/comments/$', view=views.PostViewSet.as_view({'get': 'comments', 'post': 'comments'})), re_path(r'^posts/(?P<pk>\d+)/comments/(?P<comment>\d+)/$', view=views.PostViewSet.as_view({'delete': 'remove_comment'})) ] After running it on locahost on http://127.0.0.1:8000/posts/ I am able to do … -
Check if the data in json file exit in django models
I want to check if the data in json file exit in django models table For example: In models.py table called activity in that table different fields are there Such as activity_name , activity_status I want to check the activity names in json file exit or not If exit print true or if not false Plese help me -
How to solve celery 'Not Registered' Exception
dev env django = 3.2.4 celery = 5.2.3 redis I use Celery to asynchronously process. I'm using it for email transmission and AI Inference functions, but @sharedtask applied to email works well without any problems. However, the AI Inference function is different. Once successful and then the same action is performed, the 'Not registered' Exception is displayed. Why does this happen? The success and failure of the same task are shown below. enter image description here -
Got an unexpected keyword argument 'pzn'
I'm struggling with following problem: fachbereich_detailview() got an unexpected keyword argument 'pzn' The error tells me that there is something wrong with my urls. If I change the last part of the url to int:test, it tells me that the unexpected keyword argument is test. The query 'product = Products.objects.get(pzn="existingpzn")' is working fine (Tested with shell). view.py: [...] def fachbereich_detailview(request, pzn): context = {} try: product = Products.objects.get(pzn=pzn) except: return redirect('fachbereich') context['product'] = product return render(request, 'app/LoginArea/fachbereich_detailview.html', context) [...] urls.py: [...] path('Produkt/<int:pzn>/', views.fachbereich_detailview, name='fachbereich_detailview'), [...] html: <a href="{% url 'fachbereich_detailview' product.pzn %}" class="small-text text-underline text-uppercase">Mehr erfahren</a> I just can't figure out what the problem is. I hope that someone is able to help me! Thank you in advance Nader -
When to use Django instead of Streamlit
We are devloping various web applications for design and optimization of energy infrastructure. We have been working in Django for some time now. I just became aware of Streamlit. I believe it is pretty easy to use. So my question: Why would you use Django instead of Streamlit? Streamlit seems much less complicated. Thanks. -
hello. I'm learning django. I downloaded small project from git hub and problem is intalling requrement.txt
how can i install requirement.txt? created project with different virtual environment(pipenv and venv) but in the end Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\User\AppData\Local\Temp\pip-install-x_oh84s8\django-localized-names_d98dfe1d2720418d895d5cf15016e5dd\setup.py", line 17, in <module> long_description=read('README.rst'), File "C:\Users\User\AppData\Local\Temp\pip-install-x_oh84s8\django-localized-names_d98dfe1d2720418d895d5cf15016e5dd\setup.py", line 8, in read return open(os.path.join(os.path.dirname(__file__), fname)).read() File "C:\Python39\lib\encodings\cp1251.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 2468: character maps to <undefined> [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. how can I fix it please? -
Combining javascript search with dropdown filter
I have a working code with a live javascript search where I can search in a table for a user by either their first and last name or one of them. I also have a working dropdown filter, where you can choose a rank, which will only show the users with that specific rank. The problem is, they don't combine --> If I do a search and then select the rank, it shows all users with that rank, and it doesn't use the search. It also doesn't work the other way. Does anyone have an idea how I can combine the two filters? I work in Django, so my java and HTML are on the same page. I left out the sort function because it's not relevant for my question. Here a pic of how it looks: How it looks right now HTML: {% extends 'puma_core/layouts/navbar.html' %} {% load static %} {% block content %} <div class="container mt-5"> <div class="mb-4"> <div> <div class="row"> <div class="col-8"> <h1> Gebruikers {{ peloton }} </h1> </div> <div class="col position-relative mt-sm-2 me-3"> <a class="btn btn-secondary btn-sm position-absolute end-0" href="{% url 'peloton' peloton.id %}" role="button"> Terug </a> </div> </div> </div> </div> <input id="userInput" placeholder="Zoek een gebruiker..." …