Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webpack Getting Variables
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Django Webpack template</title> </head> <body> <div id="root"></div> <p id="message">Template Data</p> <script id="templateDataScript" type="application/json"> {{ template_data|safe }} </script> <script src="{% static 'data.bundle.js' %}"></script> </body> </html> This seems to work file when I run it locally... However, if I Webpack this and use my bundle file online it does not recognize the Django template_data. Trying to find out is it possible to somehow incorporate my variables and data into the Webpack itself. Just searching for any insight. -
Django, how can I follow a http redirect?
I have 2 different views that seem to work on their own. But when I try to use them together with a http redirect then that fails. The context is pretty straightforward, I have a view that creates an object and another view that updates this object, both with the same form. The only thing that is a bit different is that we use multiple sites. So we check if the site that wants to update the object is the site that created it. If yes then it does a normal update of the object. If no (that's the part that does not work here) then I http redirect the update view to the create view and I pass along the object so the new site can create a new object based on those initial values. Here is the test to create a new resource (passes successfully) : @pytest.mark.resource_create @pytest.mark.django_db def test_create_new_resource_and_redirect(client): data = { "title": "a title", "subtitle": "a sub title", "status": 0, "summary": "a summary", "tags": "#tag", "content": "this is some updated content", } with login(client, groups=["example_com_staff"]): response = client.post(reverse("resources-resource-create"), data=data) resource = models.Resource.on_site.all()[0] assert resource.content == data["content"] assert response.status_code == 302 Here is the test to create … -
Prefetching complex query that does a Union
I'm trying to prefetch a related object to optimize performance. The code I'm trying to Prefetch is this; class Product(models.Model): ... def get_attribute_values(self): # ToDo: Implement this prefetch. if hasattr(self, "_prefetched_attribute_values"): return self._prefetched_attribute_values if not self.pk: return self.attribute_values.model.objects.none() attribute_values = self.attribute_values.all() if self.is_child: parent_attribute_values = self.parent.attribute_values.exclude( attribute__code__in=attribute_values.values("attribute__code") ) return attribute_values | parent_attribute_values return attribute_values What this does is the following; Get all attribute_values of itself, attribute_values is a related model ProductAttributeValue If it's a child, also get the parent attribute_values, but exclude attribute_values with attribute__codes that are already present in the child attribute_values result Do a union that combines them together. Currently, I have this prefetch; Prefetch( "attribute_values", queryset=ProductAttributeValueModel.objects.select_related( "attribute", "value_option" ) ), This works for the non child scenario, but unfortunately, there are a lot of child products and thus the performance isn't as great. So ideally, I can prefetch the combined attributes to '_prefetched_attribute_values', though I would be fine with doing two prefetches as well; For the product itself For the parent, but still needs to exclude attributes that the child itself had I have tried doing it with a Subquery & OuterRef, but no luck yet. -
How to wrap a search function in a class that inherits from wagtail Page?
Is there a way to make a search form using a wagtail template inheriting from Page? Instead of using a simple view. And how can I render it in the template? I find it more enriching to be able to use the wagtail page attributes to better style the search page, add more fields and make it translatable into multiple languages using for example wagtail localyze. class SearchPage(Page): # Database fields heading = models.CharField(default="Search", max_length=60) intro = models.CharField(default="Search Page", max_length=275) placeholder = models.CharField(default="Enter your search", max_length=100) results_text = models.CharField(default="Search results for", max_length=100) cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Editor panels configuration content_panels = Page.content_panels + [ FieldPanel('cover_image'), FieldPanel('heading'), FieldPanel('intro'), FieldPanel('placeholder'), FieldPanel('results_text'), ] def search(self, request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) active_lang = Locale.get_active() # Search if search_query: search_results = Page.objects.filter(locale_id=active_lang.id, live=True).search(search_query) # To log this query for use with the "Promoted search results" module: # query = Query.get(search_query) # query.add_hit() else: search_results = Page.objects.none() # Pagination paginator = Paginator(search_results, 10) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return TemplateResponse( request, "search/search_page.html", { "search_query": search_query, "search_results": search_results, }, ) My layout.html file: {% block content %} {% … -
Django IntegrityError: Foreign key constraint violation on token_blacklist_outstandingtoken
I'm encountering an IntegrityError when trying to log in to my Django application. The error suggests a foreign key constraint violation. Here are the details: Error Message django.db.utils.IntegrityError: insert or update on table "token_blacklist_outstandingtoken" violates foreign key constraint "token_blacklist_outs_user_id_83bc629a_fk_auth_user" DETAIL: Key (user_id)=(5) is not present in table "auth_user". Context This error occurs when a user attempts to log in. The POST request to /auth/login/ returns a 500 status code. Date and time of the error: [07/Sep/2024 11:08:11] Relevant Code [Include any relevant code snippets here, such as your login view or authentication configuration] Question What could be causing this foreign key constraint violation? How can I resolve this issue and allow users to log in successfully? Any insights or suggestions would be greatly appreciated. Thank you! -
Django + JS : value with double curly braces not sent to a JS function. Others are OK
A mystery hits me ! I display with a loop many shipping services available for a given order on a page containing all my orders. {% for serv in account.services %} <div class="service"> <label class="form-check-label" for="service{{order.pk}}"><small>{{serv}}</small></label> {% if forloop.first %} <input class="form-check-input" type="radio" name="service{{order.pk}}" value="{{serv.pk}}" ismulti="{{serv.is_multiparcel}}" checked> {% else %} <input class="form-check-input" type="radio" name="service{{order.pk}}" value="{{serv.pk}}" ismulti="{{serv.is_multiparcel}}"> {% endif %} {% if order.base_subtotal > serv.insurance_from %} <div class=" form-text text-danger insur-alert{{order.pk}}">Assur. appliquée car € HT sup. à {{serv.insurance_from}}</div> {% endif %} {% if order.weight > serv.max_weight %} <div class="form-text badge bg-danger" name="weight-alert">Poids commande > max. service {{serv.max_weight}} kg</div> <script> disableCheckCauseWeight("service{{ order.pk }}", "{{serv.pk}}"); </script> {% endif %} </div> {% endfor %} One of these services can be selected with a radio button and is identified by 2 prameters : service{{order.pk}} and {{serv.pk}}. Both of them are well displaying in my html code: Later in my code, for each loop, I call a JS function for disabling the given service if the order's weight is higher than the weight accepted by the service. But, {{serv.pk}} isn't sent to disableCheckCauseWeight()function, despite it's well displayed above in value="{{serv.pk}}". A console log shows well service{{order.pk}} but not {{serv.pk}}. I tried with other values like {{order.pk}}or … -
what are the steps to setup visual Studio?
How the map() function works in Python. Can someone explain with a simple example?" I was going through different topics and functions of python but then I was wondering how does map() function work, I want to understand it with simple example!! -
Populating an SQLite database from Markdown files in Django
I'm starting to learn Django and Python to migrate my website, and I'm trying to wrap my head around getting an SQLite database set up and populated. All the tutorials I see show you how to do this using the admin application and using the web UI to add posts manually, but I want Django to find the Markdown files in my folder structure and pull the info from those Markdown files and populate the database with that data. This topic (Populating a SQLite3 database from a .txt file with Python) seems to be in the direction I'm heading, but 1) it's old, and 2) it involves a CSV file. (Does this need to be in CSV? Would JSON work just as well or better, especially since I have a JSON feed on the site and will need to eventually populate a JSON file anyways?) Otherwise, I've found topics about importing files from folders to populate the database, but those tips are for Python in general, and I wasn't sure if Django had specific tools to do this kind of thing just as well or better. What's a good way to set up Django to populate an SQLite database from … -
Django REST Framework MultiPartParser parsing JSON as string
I am making a django functional based view where the request contains some JSON and a file. Using DRF's MultiPartParser is parsing the JSON section of the request as a string. what can I do to fix this? here is the view: from rest_framework.response import Response from rest_framework.request import Request from rest_framework.parsers import MultiPartParser @api_view(['POST']) @parser_classes([MultiPartParser]) def import_files(request: Request) -> Response: data = request.data print(type(data['json'])) return Response("Success", status=200) and here is the client request using python requests: import requests import json multipart_payload = [ ('json', (None, json.dumps(payload), 'application/json')), ('file', ('test.xlsx', open('test.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) ] put_response = requests.post(endpoint + "feature/", files=multipart_payload) print(put_response.json()) I have tried adding JSONParser to the @parser_classes decorator but it didn't work. if anyone had a similar issue any help would be great thanks -
how filter options with another select value on django admin forms
i have Address,city,state models with oneToOne relation and im trying filter citys by state when i want to add new address so the problem is i can see all citys for any state and i have no idea how to fix that. any idea? models class State(models.Model): state_name = models.CharField(max_length=50) def __str__(self) -> str: return self.state_name class City(models.Model): cityـname = models.CharField(max_length=50) state = models.ForeignKey(to=State,on_delete=models.CASCADE) def __str__(self) -> str: return self.cityـname class Adrress(models.Model): user = models.ForeignKey(to=User,on_delete=models.CASCADE) city = models.ForeignKey(to=City,on_delete=models.CASCADE) description = models.TextField() def __str__(self) -> str: return self.description admin @admin.register(State) class StateAdmin(admin.ModelAdmin): pass @admin.register(City) class CityAdmin(admin.ModelAdmin): pass @admin.register(Adrress) class AdrressAdmin(admin.ModelAdmin): pass so i expect when i want to add new address see form like this and on state change in city drop down only city for that state be visible The way I tried using custom form so i change code like this in admin and make custom widget and Jquery admin @admin.register(Adrress) class AdrressAdmin(admin.ModelAdmin): form = AdrressAdminForm forms class RelatedChoieField(forms.widgets.Select): def __init__(self, attrs=None, choices=()): super().__init__(attrs,choices) self.data = {} for obj in City.objects.all(): if not obj.state in self.data.keys(): self.data[obj.state.state_name] = [obj.cityـname] else: self.data[obj.state.state_name].append(obj.cityـname) def render(self, name, value, attrs=None, renderer=None): html = super().render(name, value, attrs) inline_code = mark_safe( f"<script>obj ={dumps(self.data,indent=4)};$(\"#id_state\").change(()=>{{$(\"#id_city\").innerHTML=\"\";for(var i=0;i<obj[$(\"#id_state\").find(\":selected\").text()].length;i++){{$(\"#id_city\").innerHTML+=$(\"<option></option>\").innerHTML=obj[$(\"#id_state\").find(\":selected\").text()][i]}} }})</script>" … -
Problems for send a file attachment using Django-Q
I'm testing Django-Q to improve my project, which involves sending study certificates. However, I'm encountering an issue. The log shows the following error: File "C:\Python311\Lib\multiprocessing\queues.py", line 244, in _feed obj = _ForkingPickler.dumps(obj) File "C:\Python311\Lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) TypeError: cannot pickle '_thread.RLock' object When this error appears, it starts an infinite loop that sends emails with the attached file about the certificates. I suspect that I've made a mistake somewhere, so any help would be greatly appreciated! Here is the code in my tasks.py: from django.core.mail import EmailMessage from django_q.tasks import async_task def send_email_task(subject, message, recipient_list, attachments=None): """ Sends an email asynchronously. """ email = EmailMessage(subject, message, 'victorgabrieljunior@gmail.com', recipient_list) if attachments: for attachment in attachments: email.attach(*attachment) async_task(email.send, fail_silently=False) Here my admin.py: def generate_pdf(self, request, queryset): constancia_id = queryset.values_list('id', flat=True)[0] response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="constancia.pdf"' #Code for the content in the file # Call the function from tasks.py send_email_task( "Constancia de Estudios", f'Hola {primer_nombre} {primer_apellido}, tu solicitud de constancia de estudio ha sido exitosa. ' 'Por favor revisa el archivo adjunto para obtener tu constancia de estudio', [correo], attachments=[(f'constancia_{primer_nombre}_{primer_apellido}.pdf', response.getvalue(), 'application/pdf')] ) self.message_user(request, "Constancia generada y enviada por correo exitosamente.") return response generate_pdf.short_description = "Descarga los items … -
How to apply gevent monkey patch using django-admin with huey?
I have a django app that uses huey. I want to enable the greenlet worker type for the huey consumer. Running django-admin run_huey logs this message and tasks do not run. I managed to run the huey consumer successfully with the greenlet worker type by using the manage.py and apply the monkey patching there as documented here Is it possible to achieve the same with django-admin? Do I have to create a custom manage command that applies monkey patching before the huey consumer runs? -
Django - How to use in app a profile picture after getting UID and Access_token of an user from Facebook
I successfully made a connection between my app and facebook, but I don't know how to pass ID and access_token from "User Social Auth: extra data" into User model. I tried by modifying default Django User model, by creating another model and passing user = OneToOneField, but I don't know how to pass ID and access_token. Here is my code so far: (I changed keys into "######" for security measures) Settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&ab$_bmjpvh56kv@2#tyg*_yl&ja7f&$t!4^twuo7k1+%%k%u3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base', 'social_django', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'sportowyczluchow.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', ], }, }, ] WSGI_APPLICATION = 'sportowyczluchow.wsgi.application' # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { … -
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