Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django / Keycloak / KeycloakOpenID / Login to my Django app with Keycloak
I am trying to connect my Django app to Keycloak and retrieve a token through the Keycloak API. I have tested the process first using Postman, and everything works perfectly; I receive a 200 status code. However, when I try to implement this in my Django app, I only get a 200 status code if I use hardcoded variables. When I attempt to use variables passed from a POST form, I receive a 401 Unauthorized error. What am I doing wrong? Postman everything works perfectly; I receive a 200 status code. POSTMAN REQUEST Python Django code : def get_token(self, username: str, password: str): # username = "admin@exemple.com" # password = "admin" try: token = self.get_keycloak_oidc().token( username=username, password=password, grant_type="password", ) self.token = token log.error("Successfully obtained token.") return self.token except KeycloakAuthenticationError as e: log.error(f"Failed to authenticate: {e}") return None def get_keycloak_oidc(self) -> KeycloakOpenID: if not self._keycloak_oidc: self._init_keycloak_oidc() return self._keycloak_oidc def _init_keycloak_oidc(self): self._keycloak_oidc = KeycloakOpenID( server_url=self.url, client_id=self.client_id, realm_name=self.realm, client_secret_key=self.client_secret, ) HARDCODED = 200 STATUS PARAMS = 401 STATUS (there are both the same) Error : 401: b'{"error":"invalid_grant","error_description":"Invalid user credentials"}' -
Django Cron Job Error: "[Errno 98] Address Already in Use" When Using Spotify API with django-crontab
I am working on a Django project where I use a cron job to manage Spotify playlists using the Spotify API. The cron job is scheduled with django-crontab and is intended to add tracks to multiple Spotify playlists across different accounts. Problem: The cron job works fine up to a certain point, but I encounter the following error repeatedly: ERROR 2024-09-06 01:11:02,768 cron Error adding tracks: [Errno 98] Address already in use ERROR 2024-09-06 01:11:07,771 cron Error adding tracks: [Errno 98] Address already in use ERROR 2024-09-06 01:11:12,774 cron Error adding tracks: [Errno 98] Address already in use What I have tried: Environment: I am using Ubuntu with Django, django-crontab, and Spotipy (a Python client for the Spotify Web API). Error Analysis: The error occurs after a log statement indicating that a user ID is being used to add tracks to a playlist. The next try block does not execute, and the [Errno 98] Address already in use error is raised. Port Conflict Check: I initially thought the error might be due to port conflicts with the Django server running on port 8000, but I understand that my Django server is expected to run on this port, so checking for … -
Error: Unknown metric function: 'function'. While trying to get cached loaded model (Keras Instance model)
Error: retrieving model '' from cache: Unknown metric function: 'function'. Please ensure you are using a keras.utils.custom_object_scope and that this object is included in the scope. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. Getting rows of Multiple ML Model, and loaded model storing in Redis models = MLModel.objects.all() for model_entry in models: try: model_title = model_entry.title model_name = model_entry.name model_url = model_entry.file.url lock_name = f"lock:model:{model_title}" with redis_lock(lock_name) as acquired: if not acquired: logger.info(f"Skipping model {model_name}, another worker is already loading it.") continue logger.info(f"Loading model: {model_name} from URL: {model_url}") local_model_path = os.path.join(models_directory, f"{model_name}.h5") logger.info(f"Local file path: {local_model_path}") download_file(model_url, local_model_path) loss_type = model_entry.loss_type loss_code = model_entry.loss loss_function = load_loss(loss_type, loss_code) model = tf.keras.models.load_model(local_model_path, custom_objects={loss_type: loss_function}) list_of_words = model_entry.list_of_words ml_utils_code = model_entry.ml_utils model_details = { 'name': model_name, 'model': model, 'list_of_words': list_of_words, 'ml_utils_code': ml_utils_code, 'loss_type': loss_type, 'loss_code': loss_code } cache_key = f"model:{model_title}" redis_client.set(cache_key, pickle.dumps(model_details)) logger.info(f"Model {model_name} loaded and stored in cache with key: {model_title}.") except Exception as e: logger.error(f"Error loading model {model_entry.name}: {e}") logger.info("All models loaded and stored in Redis cache.") Now while getting particular loaded model from redis it gives error import logging logger = logging.getLogger(__name__) redis_client = redis.StrictRedis.from_url(settings.REDIS_URL) def get_loaded_model(title): try: model_data = redis_client.get(f"model:{title}") if model_data: model_details = pickle.loads(model_data) ml_utils_code = model_details['ml_utils_code'] ml_utils = load_ml_utils(ml_utils_code) … -
auto generating thumbnails from images with pillow and bytesIO i django
Ive been trying to automatically generate thubmnails from images that i upload to the admin console in django(i'm using drf). i want to be able to generate thumbnails for images that i upload when creating new objects. def get_event_thumb(self): if self.event_thumb: return "http://127.0.0.1:8000" + self.event_thumb.url else: if self.event_img: self.event_thumb = self.make_thumbnail(self.event_img) self.save() return "http://127.0.0.1:8000" + self.event_thumb.url else: '' def get_event_img(self): if self.event_img: return "http://127.0.0.1:8000" + self.event_img.url else: '' def make_thumbnail(self, image, size=(300, 200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail this is what i've written in the models.py file. it's not showing me any errors at the moment, just not generating the thumbnails. -
Django on IIS with FastCGI: HTTP Error 500.19 - Internal Server Error (Config Error 0x8007000d)
I'm trying to host a Django application on IIS using FastCGI. I've followed the steps to set up IIS with FastCGI and the wfastcgi.py handler for Django. However, I keep encountering an HTTP Error 500.19 - Internal Server Error with error code 0x8007000d. The error message doesn't give much detail, except for stating that "the related configuration data for the page is invalid" and that there might be an issue with the web.config file. Below is the content of my web.config file: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <!-- FastCGI Handler Configuration for Django --> <handlers> <add name="FastCGIHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\administrator.MERITMILL\AppData\Local\Programs\Python\Python312\python.exe|C:\Users\administrator.MERITMILL\AppData\Local\Programs\Python\Python312\Lib\site-packages\wfastcgi.py" resourceType="File" requireAccess="Script" /> </handlers> <staticContent> <mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf" /> </staticContent> <httpErrors errorMode="Detailed" existingResponse="PassThrough" /> <directoryBrowse enabled="false" /> <tracing> <traceFailedRequestsLogging enabled="true" directory="C:\inetpub\logs\FailedReqLogFiles" /> </tracing> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\materials" /> <add key="DJANGO_SETTINGS_MODULE" value="material_management.settings" /> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application" /> </appSettings> </configuration> Hhere’s what I’ve done so far: Installed FastCGI and WFastCGI: Followed the installation process and verified the wfastcgi.py handler is correctly located and mapped in IIS. Set up FastCGI handler in web.config: Configured it to point to my Python312 executable and the wfastcgi.py handler file. Web.config Configuration: I've ensured the paths are correct and that there are no duplicate entries … -
Should I create more than one field with `document=True` and `user_template=True` for every model inside `search_indexes.py`?
So I have a general Haystack question here. They (haystack.readthedocs) say not to use document=True in the model you use in search_indexes.py file more than once. My question is, suppose I have 3 models that I will put into search_indexes.py, does that indicate that I have to have 3 fields with documenet=True and template=True in this file? If not, then does this mean that document=True and user_template=True can only be once regardless of the number of models? Here is the code for my search_indexes.py: from .models import ArboristCompany, ServicesType class ArboristCompany(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) company_name = indexes.CharField(model_attr='company_name') class ServicesType(indexes.SearchIndex, indexes.Indexable):``` I would like to add more fields with `document=True` and `user_template=True` for my other models in `search_indexes.py`, but kind of nervous about breaking something later on with my project involving this. -
Django Template Not Rendering Dictionary
I have two microservices. One encodes user data and sends it to the other, which decodes it and renders it. The decoded data is in a Dictionary format but can't seem to be rendered Microservice One This microservice is used to encode user data using b64encode after which the data is sent to the other service to decode and process The HttpResponse from Microservice two shows that the data was received def encode_token_data(user): payload = { 'username': user.username, 'is_superuser': user.is_superuser } json_data = json.dumps(payload) encoded_token = base64.urlsafe_b64encode(json_data.encode()).decode().rstrip("=") return encoded_token @api_view(['POST']) def login_user(request): username = request.data.get('username') password = request.data.get('password') # print(f"Received login request with username: {username}") user = authenticate(request, username=username, password=password) if user is not None: # print(f"User authenticated: {username}") auth_login(request, user) encoded_token = encode_token_data(user) # print(f"Token generated: {encoded_token}") payload = { 'token': encoded_token } receive_token_url = 'http://shared_assets:8002/receive_token/' # print(f"Sending token to: {receive_token_url}") try: response = requests.post( receive_token_url, data=json.dumps(payload), headers={'Content-Type': 'application/json'} ) print(f"Response from receive_token endpoint: Status code {response.status_code}, Response body {response.text}") if response.status_code == 200: return Response({ 'status': 'success', 'message': 'Login successful! Redirecting to Dashboard...', 'token': encoded_token }, status=status.HTTP_200_OK) else: return Response({ 'status': 'error', 'message': f'Failed to send token to the other project. Status code: {response.status_code}. Message: {response.text}' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) … -
Openlitespeed Django one click without php
I just moved to Openlitespeed Django, and I have my repo ready to be cloned, I have implemented Daphne to work smoothly with ASGI. The question is that: Can I use litespeed server without php? Openlitespeed Django one click is the fastest way to create a Django app, but for someone like me has the app ready and want to use Openlitespeed as a best alternative to Nginx and apache, I have setup everything I want and everything works smoothly, no access logs to view, no error logs to view, except for the 503 error service unavailable, and then i dig deeper into this, and found out that litespeed server is either waiting for php to be running or it's already built to work with php environment and Django will be under that environment. Again I have tried to check all the logs, access, error, debug, any clue, and nothing special, the only thing is that 503 service unavailable, Of course I have created a Daphne service file and I let Daphne to create a sock file for openlitespeed to communicate with. And all the permissions are set correctly, I tested how can openlitespeed user "nobody" can access that sock … -
How to upgrade django version of a project?
My project is running on Django 1.10 version. And I am using postgres as my DB. As Postgres has newer versions and older version is depricated, AWS is charging more for database support. So, I have to update Postgres version 16. As Django 1.10 does not have support for Postgres 16. I am planning to upgrade to Django 4.2 LTS. How can I upgrade my Django and what things should I consider (change functions or models etc.) after I install the 4.2 version of Django? -
How do i customize the django-allauth elements tag
I have install the django-allauth latest version which come in with custom element templatetags meant to be overriding with their respective tag, text but having below error when i follow the documentation for custom styling. i need a guideline on how to resolve the above error -
What to use when building a website in 2024? [closed]
What technologies should I consider using in 2024 to build a music-selling platform on top of Django? I've previously built a simple website using Django, HTML, JavaScript, SQLite, and CSS. Now, I’m planning a more advanced project: a music-selling platform. While I’m comfortable with the basics, I’m wondering what additional technologies I should explore in 2024 to enhance my project. Here are some specific areas where I’m looking for advice: Frontend frameworks: I’ve heard of tools like Next.js and Bootstrap, but I’m unsure whether they would significantly improve my project. Database: I used SQLite in my last project, but should I consider moving to PostgreSQL or another database for better performance and scalability? Authentication: I’ve previously implemented Django Allauth, but I’m curious if it remains a strong choice for authentication in 2024. Payment integration: What are the recommended tools for securely handling payment processing for digital goods like music? Performance and scalability: Any tips for improving the platform’s performance and scaling it effectively as it grows? Other tools or technologies: Are there any other useful libraries or technologies I should look into, especially for e-commerce functionality or media handling? I’d appreciate any suggestions on what additional tools, frameworks, or best … -
0 I converted my python file into .exe file
0 I converted my python file into .exe file. Before converting into .exe file it gives full output but after creating into .exe file it is not giving full output can anyone help me resolve this issue? it is like if i click that file it should connect the opc server and fetch the data and insert it into the database but while executing the python code it's working but if I click the .exe file after converting it is not working.. pip install pyinstaller pyinstaller --onefile opc.py pyinstaller --hiddenimport win32timezone -F opc.py -
I am not able to Overriding django model
I have a django model that has multiple fields class data(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) pj = ArrayField(models.IntegerField(), null=True, blank=True) name = models.CharField(max_length=225) explain = models.TextField(max_length=50, null=True) def save(self, *args, **kwargs): self.name=f"new {name}" super(data, self).save(*args, **kwargs) when i save the data model the name is not getting changed to "new name" it is getting saved as "name" I want the new naming convention to reflect. -
Need example of pytest test upload file to graphql
I am trying to run pytest and upload a file to my /graphql endpoint. I have read the official doc, but it does not cover my question. Then I tried ask chatbot. The answer contains error. It raises the error from server is not running. I have experience test uploading the file with djangoREST. I don't need to run an actual server during the test. Therefore I think gql will do the same thing. query mutation ExcelUploadFile($file: Upload!, $orderType: String!, $saleOrg: String!, $uploadType: UploadType!, $distributionChannel: String!, $division: String!) { uploadExcel( file: $file orderType: $orderType saleOrg: $saleOrg uploadType: $uploadType distributionChannel: $distributionChannel division: $division ) { status rows errors { field code message __typename } __typename } } variables { "file": null, "orderType": "ZP30", "saleOrg": "0254", "uploadType": "GROUP", "distributionChannel": "10", "division": "00" } Here is my pytest code. from io import BytesIO import openpyxl import pytest import requests from django.core.files.uploadedfile import InMemoryUploadedFile from requests_toolbelt.multipart.encoder import MultipartEncoder from scgp_po_upload.implementations.excel_upload import validate_excel_upload_file from scgp_po_upload.tests.fixtures import client_query # URL of your GraphQL endpoint GRAPHQL_ENDPOINT = "http://localhost:8000/graphql/" # Mutation query UPLOAD_MUTATION = """ mutation ExcelUploadFile($file: Upload!, $orderType: String!, $saleOrg: String!, $uploadType: UploadType!, $distributionChannel: String!, $division: String!) { uploadExcel( file: $file orderType: $orderType saleOrg: $saleOrg uploadType: $uploadType … -
Need to update Drop down used in HTML + Django
I have developed Django web application and in that I have used drop down field using the code: <select id="countrynamew" name="countrynamew" value="{{countrynamew}}"> <option value="Abkhazia">Abkhazia</option> <option value="Afghanistan">Afghanistan</option> <option value="Albania">Albania</option> <option value="Algeria">Algeria</option> </select> How can I able to assign the selected value from Python code. And I have tried the code: countrynamew = 'Abkhazia' out = ('countrynamew': countrynamew) return render(request, 'xxx.html', out ) But, it does not assigns the value and how can I assign the value? Please suggest -
Django CSRF error with request on multiple tabs simultaneously
I am working on a Django project and have encountered an issue with CSRF tokens when rendering a page with a form. To reproduce the issue, I added a 5-second delay when rendering the page. Here is the scenario: I open the URL with the form in the first browser tab. Within 5 seconds, I open the same URL in a second tab, ensuring that the first request hasn't yet completed. As a result, the first tab generates a csrftoken, and the second tab overrides it. However, the csrfmiddlewaretoken in the form on the first tab remains bound to the old csrftoken. When I submit the form from the first tab, a CSRF error occurs due to the mismatch. Could you please help to fix this issue? Thanks in advance! -
Automatically create a free trial Stripe checkout
We use Stripe for our checkout and have a free trial enabled. So when a user comes to the site to enable the free trial they just enter their email in the checkout. What I would like is to tie the start of the free trial with creating an account on my site. Since I get the user's email with account creation I would like to create the free trial programmatically and remove that step. Is that possible? Here is my code to create the checkout session. def create_checkout_session(request, app_type): subscription_plan_duration = SubscriptionPlanDuration.objects.filter().first() user_subscription = UserSubscription.objects.create( subscription_plan_duration_id = subscription_plan_duration.id, user_id = request.user.id, app_type = app_type, is_active = False #True - change for 3. ) discount_coupon = DiscountCoupon.objects.filter(subscription_plan_duration_id = subscription_plan_duration.id).first() checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': subscription_plan_duration.price_id, 'quantity': 1, }, ], metadata={ "user_subscription_id": user_subscription.id }, mode="subscription", # discounts=[{ # 'coupon': discount_coupon.coupon_id, # }], subscription_data={ "trial_period_days": 30, "trial_settings": { "end_behavior": { "missing_payment_method": "cancel" } } }, payment_method_collection="if_required", allow_promotion_codes=True, success_url=settings.APP_END_POINT + '/stripe/success', cancel_url=settings.APP_END_POINT + '/stripe/cancel-subscription/' + app_type ) return redirect(checkout_session.url) -
Heroku Postgres not working on Heroku Server [Django]
I have a Django project, where I am using Redis/Celery to call some API's. I've set up my settings.py file to connect to the Postgres database and when running the Django project locally (with Redis/Celery running locally) the data is stored in the database no problem. When I push the application to Heroku, the data doesn't save to the database. I'm not sure if this sounds like a problem with the code itself, or the settings of the server causing this (Redis/Celery on Heroku). I am using a Heroku Postgres Database. Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': 5432, } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) # The URL of the broker for celery to use CELERY_BROKER_URL = os.getenv('REDIS_URL', 'redis://localhost:6379/0') # The URL of the backend you want to use in case you wish to store the result of a task CELERY_RESULT_BACKEND = os.getenv('REDIS_URL', 'redis://localhost:6379/0') # The tasks you need to schedule CELERY_BEAT_SCHEDULE = { 'add_data': { 'task': 'comparasion.tasks.add_data_util', # Name of task 'schedule': 60.0 # Time in seconds } } Also the procfile: release: python manage.py migrate web: gunicorn Soccer.wsgi --log-file - worker: celery -A Soccer worker --loglevel=info beat: celery … -
request.session['some_variable'] TypeError: Object of type Decimal is not JSON serializable
I´m updating some code from Django 1.8 and python 2.7 to django 5.0 and python 3.11, in the old version in some functions are make session variables that store decimal values and after that make a redirect like this: request.sessions['decimal_var'] = 1.00 return HttpResponseRedirect('/somepage/') This works fine in the old version so the 'decimal_var' can be used in the redirected page, but in the new version (Django 5.0) if I pass any session variable with decimal value gives me this error: File "C:\Python311\Lib\json\__init__.py", line 238, in dumps **kw).encode(obj) ^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 200, in encode chunks = self.iterencode(o, _one_shot=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 258, in iterencode return _iterencode(o, 0) ^^^^^^^^^^^^^^^^^ File "C:\Python311\Lib\json\encoder.py", line 180, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Decimal is not JSON serializable One option is just pass int or string values, but i think this is not a real solution and why the new versions can´t manage the decimal values and the old can, this could bring more problems if is a need to use decimal values. Is there a way to manage the decimal values in the session variables? -
Django Axes works, but doesn't store Access attempts nor failures
I apologize in advance, I am new to all of this (Stack, Django and Axes). I am creating a simple website where you can create users, and I implemented django axes. It works in a sense that it locks you out after failed attempts based on username and IP. It even logs them in Admin panel under Axes' own "Access logs". But the "Access attempts" and "Access failures" are empty. Below is my users/views.py code and under it is users/urls.py: @axes_dispatch def login(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': form = UserLoginForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) messages.success(request, f'Welcome back, {username}!') return redirect('home') # successful login redirect else: # signal for failed attempt signals.user_login_failed.send( sender=user.__class__, request=request, credentials={'username': username} ) messages.error(request, 'Invalid username or password.') else: # signal for invalid signals.user_login_failed.send( sender=None, request=request, credentials={'username': request.POST.get('username')} ) messages.error(request, 'Invalid username or password.') else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form}) Here is the users urls.py: urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('register/', views.register, name='register'), path('change_profile/', views.profile, name='change_profile'), path('change_password/', views.change_password, name='change_password'), path('lockout/', views.lockout, name='lockout'), ] -
Reverse for 'topics' not found. 'topics' is not a valid view function or pattern name
<p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %}{% endblock content %} I get that error: Reverse for 'topics' not found. 'topics' is not a valid view function or pattern name. at this line: <a href="{% url 'learning_logs:topics' %}">Topics</a> Here I creat views: from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """Main page for app Learning Logs""" return render(request, 'learning_logs/index.html') # A view of topics def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic':topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) Here is a template of topics: {% extends "learning_logs/base.html" %} {% block content %} <p> Topics </p> <ul> <!--this is a for loop which iterates through topics--> {% for topic in topics %} <li> <a href = "{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topic has been added yet</li> </ul> {% endblock content %} I am new to Django and I don't understand why this problem appeared. -
Making map with markers and popups
I want to show a map in the frontend with some markers on it. Also I want to write an event for every marker so when you click, you see a popup. Is that possible with javascript? How? Wich library I have to use? Thanks! -
Separate Django API and Django regular templates views
I'm starting a project which will have a website and a mobile app. I want these two to use the same backend, which I'll code in Django, specifically django-ninja. For the website front-end, I want to use Django also as I'm familiar with it already and I feel it suits my needs for this project. The question is: should I create 2 separate Django projects, one dedicated to the API, and one dedicated to the "Front-end", or have them both in the same project? -
Problem django-autocomplete-light! new version chrome
I have a django application with python 3.7 and Django 2.2.10, which uses django admin, with the materialize css subscript for the templates. From the latest Chrome updates, the behavior of forms in modal is showing a rendering problem. A widget was customized to fit the forms: class Select2Widget(Select2WidgetMixin): def _get_language_code(self): return 'pt-BR' @property def media(self): """Return JS/CSS resources for the widget.""" return forms.Media( js=( 'autocomplete_light/jquery.init.js', STATIC_URL + 'js/select2.full.js', # 'vendor/select2/dist/js/select2.full.js', 'autocomplete_light/autocomplete.init.js', 'autocomplete_light/forward.js', 'autocomplete_light/select2.js', 'autocomplete_light/jquery.post-setup.js', ), css={ 'screen': ( 'vendor/select2/dist/css/select2.min.css', 'admin/css/autocomplete.css', 'autocomplete_light/select2.css', ), }, ) autocomplete_function = 'select2' """ retorna queryset na ordem que foi selecionado no field """ class QuerySetSelect(WidgetMixin): def filter_choices_to_render(self, selected_choices): preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(selected_choices)]) """Filter out un-selected choices if choices is a QuerySet.""" self.choices.queryset = self.choices.queryset.filter(pk__in=[c for c in selected_choices if c]).order_by(preserved) class ModelSelect2(QuerySetSelectMixin, Select2Widget, forms.Select): ... class ModelSelect2Multiple(QuerySetSelectMixin, Select2Widget, forms.SelectMultiple): ... class Select2Multiple(Select2Widget, SelectMultiple): ... Use below in forms class PessoaForm(ModelForm): ativo = forms.BooleanField(required=False) cpf_cnpj = BRCPFCNPJField(label='CPF/CNPJ', max_length=14) logradouro = forms.ModelChoiceField(queryset=Logradouro.objects, required=False, label='CEP', widget=ModelSelect2(url='logradouro_autocomplete', attrs={'data-placeholder': 'Informe o CEP', 'style': 'width: 100%;', 'data-minimum-input-length': 8, 'class':'material-ignore', 'material-ignore': True}),) municipio = forms.ModelChoiceField(queryset=Municipio.objects, label='Município', required=False, widget=ModelSelect2(url='logradouro_municipio_autocomplete', forward=['logradouro'], attrs={'style': 'width: 100%;', 'data-placeholder': 'Selecione', 'class': 'material-ignore', 'material-ignore': True })) local_emissao_cnh = forms.ModelChoiceField(queryset=Municipio.objects, label='Municipio Emissão da CNH', … -
ConnectionError:Socket connection error ssl wrap: [WinError 10054] An existing connection was forcibly closed by the host
from django.shortcuts import render, redirect from django.contrib import messages from django.core.management import call_command from ldap3 import Server, Connection, ALL from .forms import LDAPConfigForm from .models import LDAPConfig def ldap_config_view(request): if request.method == 'POST': form = LDAPConfigForm(request.POST) if form.is_valid(): server = Server(form.cleaned_data['server'],get_info=ALL) connection = Connection( server, user=form.cleaned_data['user_dn'], password=form.cleaned_data['password'], authentication="SIMPLE" ) print(connection.result) # Test LDAP connection # server = Server(config.server, get_info=ALL) # connection = Connection(server, user=config.user_dn, password=config.password, authentication="SIMPLE") print(connection) try: if connection.bind(): LDAPConfig.objects.all().delete() config = form.save() # Run sync_ldap command call_command('sync_ldap') messages.success(request, 'Connection successful!') return redirect('ldap_config') else: messages.error(request, 'Connection failed!') except Exception as e: messages.error(request, f'Connection error: {e}') else: messages.error(request, 'Invalid form data!') else: form = LDAPConfigForm() return render(request, 'ldap_sync/ldap_config_form.html', {'form': form})' In this code I am trying to connect the LDAP sever to my Django project with ldap3 package while I try to connect to the server I got the Error as ConnectionError:Socket connection error ssl wrap: [WinError 10054] An existing connection was forcibly closed by the host. Actually I am using the Hyper v virtual machine in my local machine to create the AD DS server. I have tried with the OpenLdap server from https://www.forumsys.com/2022/05/10/online-ldap-test-server/ While I try with this site credentials I am able to fetch the users in …