Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cutting and pasting using jsPDF results in running out of memory
I have created a Django project called pdfClipper. It allows a user to select clips from an existing PDF file, reorder them in any order they wish, then it creates a new PDF file with those clips pasted in that order. It begins with opening a PDF file, which is uploaded in the static storage. Then, the user goes through each page, using sliders to get clips. Then, the screen where the user can choose how to reorder clips. Finally, the final screen shows where the new PDF file is created, using a progress bar to show how far along the process is. The problem is, if there are a lot of clips, the browser potentially runs out of memory. The following code is from the final page, titled "build.html". // this API gets data about the pdf file being clipped: // - the file name // - the maximum page width // - the maximum page height async function getFileData() { const response = await fetch("https://imcinnes31-pdfclipper.herokuapp.com/pdfclip/api/files?fileId={{fileId}}"); if (!response.ok) { throw new Error("HTTP error " + response.status); } return response.json(); } // this API gets data about each clip wanted from the file: // - the page where each clip … -
Can't upload images from flutter apps to Djnago rest framework
For my college project, I built an app, where I can update any kind of text info to Django rest API, but I can't send or upload any kind of media file from Flutter apps to Django. If anyone collaborated flutter with the Django rest framework please, help me with appropriate resources. I didn't find any resources to try to upload media files such as photos, pdf, videos, etc. -
Unexpected behaviour when calling serializer.create method, causes data loss in unrelated data (Django Rest Framework)
Im writing a tests for the serializer.create method. I prepared some data to pass it to the create method def create(self, validated_data): """ Passing in the restructured validated_data to the CostumUserCreate method. """ user_data = validated_data.get('user_data') profile_data = validated_data.get('profile_data') new_user = User.objects.create( user_data=user_data, profile_data=profile_data ) return new_user my test: def test_serializer_create(self): """ Tests the correct restructuring of the validated data within the CustomUserSerializer create method. """ data = {} user_data = { 'email': 'updated.email@GMAIL.com', # Not normalized 'password': 'blabla123' } profile_data = { 'first_name': 'Jay', 'last_name': 'Miller', 'position': self.position1 } data['user_data'] = user_data data['profile_data'] = profile_data serializer = serializers.CustomUserSerializer() user = serializer.create(data) print(f'USER DATA: {user_data}') print(f'PROFILE DATA: {profile_data}') when i try to print the user_data and profile_data now into the console it will be printed as an empty dictionary in the case of the user_data but not for the profile_data USER DATA: {} PROFILE DATA: {'first_name': 'Jay', 'last_name': 'Miller', 'position': <Position: Human Resource Specialist>} but as soon as i comment out the serializer.create method the user_data appears again in the terminal USER DATA: {'email': 'updated.email@GMAIL.com', 'password': 'blabla123'} PROFILE DATA: {'first_name': 'Jay', 'last_name': 'Miller', 'position': <Position: Human Resource Specialist>} i have no idea how this can even happen since the serializer.create … -
Database tuning for 1 million record
I have table which has 1 million record. And I show the data like this, simply show the data with ListView and pagenation from django.views.generic import ListView class ListSearchView(ListView): paginate_by = 10 form_class = None form = None ordering = "-created_at" sort_headers = None def get_initial(self): return self.request.GET.copy() def get_form(self): return self.form_class(self.get_initial()) def get_ordering(self): return self.request.GET.get("sort_by", self.ordering) def get_context_data(self, **kwargs): form = self.get_form() params = querydict_to_dict(self.request.GET.copy()) search_params = {k: v for k, v in params.items() if k != 'page' and k != 'sort_by'} query = {k: v for k, v in params.items() if k != 'page'} kwargs.update({ 'form': form, 'search_params': url_encode_params(search_params), 'query': url_encode_params(query), 'sort_by': query.get('sort_by', self.ordering), 'sort_headers': self.sort_headers }) return super(ListSearchView, self).get_context_data(**kwargs) def get_queryset(self): queryset = super().get_queryset() self.form = self.get_form() if self.form.is_valid(): created_date = self.form.cleaned_data.get('created_date') if created_date: start, end = created_date.split(DATE_RANGE_SEPARATOR) start_date = datetime.strptime(start, DATE_RANGE_FORMAT) end_date = datetime.strptime(end, DATE_RANGE_FORMAT) queryset = queryset.filter( created_at__gte=start_date.astimezone(pytz.UTC), created_at__lt=end_date.astimezone(pytz.UTC) ) status = self.form.cleaned_data.get('status', []) status = [s for s in status if s != ''] if status: queryset = queryset.filter( status__in=status ) return queryset class MessageListView(LoginRequiredMixin, ListSearchView): template_name = "message/index.html" model = Message def get(self, request, *args, **kwargs): return super(MessageLogView, self).get(request, *args, **kwargs) Now the load time is more than 2~3s, I would like to … -
On click function is not working in script
In product_detail.html: {% extends 'partials/base.html'%} {%load static%} {% block content %} <style> /* Basic Styling */ html, body { height: 100%; width: 100%; margin: 0; font-family: 'Roboto', sans-serif; } .containerbox { max-width: 1200px; margin: 0 auto; padding: 15px; display: flex; } /* Columns */ .left-column { width: 65%; position: relative; } .right-column { width: 35%; margin-top: 60px; } /* Left Column */ .left-column img { width: 70%; position: absolute; left: 0; top: 0; opacity: 0; transition: all 0.3s ease; } .left-column img.active { opacity: 1; } /* Right Column */ /* Product Description */ .product-description { border-bottom: 1px solid #E1E8EE; margin-bottom: 20px; } .product-description span { font-size: 12px; color: #358ED7; letter-spacing: 1px; text-transform: uppercase; text-decoration: none; } .product-description h1 { font-weight: 300; font-size: 52px; color: #43484D; letter-spacing: -2px; } .product-description p { font-size: 16px; font-weight: 300; color: #86939E; line-height: 24px; } /* Product Configuration */ .product-color span, .cable-config span { font-size: 14px; font-weight: 400; color: #86939E; margin-bottom: 20px; display: inline-block; } /* Product Color */ .product-color { margin-bottom: 30px; } .color-choose div { display: inline-block; } .color-choose input[type="radio"] { display: none; } .color-choose input[type="radio"] + label span { display: inline-block; width: 40px; height: 40px; margin: -1px 4px 0 0; vertical-align: … -
how to pass the query result in view.py to Bootstrap-table
i use pymysql to get data from my database conn = pymysql.connect( host='localhost', user='root', password='xxxxxxxxxx', database='TCR', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor, ) cur = conn.cursor() result = cur.excute('SELECT * FROM TCR') data = cur.fetchall() Then i return 'data' to my HTML file in HTML file i use Bootstrap-tabel to display my table. i notice that js part needs a .json file to fetch the data. such as: $('#table').bootstrapTable({ url: 'data1.json', columns: [{ field: 'id', title: 'Item ID' }, { field: 'name', title: 'Item Name' }, { field: 'price', title: 'Item Price' }] }) but i don`t want to use .json, i want to use the variable 'data' in js. How do I convert data to a form acceptable to bootstrap-table? i tried this <div id="data-container" data-query-results = {{ data }} ></div> <div id="reportTableDiv" > <table id="reportTable"></table> </div> <script type="text/javascript"> text = document.getElementById('data-container').getAttribute('data-query-results'); console.log(text) var datas = JSON.parse(text); but i got an error when i use JSON.parase() Uncaught SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3) at JSON.parse () Is there an easier way to achieve my purpose? -
Forbidden (CSRF cookie not set) with cookie being sent from react axios to django backend
Building simple user authentication with React and Django but have only got register coded so far. I have tried getting this to work for hours and am getting very frustrated.The react side is built and the register page is being run from the django port 8000. The development server is getting the cookie and setting it perfectly on local host port 8000. I put it in a hidden input field in my register form, then retrieve the cookie using js-cookie perfectly in auth.js (I can see this with console.log). I then send it with axios with the cookie in the header with withCredentials=true. I get the following error: error Forbidden (CSRF cookie not set.): /accounts/register [28/Feb/2024 19:39:57] "POST /accounts/register HTTP/1.1" 403 2869 I have tried various other methods of sending the cookie. I have all the relevant CORS settings set. views.py @method_decorator(ensure_csrf_cookie, name='dispatch') class GetCSRFToken(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request, format=None): return Response({ 'success': 'CSRF cookie set'}) auth.js import axios from 'axios'; import { REGISTER_SUCCESS, REGISTER_FAIL } from './types'; import Cookies from 'js-cookie' export const register = (username, password, re_password) => async dispatch => { const config = { withCredentials: true, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': … -
Django Summernote not rendering <font> tag with safe filter
when I try to change the 'color' in Summernote, Django doesn't render it properly; it gives the HTML tag instead of the color change. In the Django admin, it works well. <font color="#000000" style="background-color: rgb(255, 255, 0);">TEXT</font> The other attributes work fine. SUMMERNOTE_CONFIG = { 'iframe': True, 'summernote': { 'airMode': False, 'height': '291', 'width': '100%', 'toolbar': [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']], ], } } in the html <div class="content"> <p>{{ question.body|safe }}</p> </div> Can someone give me a hint for this? Ty a lot!!!!! -
how to proper setup ALLOWED_HOST to allow other machine in the network access the web
Django server in machine TestPC-A , at 192.25.56.120 I want it accessible from the computer in the same network 192.25.56.xxx. what I have configured 1. settings.py ALLOWED_HOSTS = ["127.0.0.1", "localhost", "TestPC-A" , "0.0.0.0", "192.25.56.120"] 2. runserver.bat @echo off REM Activate virtual environment in the current terminal session and run server cmd /k ".venv\Scripts\activate && python manage.py runserver_plus --cert-file cert.pem --key-file key.pem 0.0.0.0:8000" I have tried to add following in Windows hosts file C:\Windows\System32\drivers\etc\hosts 192.25.56.120 TestPC-A I restart the server, and the web page is not loaded at another computer's web browser https://TestPC-A:8000/ What else that I need to set? -
Importing CSV ManyToManyField into Django model with Pandas
I'm very new to Django and trying to write a small service app for work. Mostly everything is working so far except I cannot seem to get my csv to import with the M2M fields. I now know that you can't directly import to an M2M field, but I can't seem to get it working. My models.py class Service_Interval(models.Model): interval_name = models.CharField(null=True, max_length=200, help_text='Enter the name of the service interval') class Task(models.Model): service_intervals = models.ManyToManyField(Service_Interval, help_text="Select a Service Interval") My views.py: df=pd.read_csv(filename, sep=',', usecols=['Requirements','Service Interval','Task Current', 'Task Created','Task Name', 'Task Number']) #print(df) row_iter = df.iterrows() objs = [ Task( #id = row['ID'], requirements = row['Requirements'], #service_intervals = row['Service Interval'], <- wont import service_intervals = Service_Interval.interval_name.set(interval_name=row['Service Interval']) task_created = row['Task Created'], task_current = row['Task Current'], task_name = row['Task Name'], task_number = row['Task Number'], ) for index, row in row_iter ] Task.objects.bulk_create(objs) I cannot seem to get this working or find a solution to fit in with iteration? service_intervals should add the interval name to Service_Interval.interval_name. I cannot seem to retrofit any researched solutions. Everything else imports fine. Any help would be appreciated. -
Optimizing Django View to Handle Large Data Sets Efficiently
I'm seeking advice on optimizing a Django view to enhance its performance, particularly when dealing with a large number of clients in the database. Here's the scenario: I have a Django view called tClients that retrieves client data and renders it on a webpage. The view performs filtering based on a query parameter called status. If status is provided and falls within certain values, the view filters clients accordingly. Here's the current implementation of the view: @login_required(login_url='/accounts/login') def tClients(request): client_Form = NewClient() client_update_form = ClientUpdateForm() filter_status = request.GET.get('status', None) if filter_status is not None and filter_status in ['-1', '0', '1']: clients = Client.objects.select_related() # values('id','nni','nom','date','telephone','address','observation') clients = [client for client in clients if client.is_debt == int(filter_status)] else: clients = Client.objects.values('id','nni','nom','date','telephone','address','observation') context = { 'client_Form': client_Form, 'client_update_form': client_update_form, 'tClients': clients, } return render(request, 'clients/list_clients.html', context) The Client model is defined as follows: class Client(models.Model): nni = models.CharField(max_length=20, verbose_name=_('nni'), unique=True) uid = models.CharField(max_length=500) nom = models.CharField(max_length=255, verbose_name=_('nom')) date = models.DateField(verbose_name=_("date d'inscription")) img = models.ImageField(upload_to='client/qrcodes', blank=True, null=True, verbose_name=_("Image")) telephone = models.CharField(max_length=255, null=True, verbose_name=_("Telephone")) address = models.CharField(null=True, max_length=255, verbose_name=_("Address")) observation = models.TextField(null=True, verbose_name=_("Observation")) user = models.ForeignKey(User, blank=True, on_delete=models.SET_NULL, null=True) @property def is_debt(self): current_date = timezone.localdate() debts = self.client_detter.all() if debts.exists(): for debt in debts: … -
What is Django ORM equivalent for sql "field <> 1"?
Assuming that "field" is nullable, in raw sql condition WHERE field <> 1 will exclude all non 1 rows and also exclude all NULL rows. Why Django ~Q(field=1) makes query WHERE (NOT (field = 1 AND field IS NOT NULL)) which results to include NULL rows. Is there equivalent for sql field <> 1 in Django ORM? -
Project Django does not recognize field
So. I'm creating a login page app. I have a registration page where you can add username, email and password, then you need to confirm your email through a code that's send into your email everything works well, including sending the email, but confirming the user code with the template input is giving me problems first of all, I'll show my views (won't waste time with model because it's a simple user model, with a boolean field called is_email_confirmed with default = False) views.py def createuser(request): form = MyUserCreationForm() confirmed = User.is_email_confirmed if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): code = User.objects.make_random_password(length=6,allowed_chars='1234567890') user = form.save(commit=False) user.is_active = False user.save() user.code = code usercode = user.code user.save() subject = 'Confirm your email' confirmation_code = code message = f'Confirm your email with this code: {confirmation_code}' from_email = 'adryanftaborda@gmail.com' to_email = user.email send_mail(subject,message,from_email,[to_email]) input_code = request.POST.get('verify_code') # NOT WORKING if input_code == usercode: confirmed = User.is_email_confirmed == True if confirmed: user.is_active = True user.save() return redirect('home') else: messages.error(request,'Wrong code.') else: messages.error(request,'An error occured during your registration') context = {'form':form} return render(request, 'signup.html', context) as I said, everything seems to work, until here: input_code = request.POST.get('verify_code') # NOT WORKING if input_code == … -
How can I deal with tom-select and django form?
I found recently tom-select as alternative to Select2 for my forms. It's a great solution who work perfectly ! It works great when I use to create data from a form but when I want to use to edit data it's another problem. My edition form is in a modal ad this modal is opened by clicking on edit button on an item listing on main page behind. I use fetch in javascript to get data and to populate my input/select. It works well when I first open my modal ... but if I click on another item to edit next ... no clear data ... and error message in console saying there is allready an instance of tom-select for this input. My goal is to retrieve data (sometime it's a single select, sometime it's a multiple select) on tom-select with an easy part as I did with Select2. Here is my form <div class="modal fade">[...] <form id="product-form" method="post" action="{% url 'products' %}" class="mt-2"> {% csrf_token %} {% include 'form.html' with form=form %} <input type="hidden" name="id_product" id="id_product" value="" /> <div class="d-flex gap-2"> <a href="#" type="button" class="btn btn-secondary col-3" data-bs-dismiss="modal">{% trans 'Retour' %}</a> <button id="btn-product-modal" type="submit" class="btn btn-success col-9">{% trans 'Créer' … -
'ProgrammingError: cannot cast type bigint to uuid' in Django
I've been moving development of my website over to using Docker. I replaced sqlite as my database with postgresql then ran the command docker-compose exec web python manage.py migrate in my Docker environment and it produced the following error: File "/usr/local/lib/python3.11/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid LINE 1: ...quirementschat" ALTER COLUMN "id" TYPE uuid USING "id"::uuid ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 356, in handle post_migrate_state = executor.migrate( ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/db/migrations/migration.py", line 132, in apply operation.database_forwards( File "/usr/local/lib/python3.11/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line … -
DJango ORM - analogue for LEFT JOIN query
models.py class Products(models.Model): name = models.CharField() price = models.IntegerField() class Products_Images(models.Model): products = models.ForeignKey(Products) image = models.ImageField() name = models.CharField() I need to get PRODUCTS and only ONE or NO image for each product. Like this: SELECT Products.*,Products_Images.* FROM Products LEFT JOIN Products_Images on Products=Products_Images.product_id AND Products_Images.name LIKE '%pizza%' WHERE Products.price >= 50 -
Docker, problem creating and running container. Error creating or running container: 409 Client Error .../exec: Conflict (container...is not running)
In Django, in development phase i'm building and running a Docker container using a pool. I'm new to Docker. As you can see, I deliberately don't use the shell for personal project reasons. The code worked correctly until yesterday, then after turning the PC off and on again the code doesn't work today. PROBLEM. If I understand correctly, the problem is that I am trying to follow commands in a container that is not running, but after trying various solutions to wait, it seems that waiting is useless. The error is: Error creating or running container: 409 Client Error for http+docker://localhost/v1.44/containers/76950z4e1c65fx9hq7f8756db496eb2c0f7870609756g904452231580aa6e596b/exec: Conflict ("container 76950z4e1c65fx9hq7f87 56db496eb2c0f7870609756g904452231580aa6e596b is not running") SOLUTION ATTEMPTS. I have already tried several solutions, such as checking the state of the container in a loop (with for or while) and waiting for it to become "running" before proceeding with the creation of the running instance, or I have also tried time.sleep or other similar types of time). But this doesn't solve the problem. OBSERVATION: So the problem isn't about WAITING and I don't want a solution where you have to wait, because otherwise it means something is wrong. I also checked to close all previously created containers in … -
It is impossible to add a non-nullable field 'name' to table without specifying a default
class Track(gisModels.Model): track = gisModels.PolygonField() class GeoFence(gisModels.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE) fence = gisModels.PolygonField(geography=True) The above code is my models. It is impossible to add a non-nullable field 'track' to geofence without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Select an option: I have no idea to solve it out. -
Using Django filter inside Javascript
I am beginner at django, I stuck at using Django filter inside javascript. I was trying to implement Load More data using ajax. Everything works fine but i am not able to append new data to the html container. In my home view which is extends to base.html. i have the following html content- {% block content %} {% for post in posts %} <article class="media card border-secondary" style="margin: 1rem 0;"> <div class="card-body media-body"> <h5 class="card-title">{{post.post_title}}</h5> <h6 id="reading-time" class="card-subtitle mb-2 text-muted">{{post.post_content | readtime }}</h6> <p class="card-text">{{post.post_content | truncatewords:50 |markdown|striptags }}</p> <!-- | safe --> <a href="{% url 'article-page' post.post_id post.post_title|slugify %}" class="stretched-link">Continue Reading</a> </div> </article> {% endfor %} <button type="button" id="loadmorebtn" class="btn btn-outline-primary mx-auto d-block btn-lg">Load More</button> {% endblock content %} I am using some built-in django filter and one custom filter. On Load More button clicked i have some ajax code which runs fine and return the data- <script type="text/javascript"> $(document).ready(function () { var offset = 5 const loadBtn = $('#loadmorebtn'); loadBtn.click(function (e) { e.stopImmediatePropagation(); $(this).prop('disabled', true); // Disable the button $(this).html('<span class="spinner-grow spinner-grow-lg align-middle" role="status" aria-hidden="true"></span> Loading...'); // Change button text $.ajax({ url: "{% url 'load-more-posts' %}", type: "GET", data: { 'offset': offset }, dataType: 'JSON', success: function … -
Dockerized nginx and django on Apache installed VPS
I'm trying to deploy my dockerized django project with nginx container to a VPS server which has apache. Nginx conf with 80 port, I'm getting port already in use error. Therefore, I've changed my config as following. nginx.conf; server { listen 8080; server_name sub.example.com; resolver 127.0.0.11 ipv6=off valid=10s; charset utf-8; location /static { alias /var/www/static; } location / { proxy_pass http://app; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } docker-compose.yml; version: '3.8' services: nginx: restart: unless-stopped build: context: ./nginx dockerfile: './Dockerfile' ports: - "8080:8080" volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf - staticfiles:/var/www/static container_name: nginx depends_on: - app app: image: core build: ./ restart: always container_name: app command: bash -c "python manage.py collectstatic --noinput && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 core.wsgi:application --reload" volumes: - ./storage/assets/staticfiles:/app/storage/assets/staticfiles - staticfiles:/app/storage/assets/staticfiles/ - .:/app expose: - 8000 ports: - 8000:8000 env_file: - .env depends_on: - redis redis: restart: always image: redis:latest expose: - "6379" worker: build: ./ command: celery -A core worker -l info -Q celery environment: - C_FORCE_ROOT=true volumes: - .:/app depends_on: - redis beat: build: ./ command: celery -A core beat -l info volumes: - .:/app links: - redis depends_on: - redis volumes: staticfiles: When I build and run the project on … -
BaseSSHTunnelForwarderError django, python, linux (Ubuntu 22)
I was trying to run my django app (python framework v3.10.12, pip v24.0, django v4.2.5) on Linux (Ubuntu 22) and when executing the command python3 manage.py runserver I got this error message: 2024-02-28 15:58:07,627| ERROR | Could not open connection to gateway Traceback (most recent call last): File "/home/jheison/web_app/lambda_project/manage.py", line 22, in <module> main() File "/home/jheison/web_app/lambda_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/core/management/__init__.py", line 382, in execute settings.INSTALLED_APPS File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/jheison/web_app/lambda_project/lambda_project/settings.py", line 96, in <module> ssh_tunnel.start() File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/sshtunnel.py", line 1331, in start self._raise(BaseSSHTunnelForwarderError, File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/sshtunnel.py", line 1174, in _raise raise exception(reason) sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway Note: I ran git clone xxxxx correctly, installed requirements.txt with pipenv install -r requirements.txt Note: I have already … -
Nginx www to root redirection not working
this is my nginx config upstream django { server unix:///var/tmp/******.sock; } server { listen 80; server_name mydomain.com; charset utf-8; client_max_body_size 75M; location /static { alias **********; } location / { uwsgi_pass ********; include *************; } } server { listen 80; server_name www.mydomain.com; return 301 $scheme://mydomain.com$request_uri; } here mydomain is working fine when i go to www.mydomain i am not getting redirected. and lands on nginx default page. -
Is there an automated way to generate CRUD templates on django Project/App
I'm new in django, and it seems as it says batteries included FW, and I was wondering if this feature is available in django to generate CRUD templates for each entity using CLI.. like Python manage.py createCrud books, Member This might include the urls, views etc Is there something like that.. or maybe a plugin can do this? I haven't yet resulted something valuable. Expecting python code or plugin installation then super-tuning -
Django conditional annotation using python variable
Trying to figure out a way to use annotation depending of python variable condition check. Example: some_variable = 10000,50 #float expenses_by_categories = ( Category.objects.filter(transactions__operation="expenses") .annotate( expenses_sum=Sum('transactions__value', filter=Q( transactions__date_created__month=datetime.date.today().month) & Q( transactions__date_created__year=datetime.date.today().year)), ) .annotate( percentage=Round( ExpressionWrapper( F('expenses_sum') / some_variable * 100, output_field=FloatField() ), 2)) .order_by('-percentage') ) It works as long as some_variable greater then 0 otherwise zero devision exception rised. Is there is a way to carry out some checks inside annotation with such a logic: if some_variable > 0: percentage = F('expenses_sum') / some_variable * 100 else: percentage = 0 -
React Native (Expo) + Django app: TypeError: Network request failed
I have a React Native (Expo go) frontend and Django based backend. I have the django backend setup with some API endpoints, which I am trying to reach from frontend. When using npx expo start --tunnel command instead of npx expo start command to launch the frontend, the web requests to the backend fail. This is the full setup: In django settings, I have these settings setup: CORS_ALLOWED_ORIGINS = [ 'exp://julyt-u-anonymous-8081.exp.direct', 'http://localhost:19006', 'http://192.168.153.13:8081', '10.0..rest_of_the_ip', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ('*') ALLOWED_HOSTS = ['*'] I am launching the django server with: python manage.py runserver 10.0..rest_of_the_ip:8000 I am launching the frontend with: npx expo start --tunnel When sending webrequest to the api endpoint, I get this in the frontend side: E.g., ERROR API::loginUser->FAILED TO LOGIN USER: [TypeError: Network request failed] Backend side does not receive anything. This same setup works when I am using same wifi for both backend and frontend, for example when I am at a cafe: python manage.py runserver local_IPv4:8000 npx expo start And for the record, using npx expo start does not work when I am using this current wifi. The phone (expo go app) won't connect to the server, and thus it is not an option …