Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset queryset
I have two apps: accounting and projects. Every consumption item has a fk to project. Every production has a fk to a project. Production order has fk to production. produced product has fk to production order. consumption item has fk to produced product. While creating produced line, I want to create consumption line as formset. However, consumptionitemline_to_consume field should show instances from the related project, not all instances.. Below I tried to filter the dropdown however, it just does not work. here is forms class ProductionProducedLineConsumptionLineForm(forms.ModelForm): class Meta: model = ProductionProducedLineConsumptionLine fields = '__all__' widgets = { 'productionproducedline': forms.HiddenInput(), 'produced_kg_scrap': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), 'produced_kg_wastage': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), } def __init__(self, *args, **kwargs): production_id = kwargs.pop('production_id', None) # We'll pass this when initializing the formset in the view super(ProductionProducedLineConsumptionLineForm, self).__init__(*args, **kwargs) if production_id: production = ProductionProducedLine.objects.get(id=production_id) project = production.productionorderline.production.project self.fields['consumptionitemline_to_consume'].queryset = ConsumptionItemLine.objects.filter(project=project) # This does not work? ProductionProducedLineConsumptionLineFormSet = inlineformset_factory( ProductionProducedLine, ProductionProducedLineConsumptionLine, fk_name='productionproducedline', form=ProductionProducedLineConsumptionLineForm, # Use the custom form fields=('productionproducedline','productionproducedline_to_consume', 'consumptionitemline_to_consume','consumed_kg_product','produced_kg_scrap', 'produced_kg_wastage','wastage_return_customer'), extra=1, can_delete=True ) Here is view class ProductionProducedLineCreateView(CreateView): model = ProductionProducedLine form_class = ProductionProducedLineForm template_name = 'projects/produced_create.html' def get_form_kwargs(self): """Ensure the form is initialized with necessary kwargs.""" kwargs = super(ProductionProducedLineCreateView, self).get_form_kwargs() if self.kwargs.get('order_line_id'): kwargs['order_line_id'] = self.kwargs['order_line_id'] return … -
django postgreSql database connection problem
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "Postgres" i will face this problem,I am beginner of django and POSTGRESQL How to solve this error -
Json on the front is incomplete, how to solve it?
I was serializing the data in django to pass it to bff and then to the front, I tested the requests to see if they were all "ok", the result of the direct request to django is ok, the request from bff is also ok, but when I went to see on the front it was incomplete with some of the fields missing, especially those with a compound name django rest api: { "id": 6, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": null }, { "id": 7, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": null }, bff: { "id": 6, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": "" }, { "id": 7, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": "" }, front-end (Nextjs) { "chatGroup": "", "chatID": 0, "date": "XXXXXXXXX", "firstName": "", "id": 6, "lastName": "", "messageUser": "", "status": "" }, { "chatGroup": "", "chatID": 0, "date": "XXXXXXXXX", "firstName": "", "id": 7, "lastName": "", "messageUser": "", "status": "" } As I'm using typescript I made a type for the message type: export type MessageProps = { … -
Django app; Default User ID and model field 'Trader ID' not equal
I am creating an app to allow users to enter stock trades, for record keeping. I am using Django's default User model for login and authentication. My intention is to allow the logged in user to view only their own 'Entries', which is my model for stock record entries. To this end, I have created a one to Many relationship in my Entry model named 'trader' which points to the User ID (they should be the same). After logging in though, I don't see ANY trades on the screen even though they have been entered. I checked the Database, and the Entry.trader.id is the same number as the User.id (1 in the case of the first user created). Very strange. What I tried: I tried removing this line from my views.py EntryView class: entries = Entry.objects.filter(trader_id=logged_in_user).order_by("entered_date") and replacing it with: entries = Entry.objects.all() This works (proving that the records are there)but now it shows ALL of the entries. My models.py: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User class Entry(models.Model): ONEORB="1-Min ORB" FIVEORB="5-Min ORB" ABCD="ABCD" REVERSAL="Reversal" PROFIT="Profit" LOSS="Loss" RESULT_CHOICES = ( (PROFIT, "Profit"), (LOSS, "Loss") ) STRATEGY_CHOICES … -
django forms.ModelChoiceField not populating for edit form
I'm using same view and template for adding and editing the record in django. when I click on edit, all other fields are populated correctly, but modelChoiceField has no value. I've tried the solution Django ModelChoiceField is not filled when editing but not getting the desired results. Here's how I'm defining the field in model category = forms.ModelChoiceField( queryset=Category.objects.all(), empty_label="Select Category", required=True, to_field_name="name" ) Here's how I'm initializing my form form = myForm(request.POST or None, instance=form_instance, initial=models.model_to_dict(form_instance)) if I print the output from model_to_dict(form_instance) it show {'id': 18, 'title': 'test title', 'description': 'test description', 'material': 'blah blah', 'category': 2, 'user': 3} But on the form, model choice field has empty label. How do I populate it with NAME for category having pk=2 in above case ? -
How can I properly daemonize Celery to ensure it runs continuously without any issues?
My celery works locally but when I try celery daemonization at server side, it does not work. When I run this code I can see there is a successful connection with redis. code enter image description here But I am getting error, failed to start celery service..enter image description here Can someone please help me? I run of ideas how can I solve this issue? My recouces at my instance. 4 GB RAM, 2 vCPUs, 80 GB SSD. -
best method to do Django facial recognition by capturing the customer's
Good afternoon, what would be the best way to capture frames from the user's camera to use a function I have in Django views for facial recognition. What I'm trying now is to open a camera for the user on the web and from there remove the frames, but it's not working correctly as it's giving me the error "TypeError: Object of type bytes is not JSON serializable" and also I wanted the user to have that frame around the face saying that the image is being captured. I will send below what I have in views and in my js I appreciate any help or opinion offered @csrf_exempt def process_frame_faceRecognition(request): print("Processando frame...") if request.method == 'POST': frame_data = request.POST.get('frame_data') print(frame_data) frame_data = frame_data.split(',')[1] # Remover o prefixo 'data:image/png;base64,' frame_data_decoded = base64.b64decode(frame_data) frame_data = np.frombuffer(frame_data_decoded, dtype=np.uint8) frame = cv2.imdecode(frame_data, flags=1) # Agora você pode passar o frame para a função compare_faces() face_recognition = FaceRecognition() result = face_recognition.run_recognition(frame) # Verifique o tipo de resultado antes de retorná-lo if isinstance(result, HttpResponseRedirect): return JsonResponse({'message': 'redirecionamento', 'url': result.url}) else: # Coleta os valores do generator em uma lista result_list = list(result) # Codifica a imagem como base64 _, buffer = cv2.imencode('.png', frame) frame_base64 = … -
Why Django does not be deployed easily?
I have been learning Django for a long time, and I always find difficulties in deploying my projects, I often deploy my projects on AWS, and it takes a lot of money, also, the other platforms take a lot of fees to make your Django project deployed on their platforms, After that I decided to move to PHP here I found a difference, -and the difference is in the amount of time, that you need to deploy your project (which is a lot shorter than Django), -and the amount of fees that you need to pay to the platform to deploy your project on (it is 100%100 cheaper than Django), -and there are a lot of platforms for PHP, while Django there are few platforms to deploy your project on, -and PHP is much easier to deploy, there are platforms that just you take your project and drag it then drop it to them, and this is everything. my questions are : 1- Why sometimes you have to take a cloud computer service then you have to install python , and everything in python , then you upload the Django project, it is like you are using it on your … -
TinyMCE style working in Django admin, but not working in Angular frontend
I have django backend admin template, with TinyMCE textfield. In the textfield I add inline CSS style to the HTML. It's working correctly. <ol style="color: blue; font-weight: bold;"> <li><span style="color: black; font-weight: normal;">L&aacute;togasson el a szolg&aacute;ltat&oacute; oldal&aacute;ra: </span></li> <li><span style="color: black; font-weight: normal;">Adja meg a regisztr&aacute;ci&oacute;hoz sz&uuml;ks&eacute;ges adatokat (a partnersz&aacute;mot &eacute;s a sz&aacute;ml&aacute;n szereplő nevet kiemelt&uuml;k).</span></li> <li><span style="color: black; font-weight: normal;">Jegyezze fel a regisztr&aacute;ci&oacute; sor&aacute;n megadott e-mail c&iacute;met &eacute;s jelsz&oacute;t (k&eacute;sőbb sz&uuml;ks&eacute;g lesz r&aacute;).</span></li> <li><span style="color: black; font-weight: normal;">Sikeres vagy sikertelen regisztr&aacute;ci&oacute; ut&aacute;n kattintson a Tov&aacute;bb gombra.</span></li> </ol> But on the frontend (with innerHTML), the styling is not working. I get the data correctly from the JSON, but in the html doesnt show the css, just the html. -
Advanced Search feature for E-commerce Website using Django
I am working for a ecommerce platform for which I have to make an advance, fast, error handling Search bar, we have thousands of products, many categories, many variants! I want to build a very fast search bar that have features like: dynamic Auto-suggestion fuzzy word handling suggestions for usage of open source services suggestions on python libraries like whoosh to make it faster applying caching and all, like using Redis and all Handling no product found and all I want help with what i should use what not and also, any models i should update like for user what they have searched in past, should i store that, and all, Please help me, I am asked to research and work on this, but I am confused and reached no where yet!!!!!! -
UnboundLocalErrorat /aauth/request-reset-email/
[enter image description here](https://i.sstatic.net/QsavU8an.png) I an having an [UnboundLocalError at /aauth/request-reset-email/ cannot access local variable 'email_subject' where it is not associated with a value] error. I have been trying to sort this out but all to no avail...have checked all my configurations too. please anyone with similar probblem or solution should help out. Thank! -
Error loading css and js files in django project
here is the github repository: https://github.com/RobertmPevec/business-flow whenever I load the page on my local server I get the following errors: enter image description here If anyone could help I am kinda lost here and am new to programming so any advice to fix this would be helpful, thanks. Went through settings.py and base.html to try to confirm everything was configured properly and fix any mistakes I made although nothing I tried resolved the issue -
Design User class in Django
I use the AbstractUser class to extend my User class. In my User class, there are currently 3 roles: Admin, Lecturer and Alumni. I can use is_superuser, is_staff to solve the problem, however, in the future there may be more roles appearing and if I use the above method it will not be possible to add more roles better. But if I use the additional field role = models.IntegerField(choices=Role.choices, default=Role.ALUMNI) it looks fine. But when using superuser, is_superuser = True and the user's role is Alumni. By the way, I'm working on a project using django, rest_framework. I want Users with the role of Lecturer to be created by the Admin and set a default password, and after 24 hours from the time of account creation, if the Lecturer does not change the password, the account will be locked and the Admin will have to reopen for Lecturer. I wrote two functions save and check_password_expiry but I'm not sure if it works as I want. Can someone solve my current problem, please? class User(AbstractUser): class Role(models.IntegerChoices): ADMIN = 1, "Admin" LECTURER = 2, "Lecturer" ALUMNI = 3, "Alumni" avatar = CloudinaryField(null=True) cover = CloudinaryField(null=True) role = models.IntegerField(choices=Role.choices, default=Role.ALUMNI) alumni = … -
How can we get custom token from dj-rest-auth while authentication?
We are trying to use dj_rest_auth to make social authentication, starting with Google auth, work on a site / app using JWT token pair (access & refresh). Our attempted solution is as follows: Goal: We are modifying the register & login API endpoints provided by dj_rest_auth to return our JWT custom token pair (as returned by the api/token endpoint), instead of the session key. Possible options: Option 1: Extend dj_rest_auth.registration.views.RegisterView with a CustomRegisterView, modifying the perform_create method to return the JWT token pair. Option 2: Let dj_rest_auth.registration.views.RegisterView return the session key & token be in the cookie, but modify the token in the cookie to add the logic in our custom token serializer to add additional fields. The above approaches will apply to Loginview as well. Our questions: Which of the above is better? Our preference is for approach 1 - more consistent with our maintenance & use of tokens before social auth. Is there any concern with the above option 1 - ie having register & login endpoints return the JWT token pair? Assuming Option 1 - what is the best way to do it? We are trying to extend the RegisterView - but it’s unclear which method to … -
Is there a boilerplate template for a TDD approach in Django-Python
I’m working on a side a project while trying to discipline myself to get accustomed to the TDD approach in Django. I'm not sure why I’m running into this failed test (venv) osahenru@osahenru ~/D/q-4> pytest -k test_can_post_questions ============================= test session starts ============================== platform linux -- Python 3.10.12, pytest-8.1.1, pluggy-1.5.0 django: version: 5.0.4, settings: config.settings (from ini) rootdir: /home/osahenru/Documents/q-4 configfile: pytest.ini plugins: django-4.8.0 collected 5 items / 4 deselected / 1 selected app/tests/test_views.py F [100%] =================================== FAILURES =================================== ______________________ TestEvent.test_can_post_questions _______________________ self = <test_views.TestEvent testMethod=test_can_post_questions> def test_can_post_questions(self): event = Event.objects.create(name='Python Ghana') data = { 'text': 'how are you?', } response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data) > self.assertIsInstance(response.context['form'], QuestionCreateForm) E TypeError: 'NoneType' object is not subscriptable app/tests/test_views.py:52: TypeError =========================== short test summary info ============================ FAILED app/tests/test_views.py::TestEvent::test_can_post_questions - TypeError: 'NoneType' object is not subscriptable ======================= 1 failed, 4 deselected in 0.53s ======================== (venv) osahenru@osahenru ~/D/q-4 [0|1]> here is the test causing the error message def test_can_post_questions(self): event = Event.objects.create(name='Python Ghana') data = { 'text': 'how are you?', } response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data) self.assertIsInstance(response.context['form'], QuestionCreateForm) self.assertEqual(response.status_code, 302) and here is the view function def questions(request, pk): event = Event.objects.get(id=pk) questions = Question.objects.filter(event=event) form = QuestionCreateForm() if request.method == 'POST': form = QuestionCreateForm(request.POST) … -
Why does Sentry catch my local host errors but not my errors for my prod url in Django?
I have this in my settings. I have my debug to False, did I miss something. I never messed with anything in my app urls.py. sentry_sdk.init( dsn="***", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. traces_sample_rate=1.0, # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. profiles_sample_rate=1.0, ) -
Flask as a back-end web programming framework
I'm currently working on a simple project that I wanted it to be my introduction to python web programming. I've wrote a python code of what I needed and I'm working on the interface that I wanted to be a web based one. I choose to work with flask. I wanted to know whether I have to modify the code to be suitable with the framework? and how to manipulate the database since I was working with csv files in my initial code? So basically the code consists of different search algorithms in artificial intelligence (BFS, DFS, A* and hill climbing) that return a path in a map. I wanted to used html, css, js and flask to implement an interface that gives the user option to choose starting and goal states and represent that resulting path in a map. -
Adding the django-parler to admin page in Django admin
I'm working on my Django project and I added django-parler to my Django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding … -
How to Prefetch a group concat field in Django
my question is the following : I have a view table mapped to the Django ORM, with a group_concat field using MariaDB. Is it possible to fetch IDs from this: This view stores data for operators, and each operator can be associated with multiple companies Class OperatorsView(models.Model): id = models.IntegerField(primary_key=True, db_index=True) # fleet_operator_id fleet_operator = models.ForeignKey( "companies.FleetOperator", on_delete=models.DO_NOTHING, null=True ) user = models.ForeignKey( "accounts.MobileUser", on_delete=models.DO_NOTHING, null=True ) operator = models.ForeignKey( "companies.Operator", on_delete=models.DO_NOTHING, null=True ) companies_shared_str = models.CharField( db_column="companies_shared_id", null=True, max_length=4000 ) So I would like to know if the companies_shared_str field is possible to be used in OperatorsView to prefetch in advance, not using a @property because this will lead to N + 1 queries. Any suggestions would be greatly appreciated -
Docker image is not updating on Azure container registry via gitlab
I am having an issue with my docker images which are uploaded on the Azure container registry via gitlab, but they seem not to be updating the current code, but locally they work. What could be a problem to my .gitlab-ci.yml file ? image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - develop build-dev: stage: develop before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - apk add --no-cache --upgrade bash script: - apk add --no-cache bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login $AZ_REGISTRY_IMAGE -u $AZ_USERNAME_REGISTRY -p $AZ_PASSWORD_REGISTRY - docker pull $AZ_REGISTRY_IMAGE/proj:tag || true - docker-compose build --no-cache - docker tag $AZ_REGISTRY_IMAGE/proj:tag $AZ_REGISTRY_IMAGE/pixsar:$(date +%Y%m%d%H%M) - docker push $AZ_REGISTRY_IMAGE/proj:$(date +%Y%m%d%H%M) - docker system prune -af only: - develop - fix-docker-1 -
I have a problem with send email by django
I have a problem with send_email by django I tryed gmail and hotmail and email private , all of them return the same error code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'info@bajco-sa.com' EMAIL_HOST_PASSWORD = 'admeralGXG1986' EMAIL_USE_TLS = False EMAIL_PORT = 465 Error console: ` File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 398, in getreply line = self.file.readline(_MAXLINE + 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/socket.py", line 707, in readinto return self._sock.recv_into(b) ^^^^^^^^^^^^^^^^^^^^^^^ ConnectionResetError: [Errno 54] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/blog/views.py", line 64, in post_share send_mail(subject, message, 'gxgxxxx@gmail.com', [cd['to']]) File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/init.py", line 87, in send_mail return mail.send() ^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() ^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( ^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 255, in init (code, msg) = self.connect(host, port) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 343, in connect (code, msg) = self.getreply() ^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 401, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed: " smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset … -
forbidden (403) CSRF was not verified. The request was cancelled
I am logogin with super admin in django project and want to change some properties of users but when i clicked at save button it shows an error as below: forbidden (403) CSRF was not verified. The request was cancelled. Help Reason given for failure: Origin checking failed - https://somedomain.com does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page … -
'Failed to establish a new connection: [Errno 111] Connection refused'
I am trying to run a django application with a postgres db on docker-compose. I can run it perfectly but as soon as I do a post request, I get this error: FAILED tests/test_email.py::TestUser::test_list_to - requests.exceptions.ConnectionError: HTTPConnectionPool(host='172.17.0.1', port=8080): Max retries exceeded with url: /api/v1/customers/516c7146-afc0-463b-be0e-7df01e8a86f6/emails (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff6544eada0>: Failed to establish a new connection: [Errno 111] Connection refused')) This is my docker-compose file: version: "3" services: db: image: postgres:latest restart: always environment: POSTGRES_PASSWORD: verySecretPassword POSTGRES_USER: administrator POSTGRES_DB: project volumes: - ./data/db:/var/lib/postgresql/data web: build: . restart: always ports: - "8080:8080" depends_on: - db environment: DATABASE_URL: postgresql://administrator:verySecretPassword@db:5432/project volumes: - .:/app this is my Dockerfile: # Use the official Python image as a base image FROM python:3.10 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /app # Install Django and Django REST Framework RUN pip install --no-cache-dir django djangorestframework # Install system dependencies for psycopg2 (PostgreSQL client) RUN apt-get update && \ apt-get install -y postgresql-client # Copy the requirements file and install dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy the Django project files to the container COPY . /app/ # Install system dependencies for psycopg2 (if necessary) … -
401 (Unauthorized) between my API Django_Rest_Framework and React.js
I have created API with django_rest_framework and I manage user autorisation with jwt_token, I use react.js app for my frontend. In development all request are working, but in production, all my request are coming back with 401 (Unauthorized), except sometimes when I refresh my page many times I can have an ok response. I have two differences between development and production. firstly in development I use sqlite while in production I use postgreSQL. Moreover, in production I have configured my django settings like this : SECURE_HSTS_SECONDS = 31536000 SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD = True SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_NAME = 'sessionid' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 3600 # Durée de vie du cookie de session : 1 heure SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRATION_DATE = datetime.now() + timedelta(days=30) With my react.js app I can see my token refresh and my token access and they are correctly refreshed. Also, my database work good because I can register new user. I have read a lot of error file like gunicorn, nginx or my django app but I don't really know what happened. Also, I have problem with my admin api, … -
Django static files 404 errors just for one folder and all images
I'm integrating a theme into my project. Some of the static files are found, but I get two types 404 errors. I'd appreciate any help. The first type (all images): For the line <img class="rounded-circle" src="{% static 'sleek-bootstrap/source/assets/img/user/u6.jpg" alt="Image' %}"> I get the error "GET /static/sleek-bootstrap/source/assets/img/user/u6.jpg%22%20alt%3D%22Image 404 1958 The file /static/sleek-bootstrap/source/assets/img/user/u6.jpg does exist, but somehow Django adds %22%20alt%3D%22Image to the name, so of course it can't find it. It does this for all the image files in the template The second type (one folder): for the line <script src="{% static 'sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js' %}"> ></script> I get the error "GET /static/sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js HTTP/1.1" HTTP/1.1" 404 1958 Django finds all the files in the path /static/sleek-bootstrap/source/assets/plugins/, except those in the daterangepicker plugin folder.