Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why the django choice field wont set the inital value?
i have a choice field like below def status_field(): return forms.ChoiceField( choices=[ (len(contract_status := Contract.Status.choices), 'all'), *contract_status ], widget=forms.Select(CUSTOM_SELECT_ATTRS), label='status', initial=Contract.Status.ACCEPTED ) Which is for Conract model and uses its Status Choice list which is like below class Status(models.IntegerChoices): PENDING = 1, 'pending' ACCEPTED = 2, 'active' REJECTED = 3, '...' TERMINATED = 4, '...' ON_HOLD = 5, '...' FINISHED = 6, '...' my form looks like this : class FilterForm(BaseFilterForm): __fields = ( 'contract_status', ...) contract_status = contract_status_field() i want the inital value to be active but it does not change i have tried to set it as 2 or {2 ,'active'} and Contrac.Status.ACCEPTED also i have tried to change it's value inside init . but it did not work ! Why ? how to do this? -
How to optimize Django view for performance?
I am wondering what the best practices are for optimizing view performance. I have this view that takes over 90 seconds to load (with 5 queries, 2 of which take the bulk of time). It has some complex queries, which a few Subqueries and a bunch of calculations. Should I try to split all these calculations in different views, use async for the calculations or use caching (I am fairly new to programming and Django)? def dispatchers_list(request): tenant = get_tenant(request) print("CURRENT_WEEK_CUSTOM: ", CURRENT_WEEK_CUSTOM) if request.method == 'GET': if request.GET.get('date_range') is not None: date_range = request.GET.get('date_range') date_start = datetime.datetime.strptime(date_range.split('-')[0].strip(), '%m/%d/%Y') print("date_start: ", date_start) date_end = datetime.datetime.strptime(date_range.split('-')[1].strip(), '%m/%d/%Y') custom_week_nr = get_week_number(date_end.date()) year = int(date_end.strftime("%Y")) date_start_string = date_start.strftime('%m/%d/%Y') date_end_string = date_end.strftime('%m/%d/%Y') else: date_start = start_week_nr(CURRENT_YEAR, CURRENT_WEEK_CUSTOM-1) date_start = datetime.datetime.combine(date_start, datetime.datetime.min.time()) date_end = date_start + datetime.timedelta(days=7) custom_week_nr = get_week_number(date_end.date()) year = int(date_end.strftime("%Y")) date_start_string = date_start.strftime('%m/%d/%Y') date_end_string = date_end.strftime('%m/%d/%Y') date_range = f"{date_start_string} - {date_end_string}" date_start_miles = datetime.datetime.combine(date_start - datetime.timedelta(days=7), datetime.datetime.min.time()) date_end_miles = date_start_miles + datetime.timedelta(days=14) # Calculate company rate per mile for last 2 weeks company_loads_last_2_weeks = Load.objects.filter(drop_date__gte=date_start_miles, drop_date__lt=date_end_miles).exclude(load_status='Cancelled').aggregate(billable_amount=Sum('billable_amount'), total_miles=Sum('total_miles')) if company_loads_last_2_weeks['billable_amount'] is not None and company_loads_last_2_weeks['total_miles'] is not None: company_rate_per_mile = company_loads_last_2_weeks['billable_amount'] / company_loads_last_2_weeks['total_miles'] else: company_rate_per_mile = 0 loads_subquery = Load.objects.filter( customer=OuterRef('customer'), # Reference … -
next-auth: Axios raises connect ECONNREFUSED ::1:8000 when sign-in to django
Stack Backend: django (dj_rest_auth for authentication) Frontend: nextjs (next-auth for authentication, environment variables are set correctly.) OS: Debian 12 - bookworm Dependencies: redis, memcached, rabbitmq running inside LXD - Ubuntu 22.04 container Summary i have a nextjs(13+)+django(4.2+) application up and running on my localhost, now i am at the stage of adding authentication. i am using next-auth(4.22+) to handle the authentication part. When i try to sign in, i get this error AxiosError: connect ECONNREFUSED ::1:8000, every other request made by axios go through except the login one. i have read other answers but none worked for me... Error { error: AxiosError: connect ECONNREFUSED ::1:8000 at AxiosError.from (file:///home/yuri/Coding/pos/frontend/node_modules/axios/lib/core/AxiosError.js:89:14) at RedirectableRequest.handleRequestError (file:///home/yuri/Coding/pos/frontend/node_modules/axios/lib/adapters/http.js:591:25) at RedirectableRequest.emit (node:events:514:28) at eventHandlers.<computed> (/home/yuri/Coding/pos/frontend/node_modules/follow-redirects/index.js:14:24) at ClientRequest.emit (node:events:514:28) at Socket.socketErrorListener (node:_http_client:501:9) at Socket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { port: 8000, address: '::1', syscall: 'connect', code: 'ECONNREFUSED', errno: -111, config: { transitional: [Object], adapter: [Array], transformRequest: [Array], transformResponse: [Array], timeout: 0, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', maxContentLength: -1, maxBodyLength: -1, env: [Object], validateStatus: [Function: validateStatus], headers: [AxiosHeaders], baseURL: 'http://localhost:8000', withCredentials: true, paramsSerializer: [Object], method: 'post', url: '/api/auth/login/', data: '{"username":"yuri","password":"yuri","redirect":"false","csrfToken":"80d0b198ee09f1abc790d722d42e6fa48a0e38c78a77d4e7c4bd340c9cbb9636","callbackUrl":"http://localhost:3000/auth/sign-in?from=%2Fprofile","json":"true"}' }, request: Writable { _writableState: [WritableState], _events: [Object: null prototype], _eventsCount: 3, _maxListeners: undefined, _options: … -
Limit number of query to show in a table using django
i have a query in django and want to show only 15 entries by page in my table but i want to avoid datatables if i can, if anyone can tip me a solution will be thanks. here is my table it work fine but i want to limit the number of clientes show to 15 and if posible add pagination i i dont know how to do it. <table class="table"> <thead> <tr class="text-center"> <th scope="col">#</th> <th scope="col">R.U.N</th> <th scope="col">Nombre y Apellidos</th> <th scope="col">Edad</th> <th scope="col" colspan="6">Acciones</th> </tr> </thead> <tbody> {% for cliente in clientes %} <tr class="text-center"> <td scope="row">{{forloop.counter}}</td> <td>{{cliente.runCliente}}</td> <td>{{cliente.nombreCliente}}</td> <td>{{cliente.edadCliente}}</td> <td>{{cliente.cargoCliente}}</td> <td> {% for empresa in empresas %} {% if cliente.empresa_id == empresa.id %} {{empresa.nombreEmpresa}} {% endif %} {% endfor %} </td> <td><a href="{% url 'edit_cliente' cliente.id %}" class="btn btn-success btn-md"><i class="bi bi-pencil-square"></i></a></td> <td><a href="{% url 'delete_cliente' cliente.id %}" class="btn btn-danger btn-md"><i class="bi bi-trash"></i></a></td> <td><a href="{% url 'add_registro' cliente.id %}" class="btn btn-info btn-md"> <i class="bi bi-plus-square"></i></a></td> <td><a href="{% url 'get_registrosCliente' cliente.id %}" class="btn btn-primary btn-md"> <i class="bi bi-search"></i></a></td> </tr> {% endfor %} {% endif %} </tbody> </table> my view.py function is very simple i only pass the cliente to list them all def manage_cliente(request): clientes = Cliente.objects.all() … -
ModuleNotFoundError: No module named 'littlelemonApi'
``your tPerforming system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self.kwargs) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site- packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\functional.py", line 57, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\utils\functional.py", line 57, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "", line 1204, in _gcd_import File "", line 1176, in _find_and_load File "", line 1147, in _find_and_load_unlocked File "", line 690, in _load_unlocked File "", line 940, in exec_module File "", line 241, in call_with_frames_removed File "C:\Users\USER\LittleLemon\littlelemon\littlelemon\urls.py", line 23, in path('api/',include('littlelemonApi.urls')), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER.virtualenvs\LittleLemon-a5AiNdQg\Lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module … -
Django Ajax to trigger a view not working
I'm trying to trigger a view by clicking a html button in a template. template (test.html) <div id="test_count"></div> <input type="button" value="Get number of records in DB" onclick="numberec()" /> <script> function numberec() { $.ajaxSetup( {data: {csrfmiddlewaretoken: '{{ csrf_token }}'}, }); $.ajax({ type: "POST", url: "../number_of_rec/", success: function (data) { $("#test_count").html({{number_of_rec}}); } }) } </script> View.py def number_of_rec(request): number_of_rec = Record.objects.count() data2 = render(request, 'test.html', {'number_of_rec': number_of_rec}) return (data2) def test(request): return render(request, 'test.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('number_of_rec/', views.number_of_rec, name='number_of_rec'), path('test/', views.test,name='test'), ] When I go to https://my_web_app.com/test in the web browser, the button doesn't trigger the number_of_rec view and the div is not filled with the result. BUT if I trigger the view by going to https://my_web_app.com/number_of_rec in web browser, the button is working and fill the div with the expected result. What should I do for my Ajax to trigger the number_of_rec view from the test.html page or any other page ? I'm a bit lost ... Thanks -
Rotation of the sphere in the photo with CSS
I want this hemisphere in the photo related to Wikipedia to rotate inward with only HTML and CSS codes (like the movement of the earth). The code that I sent below rotates the entire image, and it is also a 360-degree rotation, not an inward rotation. <img src="{% static "wiki.jpg"%}" alt="wiki.jpg"> img{ border-radius: 100px; margin-top: 400px; } @keyframes img { 0%{ transform: rotate(0deg); } 100%{ transform: rotate(360deg); } } img{ animation: img 20s ease-in-out infinite; } IMAGE If it is not possible to do this with this image, how can I design a similar image? -
PermissionError: [Errno 13] Permission denied: '/app/core/migrations/0005_recipe_image.py'
when i am trying makemigrations on dockerised django application, got this permissionError Here is Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip install --upgrade pip && \ apk add --update --no-cache jpeg-dev && \ apk add --update --no-cache --virtual musl-dev zlib zlib-dev && \ pip install -r requirements.txt &&\ adduser \ --disabled-password \ --no-create-home \ django-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R django-user:django-user /vol && \ chmod -R 755 /vol USER django-user COPY . . Here is docker-compose.yml: version: "3.9" services: app: build: . volumes: - ./app:/app - dev_static_data:/vol/web ports: - 8000:8000 image: app:django container_name: django_container command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db environment: - DB_HOST=db - DB_NAME=postgres - DB_USER=postgres - DB_PASS=postgres db: image: postgres volumes: - postgres_db:/var/lib/postgresql/data/ environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: postgres_db volumes: postgres_db: dev_static_data: When i run: docker-compose run --rm app sh -c "python manage.py makemigrations", the error message is: [+] Creating 1/0 ✔ Container postgres_db Running 0.0s Migrations for 'core': core/migrations/0005_recipe_image.py - Add field image to recipe Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() … -
How to add inline form to Inline form in django admin?
how do i make 2 nesting levels with default django admin methods (i want include C fields to form) models.py example Example: class A(models.Model): title=models.CharField(max_length=100) class B(models.Model): title=models.CharField(max_length=100) block_a=models.OneToOneField(A,on_delete=models.CASCADE,related_name="block_b") class C(models.Model): title=models.CharField(max_length=100) block_b=models.ForeignKey(B,on_delete=models.CASCADE,related_name="block_c") page example how i can create django admin model with inline form in inline form form example: title(class A) other_fields B: title(class B) other_fields C: title(class C) other_fields C: title(class C) other_fields C: title(class C) other_fields admin.py #its work class AInline(admin.StackedInline): model = A form = AForm class B(admin.ModelAdmin): model = B form = BForm but how do i make 2 nesting levels with default django admin methods (i want include C fields to form) -
I was trying to implement SOLID Principles. this time Dependency inversion in Python - Django
TypeError: SignInView.init() missing 1 required positional argument: 'api_response_factory' I try to use abstract methods but it failed. I'm new about SOLID implementation and new in python too, can someone give me an advice or idea about how to deal with this kind of erros? I have to add that this is my first time asking in stackoverflow from abc import ABC, abstractmethod from rest_framework.views import APIView from django.http import JsonResponse from rest_framework import status class ApiResponseFactoryAbstract(ABC): @abstractmethod def success(self) -> str: pass class ApiResponseFactory(ApiResponseFactoryAbstract): def success(self) -> str: print("Testing") return "Testing" class SignInView(APIView): def __init__(self, api_response_factory: ApiResponseFactoryAbstract): self.api_response_factory = api_response_factory def post(self, request): data = self.api_response_factory.success() return JsonResponse(data=data, status=status.HTTP_200_OK) This is app/urls.py: from django.urls import path from . import views router_auth = [ path("sign-in/", views.SignInView.as_view(), name="sign-in"), ] -
Saving a image with blob type on mysql using django and ReactJS
I would like to save a blob in mysql using django , but I have the following problem sometimes the image is saved as none and sometimes it gives a bad request problem, how can I solve this? Here my view.py: class RegiaoAPIView(APIView): serializer_class = RegiaoSerializer def get(self, request, pk=None, format=None): try: if pk is None: regioes = Regiao.objects.all() serializer = self.serializer_class(regioes, many=True) return Response(serializer.data) else: regiao = Regiao.objects.get(pk=pk) childs = Regiao.objects.filter(id_regiao_superior=regiao) serializer = self.serializer_class(regiao) serializer_apontando = self.serializer_class(childs, many=True) response_data = { "regiao": serializer.data, "childs": serializer_apontando.data if pk else None } return Response(response_data) except Regiao.DoesNotExist: return Response({"detail": "No Regioes found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"detail": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def post(self, request): try: # print("Dados binários da imagem:", request.data.get('imagem')) print("Entrou na view de criação") imagem_base64 = request.data.get('imagem', None) new_data = request.data.copy() if imagem_base64: print("Entrou no tratamento de imagem") imagem_bytes = base64.b64decode(imagem_base64) new_data['imagem'] = imagem_bytes poligono_valor = request.data.get('poligono', None) extend_valor = request.data.get('extend', None) poligono_resultante = createPolygon(poligono_valor) if extend_valor is not None: new_data['extend'] = json.dumps(extend_valor) new_data['poligono'] = poligono_resultante print("Dados antes da serialização:", new_data) serializer = self.serializer_class(data=new_data) if serializer.is_valid(): print("Dados válidos, criando objeto...") serializer.save() print("Objeto criado com sucesso") return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Erros de validação:", serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as e: … -
Django/CSS static files not loading
I am using a template to make a customized website. However some static files are loading and some are not. I get a red underline in my text editor in these locations: <section class="dento-service-area section-padding-100-0 bg-img bg-gradient-overlay jarallax clearfix" style="background-image: url({% static 'website/img/bg-img/13.jpg' %});"> <div class="container"> Any help in CSS formatting is appreciated. -
How to do mobile notifications with Django backend and flutter frontend? [closed]
I have a Flutter front-end mobile (iOS) app with a Django backend. I have a feature where I create posts and tag people. So when a creator publishes the post, the data is stored in the backend, Django. And also reflects on the tagged people's homepages when they reopen or refresh their app. Now I am planning to add a notification system in the app, where the post publishing should also alert the tagged people with a notification that they have been tagged. With a quick google seems like there are 2 ways to do it and I am confused about which one is feasible: Approach 1: When the creator publishes the post, have a concurrent command to send FCM notifications to the invited mobiles. Here, I won't be dealing with the backend at all. This ‘frontend-originating’ notifications seem easy as I don't have to deal with backend Django at all. Approach 2: Once the data is stored in the backend, send a django-fcm notification to alert the devices. This seems like a robust solution, as I think, in the future, IF I add backend computations and want to alert the user, I will have a ‘backend-originating’ notification already set … -
Django ManyToMany get error 'Object of type QuerySet is not JSON serializable'
i have this issue on my application. Object of type QuerySet is not JSON serializable In fact, i creating an application in which we have a relationship of the type several Products inone or more Orders. Here is my code : models.py # model Product class Products(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=500) class Meta: db_table ="products" # model Order class Orders(models.Model): order_id = models.AutoField(primary_key=True) order_number = models.CharField(max_length=500) supply = models.ForeignKey(Supplies, on_delete = models.CASCADE) statut = models.CharField(max_length=500, default="validé") date_of_order = models.DateField() products = models.ManyToManyField(Products, through='OrderProduct') class Meta: db_table ="orders" # model OrderProduct class OrderProduct(models.Model): Order = models.ForeignKey(Orders, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) product_quantity = models.PositiveIntegerField(default=1) class Meta: db_table ="ordersproducts" views.py # OrderGetAllApi @csrf_exempt def order_list(request): orders = Orders.objects.select_related('supply').all # orders = Orders.objects.select_related('products').all() order_list = [] for order in orders: order_list.append({ 'order_id': order.order_id, 'order_number': order.order_number, 'date_of_order': order.date_of_order, 'supply_id': order.supply.supply_id, 'supply_name': order.supply.supply_name, 'supply_address': order.supply.supply_address, 'products': order.products.all() }) return JsonResponse(order_list, safe=False) serializers.py class OrderProductSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = OrderProduct fields = ['product_id', 'product_name', 'product_quantity'] # fields = '_all_' class OrderSerializer(serializers.ModelSerializer): supply = SupplySerializer() products = OrderProductSerializer(many=True) class Meta: model=Orders fields=('order_id', 'order_number', 'date_of_order', 'statut', 'supply', 'products') I want to get the list of order with their respective products. when i enter … -
I got this error while making migration . module got error and for frozen importlib
I like to get file in postgreSQL . so i want to do migration so i got these error. there is more than model error like frozen importlib like error so help me to clear the error. I Expect the code and migrate successfully. File "J:\good\mainone\manage.py", line 22, in <module> main() File "J:\good\mainone\manage.py", line 18, in main execute_from_command_line(sys.argv) File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "J:\good\test\Lib\site-packages\django\core\management\base.py", line 425, in run_from_argv connections.close_all() File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 84, in close_all for conn in self.all(initialized_only=True): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 76, in all return [ ^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 73, in __iter__ return iter(self.settings) ^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\db\utils.py", line 148, in configure_settings databases = super().configure_settings(databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 128, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django Heroku /GET Favicon.Ico when running heroku logs --tail
My Heroku build is complete, but the application is not booting for some reason. When I run heroku logs --tail, 2023-09-04T13:32:07.484629+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=3515dc4d-fb0c-4ccb-bbdc-cb81a1ae5a31 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:07.768182+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=8c703a21-5109-4f0a-af7a-22c0e2687c8a fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:14.000000+00:00 app[api]: Build succeeded 2023-09-04T13:32:35.613845+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=6c9caf84-4fb9-4a08-96ea-ee41bae09184 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:35.808771+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=cd6e61e2-ee17-4f5e-abb4-c2ca33636d17 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.705631+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=journallove-e9a7a6e26520.herokuapp.com request_id=5d813e56-e116-4432-86f5-1ba43ba9227b fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https 2023-09-04T13:32:45.899516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=journallove-e9a7a6e26520.herokuapp.com request_id=14f662de-7547-40d0-bee9-522e847922c4 fwd="130.58.166.192" dyno= connect= service= status=503 bytes= protocol=https`` these are the issues that pop up. This is my Procfile and req.txt. web gunicorn journallove.wsgi:application --log-file - ` asgiref==3.6.0 blind==0.0.1 blinker==1.6.2 certifi==2023.5.7 charset-normalizer==3.1.0 click==8.1.3 cloudpickle==2.2.1 Cython==0.29.35 distlib==0.3.6 dj-database-url==2.1.0 Django==4.2.1 entrypoints==0.4 filelock==3.12.2 Flask==2.3.2 gitdb==4.0.10 GitPython==3.1.31 greenlet==2.0.2 gunicorn==20.1.0 django-heroku==0.3.1 idna==3.4 itsdangerous==2.1.2 Jinja2==3.1.2 joblib==1.3.1 MarkupSafe==2.1.2 mysql-connector-python==8.0.33 mysqlclient==2.1.1 nltk==3.8.1 numpy==1.24.3 package-json==0.0.0 pandas==2.0.1 platformdirs==3.8.1 protobuf==3.20.3 psycopg2-binary==2.9.7 PyMySQL==1.0.3 pytz==2023.3 PyYAML==6.0 querystring-parser==1.2.4 regex==2023.6.3 requests==2.31.0 six==1.16.0 smmap==5.0.0 SQLAlchemy==2.0.15 sqlparse==0.4.4 templates==0.0.5 tqdm==4.65.0 typing_extensions==4.6.2 tzdata==2023.3 urllib3==2.0.2 views-py==2.0.0 virtualenv==20.23.1 Werkzeug==2.3.4` I tried to move … -
Connecting Django Application in One Docker Container to MySQL in Another Container
Title: "Connecting Django Application in One Docker Container to MySQL in Another Container" I have a setup with two Docker containers: mysql-container: This container runs a MySQL image. my-django-container: It hosts a functional Django application. My objective is to establish a connection between the Django application running in my-django-container and the MySQL server in mysql-container. However, I'm encountering a database connection error: django.db.utils.OperationalError: (2002, "Can't connect to server on '36.253.8.13' (115)") Here are my Django settings for the database: "default": { "ENGINE": "django.db.backends.mysql", "NAME": "name", "USER": "username", "PASSWORD": "password", "HOST": "172.18.0.2", # What should I put here? The actual IP of the server `36.253.8.13` or the IP of the SQL container `172.18.0.2`? "PORT": "3306", # Is this the default port for SQL? } I've also placed both containers in the same Docker network, and I can confirm that both containers are visible when I inspect the network using the docker network inspect command. As a Docker novice, I would greatly appreciate any assistance in resolving this issue. -
How to use or work with fileshare.aio library?
I have been trying to implement the azure.storage.fileshare.aio Python SDK to upload files to my Azure File Share. I tried using the asyncio class and its functions to implement the directory_client.upload_file() function, that seems to be not working as expected and the control directly jumps to the return statement. I have provided the code snippet below. Please excuse any of the knowledge gap regarding async implementation, I have just started off with it. def some_other_func(): ..... directory_client = get_directory_client_aio(base_url=file_dir_url) response = asyncio.run(save(directory_client, new_file_with_changes, tasks=tasks)) ..... return response async def save(directory_client, new_file_with_changes, tasks : list): async with directory_client: tasks.append(asyncio.create_task(directory_client.upload_file(file_nam=new_file_with_changes.name, data=new_file_with_changes, length=new_file_with_changes.size))) asyncio.gather(*tasks) return Response.send_response(code=55) It will be appreciated if I get some assistance, Do's and Don'ts on the same. Thank you. -
Django and React authentication with Axios failing
I am building a web app with React and Django (frontend and backend resp.) and I am struggling to do user authentication. The urls in Django in my setup are basic, I will commit them for now. The views should be straightforward (feel free to suggest a more idiomatic approach as I am struggling with getting the right request response flow) basically, you can get a user with /users/int:id/ which returns either a private or public user object depending on whether the id is also the id of the authenticated user, login sends the id of the current user when successful. The issue I have is that login on it's own works just fine, though, when I refresh the page, react seems to have forgotten that the user was logged, it would be really annoying to ask the user to log in every time the page reloads. Therefor I made the authenticate view (and url users/authenticate/) which is supposed to return the private user object based on the session id. It is at this stage that things go wrong, the view does not recognise the user as authenticated (i.e., is_authenticated would fail). Some of the react: Home.js export const Home … -
malfuncting of python 3.11.5
while working on Django and I got to the point of installing Django with pipenv it refused to install Django saying it is neither an internal file nor external file. I tried deleting python and installing it i was expecting it to create a virtual environment. -
Django app stopped working after installing django-graphql-auth
I was working on a Django application with GraphQL. I installed few required libraries. Everything seems to be working fine until I installed django-graphql-auth. Immediately after installing that, I'm getting below error. /Users/sukumar/IntellijProjects/venvs/plotcare_be/bin/python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/core/management/init.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/sukumar/IntellijProjects/venvs/plotcare_be/lib/python3.8/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) File "/opt/homebrew/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", … -
How to pass arguments to get_success_url
views.py: class CommentDeleteView(DeleteView): model = Comments context_object_name = 'delete_comment' template_name = 'blog/comment_delete.html' def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True else: return False def form_valid(self, comment): messages.success(self.request, 'You have deleted the comment') return super().form_valid(comment) def get_success_url(self): post_pk = self.get_object().post.pk return reverse('post_detail', args=(self.kwargs['pk': post_pk])) models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(to=User, on_delete=models.CASCADE) def __str__(self): return f'{self.title} by {self.author}' def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) class Comments(models.Model): content = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(to=User, on_delete=models.CASCADE) post = models.ForeignKey(to=Post, related_name='comments',on_delete=models.CASCADE) def __str__(self): return f'Comment by {self.author} for {self.post.title}' def get_absolute_url(self): return reverse('comment_detail', kwargs={'pk': self.pk}) urls.py: urlpatterns = [ # path('', home, name='blog_home'), path('', PostListView.as_view(), name='blog_home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post_update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post_delete'), path('post/create/', PostCreateView.as_view(), name='post_create'), path('post/<int:pk>/comments/create/', CommentCreateView.as_view(), name='comment_create'), path('comments/<pk>/', CommentDetailView.as_view(), name='comment_detail'), path('comments/<pk>/update/', CommentUpdateView.as_view(), name='comment_update'), path('comments/<pk>/delete/', CommentDeleteView.as_view(), name='comment_delete'), path('about/', about, name='blog_about'), ] I cant understand how to pass Post primary key to get-successurl function. Comment model is a foreignkey to Post model. enter image description here *I have tried to get post pk with get_*object function but it doesnt seem to work. I cant really uderstand how it works and if you can give me some resources where to … -
How to host a Flask Application on KingHost?
KingHost has a tutorial page for hosting this type of application, but it is not in the same scenario as mine, in which it has more files and folders like "static", in addition to not being clear and explanatory. I would very much like some help. I already spoke with their support, but they say they don't have programming support and don't even know the solution to my problem. I need to know the correct directory, where I should put the .wsgi, virtualenv, app.py, static and templates. Can anyone help me, please? Follow my .wsgi: # vim: syntax=python import sys activate_this = '/home/tvconstruai/apps_wsgi/source/venv/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) sys.path.append('/home/tvconstruai/apps_wsgi/') from source.app import app as application KingHost has a tutorial page for hosting this type of application, but it is not in the same scenario as mine, in which it has more files and folders like "static", in addition to not being clear and explanatory. I followed their tutorial, and on my page web says they can't find the files since I put them where they asked. -
how webpack config file handle logo path when bundling frontend
I have a django project already build and running and i need to change its logo. I have updated the logo path in /static/js/header.jsx but change is not showing up in browser. I have cleared the browser cache. I am new to django and I am wondering if it has anything to do with webpack config file or something like that. Any one with any idea would help alot. Thanks Below is just code from /node/webpack.config.js not necessary related to my problem: var path = require('path'); var nodeExternals = require('webpack-node-externals'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var DeepMerge = require('deep-merge'); var nodemon = require('nodemon'); var fs = require('fs'); var deepmerge = DeepMerge(function (target, source, key) { if (target instanceof Array) { return [].concat(target, source); } return source; }); class WatchRunPlugin { apply(compiler) { compiler.hooks.watchRun.tap('WatchRun', (compilation) => { console.log('Begin compile at ' + new Date()); }); } } class CleanOldAssetsOnBuildPlugin { apply(compiler) { compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => { const newlyCreatedAssets = compilation.assets; const unlinked = []; console.log(path.resolve(buildDir + 'client')); fs.readdir(path.resolve(buildDir + 'client'), function (err, files) { if (typeof files === 'undefined') { return; } // we've started to see cases where files is undefined on cloudbuilds. adding this here as … -
Django async with AppConfig.ready sync/async
I am running Django version 4.2.4 in async mode. For one of my apps I have some code to run on ready like this: class CoreConfig(AppConfig): name = 'demo.core' def ready(self): from .utils import my_sync_func my_sync_func() When I run this code, I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" When I use sync_to_async like this: class CoreConfig(AppConfig): name = 'demo.core' async def ready(self): from .utils import my_sync_func await sync_to_async(my_sync_func)() I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" What is the correct way of doing this? Thanks a lot