Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crispy Form {% crispy form %} does not show errors while {{ form|crispy }} does not work with FormHelper
How do I get both layout helper and display error messages working in crispy forms. I created a simple form just one field to upload a file. # forms.py class FileUploadForm(forms.Form): file = forms.FileField(label='File', validators=[FileExtensionValidator(allowed_extensions=ALLOWED_EXTENSIONS)]) def __init__(self, *args, **kwargs): print ("==== FileUploadForm:__init__ ====") super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.form_style = 'inline' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Field('file', css_class='form-control-sm') # Apply Bootstrap's small form-control ) I noticed the layout helper works when using {% crispy form %}. However it will not show errors such as when I leave the input blank or upload an invalid file extension. {% crispy form %} example If I used {{ form|crispy }}, the layout helper does not work but the errors are displayed. {{ form|crispy }} example Relevant information django-crispy-forms==2.1 Django==5.0.6 crispy-bootstrap5==2024.2 Python 3.12.5 # html <!-- Bootstrap 5.3.3 --> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <!-- Javascript Bootstrap --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script> # settings.py INSTALLED_APPS = [ 'crispy_forms', # package: crispy form for bootstrap 'crispy_bootstrap5', # bootstrap 5 ] CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" -
Database constraint on latitude and longitude of a PointField with MySQL backend
I have a following Django model: class Place(models.Model): location = models.PointField(geography=True) The location field seems to happily accept any arbitrary number for latitude and longitude. Even past the limits of +-180 and +-90. My research says this is due to SRID not being set in the database column, even though the database was generated by Django. I do belive the MySQL backend just does not support properly setting the SRID on database level. To prevent any issues from arising, I'm trying to write constraints on the field. However, I do not seem to be able to generate a working constraint object. Perfect outcome would be checking the lat & lng are in range of the PointField object's extent field, but I'd be happy to settle for a hardcoded limits also. Alternatively, a solution to make the database respect the proper lat & lng limitations without any extra Django constraints would be greatly appreciated. I've tried many iterations of something like this. I have not found a combination that would make both python and MySQL happy. class GeometryPointFunc(Func): template = "%(function)s(%(expressions)s::geometry)" def __init__(self, expression: any) -> None: super().__init__(expression, output_field=FloatField()) class Latitude(GeometryPointFunc): function = "ST_Y" class Longitude(GeometryPointFunc): function = "ST_X" ... class … -
Django Channels direct messages over channels
I have a basic setup where a user connects to server I save the channel_name into DB. And later on I try to send the message to connected users. class CommandConsumer(WebsocketConsumer): def connect(self): Client.objects.create(user=self.scope['user'],channel_name=self.channel_name) self.accept() def disconnect(self, close_code): # Leave room group #self.channel_layer.group_discard(self.room_group_name, self.channel_name) Client.objects.filter(channel_name=self.channel_name).delete() # Receive message from WebSocket def receive(self, text_data): destination_clients=Client.objects.filter(user_id__in=userstatuse_userids) print(destination_clients) /****self.send(text_data=json.dumps({"type": "chat.message","command":command,"request":request,"response":clubs_data})) This line works as message is sent to the owner of that channel, the person who sent the message *****// for each_user in destination_clients: /*this line however does not send the message to anyone*/ self.channel_layer.send(each_user.channel_name, {"type": "chat.message","text":"test"}) def chat_message(self, event): # Send message to WebSocket print("Chat message") self.send(text_data=json.dumps(event)) I have checked the channel names by printing them out and they match so I am not sending to wrong channels. chat message function is never called. does the whole consumer have to be async ? I do not want to implement this using groups. Their website has an example but I could not get it to work. https://channels.readthedocs.io/en/stable/topics/channel_layers.html -
Cannot Upload File to One Drive via Python
I have tried to upload file to one drive by using python code: Please my upload script below for reference: url = f'https://graph.microsoft.com/v1.0/users/{user_id}/drive/root:/{local_file_path}:/createUploadSession' headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json' } session_data = { "item": { "@microsoft.graph.conflictBehavior": "replace", # Action on conflict (replace, fail, etc.) "name": "2.txt" # The file name in OneDrive } } upload_session = requests.post(url=url, headers=headers,json=session_data).json() Error Message: {"error": {"code": "Request_BadRequest", "message": "Specified HTTP method is not allowed for the request target.", "innerError": {"date": "2024-11-07T04:21:05", "request-id": "7be5355c-381a-4ea8-9d89-0b0a99208bb4", "client-request-id": "7be5355c-381a-4ea8-9d89-0b0a99208bb4"}}} -
How to create a Foreign Key for a table for a table that is not part of SQLAlchemy ORM?
I'm trying to have a FK to a table that is managed by Django ORM however SQLA Doesn't seem to like it. class SomeSAModel(DeclarativeBase): user_id: Mapped[int] = mapped_column( sa.ForeignKey("users_customuser.id") # this is a reference to a Django table ) And this is the error I get when I run alembic revision --autogenerate File "/home/dev/Desktop/t5hob/Backend/alembic/env.py", line 137, in run_migrations_online context.run_migrations() File "<string>", line 8, in run_migrations File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/runtime/environment.py", line 946, in run_migrations self.get_context().run_migrations(**kw) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/runtime/migration.py", line 616, in run_migrations for step in self._migrations_fn(heads, self): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/command.py", line 212, in retrieve_migrations revision_context.run_autogenerate(rev, context) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 570, in run_autogenerate self._run_environment(rev, migration_context, True) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 617, in _run_environment compare._populate_migration_script( File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 65, in _populate_migration_script _produce_net_changes(autogen_context, upgrade_ops) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 98, in _produce_net_changes comparators.dispatch("schema", autogen_context.dialect.name)( File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/util/langhelpers.py", line 310, in go fn(*arg, **kw) File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/compare.py", line 134, in _autogen_for_tables [(table.schema, table.name) for table in autogen_context.sorted_tables] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py", line 1141, in __get__ obj.__dict__[self.__name__] = result = self.fget(obj) ^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/alembic/autogenerate/api.py", line 482, in sorted_tables result.extend(m.sorted_tables) ^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 5626, in sorted_tables return ddl.sort_tables( ^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py", line 1252, in sort_tables for (t, fkcs) in sort_tables_and_constraints( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/ddl.py", line 1328, in sort_tables_and_constraints dependent_on = fkc.referred_table ^^^^^^^^^^^^^^^^^^ File "/home/dev/Desktop/t5hob/Backend/.venv/lib/python3.12/site-packages/sqlalchemy/sql/schema.py", line 4753, … -
How to make a Django `url` case insensitive?
For example, if I visit http://localhost:8000/detail/PayPal I get a Page not found error 404 with the following message: Using the URLconf ... Django tried these URL patterns, in this order: ... detail/<slug:slug> [name='processor_detail'] The current path, detail/PayPal, matched the last one. Here is my code: views.py: class ProcessorDetailView(DetailView): model = Processor template_name = 'finder/processor_detail.html' slug_field = 'slug' # Tell DetailView to use the `slug` model field as the DetailView slug slug_url_kwarg = 'slug' # Match the URL parameter name models.py: class Processor(models.Model): #the newly created database model and below are the fields name = models.CharField(max_length=250, blank=True, null=True) #textField used for larger strings, CharField, smaller slug = models.SlugField(max_length=250, blank=True) ... def __str__(self): #displays some of the template information instead of 'Processot object' if self.name: return self.name[0:20] else: return '--no processor name listed--' def get_absolute_url(self): # new return reverse("processor_detail", args=[str(self.slug)]) def save(self, *args, **kwargs): #`save` model a certain way(detailed in rest of function below) if not self.slug: #if there is no value in `slug` field then... self.slug = slugify(self.name) #...save a slugified `name` field value as the value in `slug` field super().save(*args, **kwargs) urls.py: path("detail/<slug:slug>", views.ProcessorDetailView.as_view(), name='processor_detail') I want that if I follow a link it either 1. doesn't matter what case … -
When I add project in python manager for my django website displaying me : Project startup failed, please check the project Logs
When I add project in python manager for my django website displaying me : Project startup failed, please check the project Logs and the status is suspended as you can see in the image below.enter image description here I followed these steps : The "logs" that are mentioned do not seem to be working but I do see these errors while executing: The dependencies needed to install the project, please wait... ERROR: Could not find a version that satisfies the requirement uvicom (from versions: none) ERROR: No matching distribution found for uvicom 2024-11-06 15:16:38 Start installing dependencies Looking in indexes: pypi.org ERROR: Could not find a version that satisfies the requirement asgiref=3.8.1 (from versions: none) ERROR: No matching distribution found for asgiret-381 and (myenv) root@vps-X:/www/wwwroot/myproject# gunicorn myproject.wsgi:application [2024-11-06 14:07:13 +0100] [203739] [INFO] Starting gunicorn 23.0.0 [2024-11-06 14:07:13 +0100] [203739] [ERROR] Connection in use: ('0.0.0.0', 8000) [2024-11-06 14:07:13 +0100] [203739] [ERROR] connection to ('0.0.0.0', 8000) failed: [Errno 98] Here are the steps I followed: Step 1: Connect to Your Server Use SSH to connect to your server securely. Replace <your-server-ip> with the IP of your server. ssh root@<your-server-ip> Step 2: Set Up Your Project Directory and Python Environment Create the Project … -
Django `The current path, detail/PayPal, matched the last one` error
I'm using Django's DetailView to display detailed information in my web app. I've set up a Processor model with a name and a slug field, and I'm using the slug field in the URL pattern and the DetailView. However, I'm running into an issue where the DetailView is not able to find the Processor object if the capitalization of the URL slug doesn't exactly match the slug field in the database. For example if I visit localhost:8000/detail/paypal I get the following error: Using the URLconf ... Django tried these URL patterns, in this order: ... detail/<slug:slug> [name='processor_detail'] The current path, detail/PayPal, matched the last one. In addition the url I entered in the url field changes to localhost:8000/detail/PayPal, capitalizing the letters. Finally, the url only works if I first visit it by clicking on a link to it from another page. After that it works perfectly normally whether I go incognito mode or not and no matter the capitalization I use in the slug. But if I go incognito mode and visit the url directly(ie, after not having visit it by clicking on a link to it from another page) it doesn't load at all whether I capitalize the slug … -
How to inject css from vue into a django template?
I have django as backend, vue as frontend - using boilerplate from https://github.com/ilikerobots/cookiecutter-vue-django I want to integrate quasar for my frontend. This is my setup in main.js: import './assets/main.css' import { createApp } from 'vue' import { createPinia } from 'pinia' import { Quasar } from 'quasar' import App from './App.vue' import 'quasar/dist/quasar.css' import '@quasar/extras/material-icons/material-icons.css' import '@quasar/extras/material-icons-outlined/material-icons-outlined.css' import '@quasar/extras/material-icons-round/material-icons-round.css' import '@quasar/extras/material-icons-sharp/material-icons-sharp.css' import '@quasar/extras/material-symbols-outlined/material-symbols-outlined.css' import '@quasar/extras/bootstrap-icons/bootstrap-icons.css' const app = createApp(App) app.use(createPinia()).use(Quasar, { plugins: {} // Add Quasar plugins here if needed }) app.mount('#app') I am injecting this in my django template header.html: {% extends "base.html" %} {% load vue_utils %} {% block content %} <div id="#app"></div> {% endblock %} {% block inline_javascript %} <script type="module" crossorigin src="{% vue_bundle_url 'main' %}"></script> {% endblock inline_javascript %} This is my vue component - App.vue: <template> <q-layout view="hHh lpR fFf"> <q-header elevated class="bg-primary text-white" height-hint="98"> <q-toolbar> <q-btn dense flat round icon="menu" @click="toggleLeftDrawer" /> <q-toolbar-title> <q-avatar> <img src="https://cdn.quasar.dev/logo-v2/svg/logo-mono-white.svg"> </q-avatar> Title </q-toolbar-title> </q-toolbar> <q-tabs align="left"> <q-route-tab to="/page1" label="Page One" /> <q-route-tab to="/page2" label="Page Two" /> <q-route-tab to="/page3" label="Page Three" /> </q-tabs> </q-header> <q-drawer show-if-above v-model="leftDrawerOpen" side="left" behavior="desktop" elevated> <!-- drawer content --> </q-drawer> <q-page-container> <router-view /> </q-page-container> </q-layout> </template> <script> import { ref } from 'vue' console.log("HERE") … -
Django Search Query to Match Names With and Without Accents in PostgreSQL
I'm using Django with a PostgreSQL database. In my database, I have a Users table with a name column that stores names with special characters, such as accents and the letter "Ñ". When performing a search, I want the results to include entries with and without accents. For example, if I have users with the names "lúlú" and "lulu", I would like both to appear in the search results, regardless of whether the search term includes accents. Here's my current code for the search functionality: def autocomplete(request): result = [] try: if request.user.is_staff and request.user.is_active: columns = request.GET.get("column_name").split(",") value = request.GET.get("column_value") columns = [ ("{}__icontains".format(column), request.GET.get("term")) for column in columns ] filters = request.GET.get("filters", []) if filters: filters = filters.split(",") filters = [tuple(x.split("=")) for x in filters] queryset = Filter( app_label=request.GET.get("app_label"), model_name=request.GET.get("model"), ).filter_by_list(columns, operator.or_, filters) for q in queryset: result.append( {"obj": q.to_json(), "label": str(q), "value": q.to_json()[value]} ) except AttributeError: pass return HttpResponse(json.dumps(result, cls=Codec), content_type="application/json") How can I modify my search to ignore accents and special characters so that a search for "lulu" also matches "lúlú" and vice versa? Are there any recommendations for handling accent-insensitive searches in Django with PostgreSQL? -
drf-spectacular (swagger) does not show request body of "application/json" in SwaggerUI
I have a login view with the following request body: However, when I select the content-type "application/json", I only receive the example, without the relevant data from my serializer that is shown in other content-types. I've tried numerous options to show the request body scheme of the request body, but nothing seems to work. This is my view: class LoginSerializer(serializers.Serializer): username = serializers.CharField( min_length=4, # Minimum length for login max_length=50, # Maximum length for login required=True, # Field is required help_text="email of the user", ) password = serializers.CharField( min_length=8, # Minimum length for password max_length=128, # Maximum length for password required=True, # Field is required style={'input_type': 'password'}, # This will hide the input in browsable API write_only=True, # Prevents password from being exposed in responses help_text="password of the user", ) @extend_schema(examples=[ OpenApiExample( 'Example', value={"username": "email of the user", "password": "password of the user"}, request_only=True, ) ],) class LoginView(GenericAPIView): """Authenticates the user via django session authentication cookie""" serializer_class = LoginSerializer def post(self, request): serializer = LoginSerializer(data=request.data) username = request.data.get('username') password = request.data.get('password') if not serializer.is_valid(): return ValidationError(serializer.errors) user = authenticate(username=username, password=password) if user is None: return ValidationError('Invalid credentials.') login(request, user) return JsonResponse({'detail': 'Successfully logged in.'}) and these are my drf settings: … -
When I use Jinja like this, it is calling all the tables and their columns. I only want to pass a particular column from the backend [duplicate]
{% for datas in data %} <option value="Hr">{{ datas.organization.org_name |slice:"15"}}</option> {% endfor %} When I retrieve data like this, the frontend will access all the database tables and columns. I only want to pass the org_name column. def department(request): data = main_collection.objects.all() return render(request, 'department/homee.html', {'data': data}) -
How to Build a Python-Based GraphQL API Gateway and Federation Service for Django Microservices?
I have a set of Django microservices, each exposing GraphQL APIs. Currently, I'm using Apollo Server with Apollo Federation to combine all subgraphs into a single supergraph. However, I've encountered a few limitations: Some of Apollo’s advanced features aren't free. The rover command (used to create a supergraph from subgraphs) requires an internet connection, which isn't ideal for my setup. I'm looking to build a custom solution in Python (using Flask, Django, or similar) that can serve as both an API gateway and a GraphQL federation service. The goal is to aggregate all subgraphs and generate a supergraph without relying on Apollo's proprietary tools. Has anyone implemented a similar solution or have suggestions for frameworks, libraries, or strategies to accomplish this? Any advice on building this gateway and handling GraphQL federation in Python would be greatly appreciated. I'm looking to build a custom solution in Python (using Flask, Django, or similar) -
Dynamically load secure components into a React app from Django backend after user authentication
I am building a Django/React application with two types of user experiences: Front-end browsing: Accessible with or without logging in. Dashboard: Accessible only to authenticated users. The dashboard contains sensitive components with static information that I prefer to keep entirely off the client side until the user is authenticated. This is important for both security and performance reasons. Is there a way in this Django/React setup to dynamically load (or send) additional React components or HTML from Django only after the user has successfully logged in? I’m looking for a secure and efficient way to deliver these sensitive components without including them in the initial bundle for all users. -
In pytest set up databases mirroring and test
I have a Django app that reads a read_only replica from a model in the DB. So in the pytest conftest fixtures, I have this settings.DATABASES["read_only"]["TEST"] = {"MIRROR": "default"} but when I instantiate fixtures, the read_only database doesn't have the data that I created with factoryboy. @pytest.fixture() def populate_cache() -> Callable[[CountryFactory], Household]: """ Fixture to populate the dashboard cache for a specific business area, verify creation in the default DB, and ensure readability in the read_only DB. """ def _populate_cache(goodcountry: CountryFactory) -> Household: # Create household and related records household, individuals = create_household("business_area": afghanistan) PaymentFactory.create_batch(5, household=household) PaymentRecordFactory.create_batch(3, household=household) # Verify data exists in the default DB payment_count_default = Payment.objects.using("default").filter(household=household).count() print(f"Payments in default DB: {payment_count_default}") # Verify data accessibility in the read_only DB payment_count_read_only = Payment.objects.using("read_only").filter(household=household).count() print(f"Payments in read_only DB: {payment_count_read_only}") # Assert that the data is accessible in the read_only DB assert payment_count_read_only == payment_count_default, "Mismatch in Payment count between default and read_only DBs." return household return _populate_dashboard_cache and I get an error: Payments in default DB: 5 Payments in read_only DB: 0 -
504 Gateway Timeout in Production for Django API Endpoint with Meta Products Feed API, but Works Locally
I'm working on a Django API that integrates with the Meta API for WhatsApp product feeds. This endpoint works perfectly on my local machine, but when I deploy it to production, it returns a 504 Gateway Timeout error. Details: Local Request (Works): curl -X POST http://127.0.0.1:8000/api/whatseat/save-changes/ -d "business_id=2" Production Request (504 Gateway Timeout): curl -X POST https://<production-url>/api/whatseat/save-changes/ -H "Authorization: Token <token>" -d '{"business_id": 2}' Key Observations: Error happens only in production—locally, the endpoint works fine. When this endpoint is called without the necessary WhatsApp data, it correctly returns a prompt to complete settings. So, the problem seems to occur during an external API request to the Meta (WhatsApp) API. def post(self, request): business_id = request.data.get('business_id') try: whatsapp_business = WhatsApp.objects.get(business=business_id) except ObjectDoesNotExist: return Response({"message": "Complete WhatsApp setup in settings"}, status=400) access_token = whatsapp_business.access_token product_catalog_id = whatsapp_business.catalog_id if not all([access_token, product_catalog_id]): return Response({"error": "Missing Access Token or Catalog ID"}, status=400) # External API request (seems to be the timeout issue in production) try: product_feed_data = request.build_absolute_uri(reverse('get-product-feeds')) response = requests.get(product_feed_data, params={ 'access_token': access_token, 'product_catalog_id': product_catalog_id }) response.raise_for_status() except requests.RequestException as e: return Response({'error': str(e)}, status=500) # Other logic... (contains another call to graph api for uploading the new data feed) Troubleshooting Attempts: Local … -
Show product name in template django
I want to show all of the user orders in its panel so, I have following models: this is my product model in django and in my order model I have productfk field that is id of user product. class Product(models.Model): id= models.IntegerField(primary_key=True) activedate = models.DateField() name= models.CharField(max_length=256) description = models.TextField() #following u can set user owner for this row #owner =models.ForeignKey(to=User,on_delete=models.CASCADE) category = models.CharField(max_length=256) unit =models.CharField(max_length=50) active = models.BooleanField(default=False) unitprice = models.DecimalField(max_digits=18, decimal_places=0) quantity = models.FloatField() minorder = models.FloatField() maxorder = models.FloatField() readytopay = models.BooleanField(default=False) showquantity = models.BooleanField(default=False) lastupdate = models.DateField() def __str__(self): return self.name and folloring is my order model: class Orders(models.Model): id = models.IntegerField(primary_key=True) customerfk = models.ForeignKey(to=User,on_delete=models.CASCADE) oxygenid = models.IntegerField() financialfk = models.IntegerField() orderdate = models.DateTimeField() productfk = models.IntegerField() unit = models.CharField(max_length=50) quantity = models.FloatField() unitprice = models.DecimalField(max_digits=18, decimal_places=0) discount = models.DecimalField(max_digits=18, decimal_places=0) totalprice = models.DecimalField(max_digits=18, decimal_places=0) onlinepayment = models.DecimalField(max_digits=18, decimal_places=0) customerdesc = models.TextField() companydesc = models.TextField() userip = models.CharField(max_length=20) status = models.CharField(max_length=50) creationdate = models.DateTimeField() def __str__(self): return self.status and this is my order view @login_required(login_url='/authentication/login') def index(request): unit=Unit.objects.all() orderstatus=OrderStatus.objects.all() #order=Orders.objects.all() order =Orders.objects.select_related('customerfk') paginator = Paginator(order,20) page_number = request.GET.get('page') page_obj = Paginator.get_page(paginator,page_number) #currency = UserPreference.objects.get(user=request.user).currency context={ 'order':order, 'orderstatus':orderstatus, 'unit':unit, 'page_obj':page_obj } return render(request,'orders/index.html',context) how i can … -
<link> has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a registration form to my website when I submit in web browsers (desktop) it successfully submitted but when I try to register using my browsers in mobile it shows Access to XMLHttpRequest at 'https://<link>/Member_Management/api/MembersDetails/' from origin '<link>?' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I already tried to multiple browsers from different devices this is already setup in my settings: CORS_ALLOW_ALL_ORIGINS = True # CORS configuration CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = [ <links> ] CORS_ALLOW_HEADERS = [ 'accept', 'authorization', 'content-type', 'x-csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] my ajax call $.ajax({ url: memberbackend_link + '/Member_Management/api/MembersDetails/', type: 'POST', data: memberData, contentType: false, processData: false, success: function(response) { How to fix the corsheaders to my website to be able to submit using mobile browsers -
Caddy for https on top of working django asgi app supposedly breacks websocket communication
I have a working django asgi application that uses channels for websocket communication with daphne and redis, and is running in a dockerized setup. To enable the secure https protocol, I tried going for a solution using caddy with selfsigned certificates (the app is deployed to a server internal to my organization). I get the caddy setup working so that I can access via https, but it seems to break the websocket part. For example, on clicking some buttons that should trigger websocket communication, I get errors like Uncaught ReferenceError: can't access lexical declaration 'ws' before initialization with a pointer to where I do a ws.send(...) in javascript. The websocket is initialized with let ws = new WebSocket('ws://' + window.location.host + '/ws/validation/'); Here is my docker-compose.yml: services: mywebapp: build: context: . dockerfile: Dockerfile.prod ssh: - default command: daphne -b 0.0.0.0 -p 8080 mywebapp.asgi:application ports: - "8080:8080" volumes: - .:/app depends_on: - redis env_file: - .env redis: image: redis:latest ports: - "6379:6379" caddy: image: caddy:latest ports: - "8081:80" - "8443:443" volumes: - ./Caddyfile:/etc/caddy/Caddyfile - /selfsigned.crt:/etc/ssl/certs/selfsigned.crt - /selfsigned.key:/etc/ssl/private/selfsigned.key depends_on: - mywebapp volumes: caddy_data: And this is my Caddyfile: example.com { tls /etc/ssl/certs/selfsigned.crt /etc/ssl/private/selfsigned.key reverse_proxy mywebapp:8080 { header_up Host {host} header_up X-Real-IP {remote} … -
difficulty to store staticfiles on S3 using STORAGES setting in django >=4.2
for file storage on AWS S3, django 4.2 introduced the STORAGES dictionary setting, replacing the individual DEFAULT_FILE_STORAGE and STATICFILES_STORAGE setting variables as explained on the django-storages documentation. I am posting this question because I do not find good resources about this "new" STORAGES dictionary setting. The documentation is light unfortunately about what the content of this STORAGES dictionary ought to be: STORAGES = { "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { ...your_options_here }, }, } adding that to... put static files on S3 via collectstatic on Django >= 4.2 you'd include the staticfiles key (at the same level as default) Referring to another source, I defined the following STORAGES dictionary in my settings.py: DEFAULT_STORAGE_BACKEND = "storages.backends.s3.S3Storage" DEFAULT_STORAGE_OPTIONS = { "access_key": os.getenv("S3_ACCESS_KEY"), "secret_key": os.getenv("S3_SECRET_KEY"), "bucket_name": os.getenv("S3_BUCKET"), "region_name": os.getenv("S3_REGION"), } STORAGES = { "default": { "BACKEND": DEFAULT_STORAGE_BACKEND, "OPTIONS": DEFAULT_STORAGE_OPTIONS, }, "staticfiles": { "BACKEND": "storages.backends.s3.S3StaticStorage" } } But when trying to collect my static files, I get the following error: 2024-11-06T04:01:52.930704485Z Collecting static files... 2024-11-06T04:01:57.469881851Z Traceback (most recent call last): 2024-11-06T04:01:57.470527987Z File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main 2024-11-06T04:01:57.474490708Z return _run_code(code, main_globals, None, 2024-11-06T04:01:57.475537977Z File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code 2024-11-06T04:01:57.475962333Z exec(code, run_globals) 2024-11-06T04:01:57.476460840Z File "/opt/project/src/manage.py", line 22, in <module> 2024-11-06T04:01:57.476786833Z main() 2024-11-06T04:01:57.476935378Z File "/opt/project/src/manage.py", … -
Python updating a global resource pool causes requests to block
Backdrop: Service basics: Django framework, cpu intensive service, start five uwsgi processes Because the underlying resource of the service is very large (2G), there are multiple versions, and this variable cannot be pickled, it is designed in the form of five processes The shape of this resource is as follows: GResource = {'key_1':resource_1, 'key_2':resource_2,'key_3':resource_3} Each request accesses this global variable GResource. At the same time, GResource is updated by BackgroundScheduler every two minutes Request time monitoring shows that when the 'GResource' cycle is updated, the request time will be higher than usual, usually 50 to 300ms, or even higher May I ask why -
uwsgi has not killed and became zombie, when stop by max-requests
I have problem... I set up configuration property 'max-requests'. When server receive requests at max-requests, uwsgi tell 'The work of process PID is done. Seeya!' and respawn worker at now But, my uwsgi became zombie process.... service 232327 0.0 0.0 0 0 ? Zl Nov05 0:06 [uwsgi] <defunct> So i configure 'vaccum', but it is not solution how do i can solve this problem.... This is my uwsgi configuration and I run server with django. [uwsgi] virtualenv = /home/service/service/.venv socket = /tmp/uwsgi_sock pidfile2=/tmp/service.pid module=project.wsgi callable=application master=true processes=1 threads=2 max-requests=2500 harakiri=15 lazy-apps=true vaccum=true logto=/var/log/service/uwsgi.log log-maxsize = 32428800 enable-threads = true ignore-write-errors=true ignore-sigpipe=true disable-write-exception=true I add configure 'vaccum'... and harakiri short.... but above harakiri seconds, process still zombieyour text -
why is my server showing bad request in the log as soon as it starts and it was working fine a few days ago
I deployed my Django project on Render, but every time I try to access the root URL (/), I receive a 400 Bad Request error. I have confirmed that my settings are configured with ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS to include the Render domain (challo-backend-1.onrender.com). My Redis server is configured to 127.0.0.1:6379 for Channels, and I’m using Django 5.1.2. ==> Your service is live 🎉 127.0.0.1 - - [05/Nov/2024:16:41:12 +0000] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" [2024-11-05 16:42:10 +0000] [95] [INFO] Handling signal: term [2024-11-05 16:42:10 +0000] [98] [INFO] Worker exiting (pid: 98) [2024-11-05 16:42:11 +0000] [95] [INFO] Shutting down: Master` """ Django settings for challo project. Generated by 'django-admin startproject' using Django 5.1.2. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ import dj_database_url from pathlib import Path from datetime import timedelta import os from django.core.exceptions import ImproperlyConfigured # Base Directory BASE_DIR = Path(__file__).resolve().parent.parent # Security settings (replace with your environment variable) def get_secret_key(): try: return os.environ['SECRET_KEY'] except KeyError: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") SECRET_KEY = get_secret_key() # Allowed Hosts and CSRF Trusted Origins ALLOWED_HOSTS = ['challo-backend-1.onrender.com', '127.0.0.1', 'localhost'] CSRF_TRUSTED_ORIGINS = ['https://challo-backend-1.onrender.com'] # Channel Layers CHANNEL_LAYERS … -
How to deploy Django app in docker with UV
I am writing a Dockerfile Configuration for a Django app. I am usin uv to manage my dependencies in a virtualenv. The app runs normally outside the container, but when I try to run it from the container, it can't find the django package: from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' This tells me that the recreation of the virtualenv inside the container is not working as it should. But I cannot find the problem. Here is my Dockerfile: FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim WORKDIR /app # Enable bytecode compilation ENV UV_COMPILE_BYTECODE=1 # Copy from the cache instead of linking since it's a mounted volume ENV UV_LINK_MODE=copy #ENV PYTHONDONTWRITEBYTECODE 1 #ENV PYTHONUNBUFFERED 1 RUN apt-get update && \ apt-get install -y --no-install-recommends gcc python3-dev libpq-dev gunicorn &&\ apt-get clean && \ rm -rf /var/lib/apt/lists/* # Install the project's dependencies using the lockfile and settings RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ uv sync --frozen --no-install-project --no-dev # Then, add the rest of the project source code and install it # Installing separately from its dependencies allows optimal layer caching ADD . /app RUN --mount=type=cache,target=/root/.cache/uv \ uv sync --frozen --no-dev #COPY --from=builder /usr/local/lib/python3.11/site-packages/ /usr/local/lib/python3.11/site-packages/ # Place executables in the environment at the … -
frontend cors error 'access-control-allow-credentials'
im using angular for my frontend and django with rest framework for my backend any request made from the front end gives the following message in my console Access to fetch at 'http://localhost:8000/login/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. this is confusing as my frontend has a interceptor which enables withCredentials export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn){ console.log(req) const modifiedRequest = req.clone({ withCredentials: true, }); return next(modifiedRequest) } and my backend has allow credentials set to true so im not sure where this error is coming from #cors settings CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] CORS_ALLOW_CREDENTIALS: True CSRF_TRUSTED_ORIGINS = [ 'http://localhost:4200', ] CORS_ALLOW_HEADERS = ( *default_headers, ) so i removed withCredentials from my interceptor which allowed requests to go through but im using cookies for auth and none are set in my frontend when you log in