Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ngnix not connecting to Django/Gunicon container
I have a backend on DigitalOcean and i get a 502 when connecting to it The Ngnix error: 2023/12/01 10:05:43 [error] 31#31: *507 upstream timed out (110: Connection timed out) while connecting to upstream, client: 141.101.98.150, server: mydomaine.com, request: "GET / HTTP/1.1", upstream: "http://172.27.0.7:5001/", host: "mydomaine.com" Nginx config for dev container: server { listen 80; listen [::]:80; server_name mydomaine.com; return 301 https://$host$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name mydomaine.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; access_log /var/log/nginx/dev_access.log; error_log /var/log/nginx/dev_error.log; location / { proxy_pass http://dev:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Docker compose file: version: "3.7" services: webserver: image: nginx:1.22.0 container_name: webserver restart: always ports: - 80:80 - 443:443 volumes: - ./logs/nginx/:/var/log/nginx/ - ./nginx/ssl/:/etc/nginx/ssl/:ro - ./nginx/configs/:/etc/nginx/sites-enabled/:ro - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro networks: - backend db_prod: image: postgres:15 container_name: db_prod restart: always ports: - "${POSTGRES_PROD_PORT}:5432" volumes: - db_prod:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: #TODO: fix Unsupported config option for services.{service_name}: 'profiles' # - prod networks: - backend db_dev: image: postgres:15 container_name: db_dev restart: always ports: - "${POSTGRES_DEV_PORT}:5433" volumes: - db:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: # - dev networks: - backend prod: build: ./src command: ["./start.sh"] … -
Second Record Occurs When the Form is Resubmitted by Pressing the Back Key from the Browser
When the user fills in the form and saves it, they are redirected to the next page. However, when the user presses the back button from the browser, the completed form is brought to the user from the browser cache. The user thinks that the form has been edited and when he/she makes the necessary edits and resubmits the form, a second record is created in the database. class UserFormView(FormView): def get(self, request, userformmodel_id = None): instance = get_object_or_404(models.UserFormModel, pk=userformmodel_id) if userformmodel_id else None form = forms.UserFormForm(instance=instance) if instance else forms.UserFormForm() context = { 'form' : form, } return render(request, 'formuser.html', context) def post(self, request, userformmodel_id=None): instance = get_object_or_404(models.UserFormModel, pk=userformmodel_id) if userformmodel _id else None form = forms.UserFormForm(request.POST, instance=instance) if instance else forms.UserFormForm(request.POST) if form.is_valid(): form.save(user_id=request.user.id) return redirect('other-page') context = { 'form' : form, I } return render(request, 'userform.html', context) I couldn't find any solution. The only solution is not to redirect the user to another page after submitting the form. -
which is better ajax or websocket for the client to receive 1 message from the server?
I have a Django site for processing pdf files. The user uploads the file and indicates what to do with it, after which the file is sent to the server and transferred to the celery task. Meanwhile, I redirect the user to the page with the loader and he waits for the result to arrive (a link to download the result should appear). And I had a question - how can I send a message (a link to download the result) to the client from the server when the task is completed - establish a websocket connection in order to send or use ajax constantly asking the server if there is no result yet? I have the following selection criteria: an instant message from the server is not mandatory for me (there may be a delay of 2-3 seconds); the duration of file processing will take a maximum of 10-15 seconds; if I use ajax, I will send requests to the server every 2 seconds; I need to choose an option that will be less expensive in terms of resources. I've read a lot about these technologies, but I couldn't figure out what would be better. I will be grateful … -
I am building a website about group budgeting something in Django. Remark "pending, "not pending", "paid" not working well
If i am using an admin account, i want my remark to be "Paid" if all members submitted a proof file and otherwise, "Pending". And if i am using a member account, i want my remark to be "Paid" if i submitted a proof file and otherwise, "Not Paid". Now, the problem is even though all members submitted proof, the remark is still "Pending" same with inside the members account, the remark is "Not Paid" although it has submitted proof. Can anyone help me fix this please. I am in rush. Models.py class bills(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) amount = models.IntegerField() remarks_admin = models.CharField(max_length=255, default="") remarks_member = models.CharField(max_length=255, default="") title = models.CharField(max_length=30) due = models.DateTimeField(null=True) assigned = models.DateField(auto_now=True) slug = models.SlugField(null=False, blank=False, default="") class Submission(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bills = models.ForeignKey(bills, on_delete=models.CASCADE) proof = models.FileField(null=True) bills.html ```{% extends "base/base.html" %} {% block content %} <div class="container"> <div class="row justify-content-center align-items-center" style="height: 100vh;"> <div class="col-md-6"> <h1 class="text-center">{{ room.title }}</h1> <div class="form-group text-center"> <p>Room Code: <br><b>{{ room.join_code }}</b></p> </div> <a href="{% url 'post-bills' room_id=room.join_code %}"> <button type="button" class="btn btn-primary btn-lg">Add Bills</button> </a> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Amount</th> <th scope="col">Due Date</th> <th scope="col">Remarks</th> </tr> </thead> <tbody> … -
got problem with the websocket with python/django
Im trying to make notification for my project but Im having problem with my DB and api first Im using postgreSQL but my models.py does not upload on db second so I made db on admin page and it actually uploaded on my db so I checked on my developer's tool, they did actually brought API but empty so I need help on those 2 issues can't upload notification models on pgadmin when I leave a comment on my project when I passively upload data at db on admin it worked but still API is empty here are some of my project works Thank you views.py class NotificationCreate (APIView): # 로그인 한 유저만 가능 permission_classes = [IsTokenValid] # IsTokenValid 권한을 적용 def post(self, request): print("Notification_post") content = request.data.get('content') notifications = Notifications(content=content) notifications.save() serializer = NotificationSerializer(notifications) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self,request): print("Notification_get") notifications = Notifications.objects.all() serializer = NotificationSerializer(notifications, many=True) return Response(serializer.data, status=status.HTTP_200_OK) class CommentCreateAPIView(APIView): permission_classes = [IsTokenValid] def post(self, request, study_id, story_id): print("Comment_post") # 사용자로부터 댓글 내용을 받아옵니다. content = request.data.get('content') article_type = request.data.get('article_type') # 'study' 또는 'story' article_id = request.data.get('article_id') # 게시물의 ID user = get_user_from_token(request) # 실제로 댓글을 생성하고 데이터베이스에 저장하는 코드 (예시) # Comment 모델이 있다고 가정하고 사용자 … -
Add appointment funtionality for my django app using Google calendar API
i am working on django app where patient and doctor interact , i want to add appointment funtionality for patient. Details: 1.The patient user should be able to see a list of all the doctors in the system 2.Each list item should have: Profile picture Name A button “Book Appointment” 3.Upon clicking that button the patient user should see a form with following: Required speciality Date of Appointment Start Time of Appointment A confirm button 4.Each appointment will be of 45 mins 5.When user clicks on confirm a calendar event has to be created for the doctor user 6.On confirmation the patient should see a screen with the appointment details: Doctors Name Appointment date Appointment start time Appointment end time(to be calculated by the application) here my code link :https://github.com/geetanshpardhi1/intern_task_1 Please help me to code. -
Accss ManyToMany through model attribute for spcific row in drf serilizaer
I'm using Django 4.2 with Django-rest-framework and I need some help with returning a serialized object. I have 2 models that have many to many relationship using a through model to hold a bit more logic I want to return a serialized object that includes an extra attribute from the through model. How can I do that? My models: class Chart(models.Model): name = models.CharField(max_length=255, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: ordering = ['id'] def __str__(self): return self.name class MonitoredFlow(models.Model): name = models.CharField(max_length=255, unique=True) charts = models.ManyToManyField(Chart, through="ChartFlows", related_name="monitored_flows", through_fields=("monitored_flow", "chart") ) class Meta: ordering = ['id'] def __str__(self): return self.name class ChartFlows(models.Model): chart = models.ForeignKey(Chart, on_delete=models.CASCADE) monitored_flow = models.ForeignKey(MonitoredFlow, on_delete=models.CASCADE) is_visible = models.BooleanField(default=True) class Meta: ordering = ['id'] def __str__(self): return f"{self.chart.name}: {self.monitored_flow.name}" When retrieving a Chart object, I would like to know for the monitored flow if he is visible (or not) on the specific chart. I would like to get from my view or serializer an object that looks something like this: { "id": 1, "name: "some chart name", "monitored_flows": [ "id": 1, "name": "some flow name", "is_visible": true ] } My challenge is how to add the is_visible attribute from the through model. Thanks for the … -
Django user authentication with phone and Email
I want to customize my Django user authentication system so users can sign up/in with both phone number and email (OTP and password). What should I do? How can I customize my user model? Should I use AbstractUser or AbstractBaseUser or something else? -
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile uploading file by Django [closed]
I am getting this error to upload my file to google drive I am uploading excel file, but it works fine if I upload .py or .txt gauth = authenticate() drive = GoogleDrive(gauth) gfile = drive.CreateFile({'parents': [{'id': config('ID')}]}) # gfile['title'] = file_name gfile.SetContentFile(uploaded_file) gfile.Upload() -
Django file uploading function can run in localhost but can't run in EC2 instance of AWS
So I'm trying to create a chatbot webapp that can do data analysis from an excel, csv, google spreadsheet, and all sorts. It's good when I ran it in the local anaconda environment, and now I want to set it up in the AWS EC2. But then things happen, you see when I get it run in the locals it doesn't give error on the inspect and then comes this new 2 error: POST https:/demo.myapp.company/upload/ 500 (Internal Server Error) Error uploading file: Error: Network response was not ok Internal Server Error at (index):646:16 But in my local anaconda environment it doesn't yield that, as a matter fact it always successfully uploaded files with no fail (around 50 times as per now without any error). I asked openai's chatgpt and says this error falls on the server side and has nothing to do with the code so then I tried using all 12 suggestions and nothing worked, anyone familiar with this kind of error? The app pipeline will look like this: User clicked the upload button and select the excel file, here's how the file is handled in django: On the views.py: import requests, boto3, pandas, etc. def file_upload(request): act = … -
How to expire / invalidate simple jwt token in Django rest framework
How can I invalidate the user token when the user status changes (banned/inactive) by the admin? I am new to Django. -
Django websocket code is skipped when running server via nginx and asgi
In our code, AsyncJsonWebsocketConsumer.send_json() works fine when we are running the server via Django runserver but gets skipped when it is ran via nginx and asgi. This is the calling code and it is within an api view: async_to_sync(channel_layer.group_send)( 'office_id_{}'.format(patient.office.pk), { 'type': 'message_received', 'patient_id': patient.id, } ) message_received looks like this: async def message_received(self, event): await self.send_json(event) What do we have to do to get this to work under nginx and asgi? Thanks, -
Prevent Django management commands from stripping out quotes from arguments
I have a Django management command mycommand.py with an argument that accepts a JSON-formatted string, like: from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('json_str') def handle(self, json_str, **options): print('json_str:', json_str) However, if I run this from Bash: python manage.py mycommand '[123, "abc"]'` the output I see is: [123, abc] which is invalid JSON since the quotes have been stripped out. Is this being done by Bash or by Django, and how do I stop it? Attempting to use \ to escape the quotes in Bash has no effect. -
Can't delete Celery Task
I'm having a very weird Issue, I mounted a Django app with Docker, and added a Redis DB to implement Celery tasks, now, yesterday everything was working perfectly, but today I created a new task to test, and now I can't get rid of it, it is on a permanent state of pending, and doesn't matter what I do, I can't stop current_app.AsyncResult(task_status.task_id) from returning it with the pending state. I've tried to remove it celery -A proj purge, current_app.control.purge(), task.revoke(), and current_app.control.revoke(task.id, terminate=True). But despite that it is still returning it. This is how my Redis DB looks like now: There are no tasks ids, Am I doing something wrong, or is there something that I'm misunderstanding? My structure looks something like this: docker-compose.yml version: "3.3" networks: backend: driver: bridge services: django: image: "test:latest" command: python manage.py runserver env_file: - .env volumes: - .:/app ports: - ${PORT_OUT}:8000 networks: - backend links: - db - redis depends_on: - db - redis db: # DB parameters celery: image: "test:latest" command: celery -A djangoproject worker -l debug env_file: - .env volumes: - .:/app networks: - backend links: - db - redis depends_on: - django - redis - db redis: image: "redis:7.0" container_name: … -
AWS App runner - Django - migrations after deploy fails
AS part of the development model changes are made and prepared with makemigrations. When deploying this code to another instance (via Git) the migrations need to be run on the database of the instance. I have configured the apprunner.yaml file as: ['''version: 1.0 runtime: python3 build: commands: build: - pip install -r requirements/production.txt post-build: - source /var/app/venv/*/bin/activate - python manage.py migrate - deactivate run: runtime-version: 3.8.16 command: sh startup.sh network: port: 8000'''] I've also tried it without the 'post-build' section. startup.sh contains: '''#!/bin/bash gunicorn config.wsgi:application''' also tried a version of the startup.sh with below - also fails '''#!/bin/bash python manage.py migrate && gunicorn config.wsgi:application''' Log: 12-01-2023 10:05:40 AM [AppRunner] Reading apprunner.yaml config file. 12-01-2023 10:05:40 AM [AppRunner] Successfully Validate configuration file. 12-01-2023 10:05:42 AM [AppRunner] Starting source code build. 12-01-2023 10:09:00 AM [AppRunner] Service update failed. For details, see service logs. I've tried variants of the yaml file as mentioned, one without the post-build, a post-build with on,y the Python... line, variants of the startup.sh file as above. I've also tried using just the build settings it falls back on to change the start command from gunicorn config.wsgi:application to Python manage.py migrate && gunicorn config.wsgi:application. All just fails and rolls … -
Django 4.0.10 Migration Error: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name'
I am experiencing a migration issue in Django 4.0.10 using Python 3.12.0 and PostgreSQL as my database. The error occurs during the migration process and seems to be related to ManyToManyField attributes in my CustomUser model. Error message: AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name' This issue arises when I run python manage.py migrate. It seems to be triggered by a specific migration file that modifies ManyToManyField relationships. Here are the relevant parts of my CustomUser model from models.py and the problematic part of the migration file: models.py (CustomUser model excerpt): class CustomUser(AbstractUser): # Basic personal information height = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, help_text="Height in centimeters") weight = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True, help_text="Weight in kilograms") # Health and dietary information activity_level = models.CharField(max_length=50, choices=[('sedentary', 'Sedentary'), ('light', 'Light Activity'), ('moderate', 'Moderate Activity'), ('active', 'Active'), ('very_active', 'Very Active')], default='sedentary', help_text="Activity level of the user") health_goal = models.CharField(max_length=100, choices=[('lose_fat', 'Lose Fat'), ('gain_muscle', 'Gain Muscle'), ('maintain_weight', 'Maintain Weight'), ('improve_fitness', 'Improve Fitness')], default='maintain_weight', help_text="Primary health goal") dietary_restrictions = models.ManyToManyField('DietaryRestriction', blank=True) food_preferences = models.ManyToManyField('FoodItem', blank=True) # Nutritional needs daily_caloric_intake = models.IntegerField(null=True, blank=True, help_text="Recommended daily caloric intake") daily_protein_needs = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text="Recommended daily protein intake in grams") daily_carb_needs = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text="Recommended daily … -
Get access to the last object from foreign key
My models are here: class UserToPackageMeta(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="package_metas" ) package = models.ForeignKey( "platforms.Package", on_delete=models.RESTRICT, related_name="user_metas" ) class Package(models.Model): platform = models.ForeignKey( Platform, on_delete=models.CASCADE, related_name="packages" ) class Platform(models.Model): slug = models.CharField(max_length=125, blank=True, null=True) I want to write a query to get users based on platfrom slug on last package they have because any user can have diffrante packages: I tried this: users = users.filter(package_metas__package__platform=platform) But this won't consider only the last package for each user. -
why is my signup and login not created and authenticated when I put it in the same function in my django project?
initally I seperate the registration and loginUser function on my views.py, which work just fine creating the user. user created on DB and logout also works fine. but I had problems with the login that it won't log the user in withou giving any error alert. I figured that me putting the login and signup form in the same html file might be the problem so I tried to merge the register and loginUser function def registerUser(request): form = CreateUserForm() if request.method=="POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + form.cleaned_data.get('username')) email = form.cleaned_data.get('email') Customer.objects.create(username=User.objects.get(username=user), email=email) return redirect('register') context={'form':form} return render(request, 'store/register.html',context) def loginUser(request): if request.method =="POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return redirect('store') else: messages.info(request, 'Incorrect username or password') context={} return render(request, 'store/login.html',context) here are the merged function views.py from django.shortcuts import render, redirect from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect import json import datetime from .models import * from . utils import cookieCart, cartData, guestOrder # for userCreation from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .forms import CreateUserForm, LoginForm from django.contrib import messages # authenticate user from django.contrib.auth import authenticate, … -
running django makemigrations twice generates two migrations, one to add a field and one to alter that same field … to itself
One would expect that running makemigrations twice in a row would be a no-op for the second one, but in fact I get two migrations, and the second one can't be applied (an exception is thrown trying to access None.startswith). Output somewhat sanitized: % ./manage.py makemigrations Migrations for 'foo': foo/migrations/0004_foo.py - Add field foo to bar % ./manage.py makemigrations Migrations for 'foo': fooo/migrations/0005_alter_foo.py - Alter field foo on bar The contents of the migrations are basically: operations = [ migrations.AddField( model_name="bar", name="foo", field=models.ForeignObject( default=1, from_fields=["original_id", "original_date"], on_delete=django.db.models.deletion.PROTECT, related_name="+", to="foo.baz", to_fields=["id", "date"], ), preserve_default=False, ), for the first, and then the "alteration": operations = [ migrations.AlterField( model_name="bar", name="foo", field=models.ForeignObject( from_fields=("original_id", "original_date"), on_delete=django.db.models.deletion.PROTECT, related_name="+", to="payment.payment", to_fields=("id" "date"), ), ), ] Attempting to run the migration results in: File "/Users/wolfson/.local/share/virtualenvs/message_digest-gQFszokA/lib/python3.11/site-packages/django/db/backends/postgresql/operations.py", line 189, in quote_name if name.startswith('"') and name.endswith('"'): ^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'startswith' -
Error 500 rom Djanjo when trying to send my form data in JavaScript to my Django Url
I am trying to build a ToDo List in Djanjo and I am having issues while trying to build the edit view functionality, below is my home.html file <div class="col-md-7 col-lg-7" style="height: 450px; overflow: scroll;"> <!-- List of all the tasks for the day --> {% for task in tasks %} <div class="card m-1"> <div class="card-body"> <span id="task_{{ task.pk }}_text">{{ task.task }}</span> <span style="position: relative; float: right;"> <a href="{% url 'mark_as_done' task.pk %}"class="btn btn-success"><i class="fa fa-check"></i> Mark as Done</a> <a href="{% url 'delete_task' task.pk %}" class="btn btn-danger"><i class="fa fa-trash"></i></a> <!-- When this button is clicked, a textbox/form will appear, after it appears and you press submit task is updated --> <a onclick="showTextBox('{{ task.pk }}')" class="btn btn-primary"><i class="fa fa-pencil"></i></a> <form id="textbox_{{ task.pk }}" onsubmit="saveValue(event, '{{ task.pk }}')" method="post"> {% csrf_token %} <input type="text" id="inputValue_{{ task.pk }}" name="edited_task" placeholder="Update task"> <input type="submit" value="Submit"> </form> </span> </div> </div> {% endfor %} </div>`` Next is my script, where I try to send the data to the backend <script> function showTextBox(key){ /*console.log(100); console.log(`textbox_${key}`);*/ var textbox = document.getElementById(`textbox_${key}`); textbox.classList.toggle('hidden-textbox'); } function saveValue(event,key){ /*each task object has a primary key associated to it*/ event.preventDefault(); var primary_key=key; var enteredValue = document.getElementById(`inputValue_${primary_key}`).value; const base="{% url 'edit' 123 %}".slice(0, -4); … -
Problems with pyenv virtualenv and Django 1.6
I installed python 2.7 using pyenv to run an older project that still uses Django 1.6, but I can't get the path to work. Even thou I have the virtualenv that I created with 2.7 activated, and all pip requirements installed, whenever I try to run the project I get the following error: ImportError: Could not import settings '***.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named objects *Name of the project was replaced by *** When I try and print the os path I get this result: \<module 'posixpath' from '/Users/userx/.pyenv/versions/2.7.18/lib/python2.7/posixpath.pyc'\> Instead of getting the directory for the Django project. Does anyone know how can I get a python version installed with pyenv to run on the correct directory? ps.: already tried this ImportError: Could not import settings and already tried this Issues with pyenv-virtualenv: Python and PIP not changed when activating / deactivating virtual environment and everything regarding pyenv init settings and path -
Server Error (500) on django app production
I am trying to deploy a Django Application on Render. In my project, I have some number of apps that have their own urls file. Then, in the project's url, I included them. Have a look at the project's url: urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('about/', include('about.urls')), path('services/', include('services.urls')), path('teams/', include('team.urls')), path('contact/', include('contact.urls')), path('kbdash/', include('management.urls')), path('auth/', include('users.urls')), ] And for every app the url looks like this: urlpatterns = [ path('', about_page, name='about'), ] all these urls work except for the path('kbdash/', include('management.urls')) kbdash/ is for managing all url in management app. Below is the url of management app: urlpatterns = [ path('', views.Dashboard.as_view(), name='dashboard'), path('fuels/', views.fuel_list_view, name='fuel_list'), path('fuels/manage/', views.manage_fuel_view, name='manage_fuel'), path('fuels/manage/<int:pk>/', views.manage_fuel_view, name='manage_fuel_edit'), path('fuels/add/', views.save_fuel_view, name='save_fuel'), path('fuels/detail/<int:pk>/', views.fuel_detail_view, name='fuel_detail'), path('fuels/delete/<int:pk>/', views.fuel_delete_view, name='delete_fuel'), path('stocks/', views.stock_list_view, name='stock_list'), path('stocks/manage/', views.manage_stock_view, name='manage_stock'), path('stocks/manage/<int:pk>/', views.manage_stock_view, name='manage_stock_edit'), path('stocks/add/', views.save_stock_view, name='save_stock'), path('stocks/detail/<int:pk>/', views.stock_detail_view, name='stock_detail'), path('stocks/delete/<int:pk>/', views.stock_delete_view, name='delete_stock'), path('inventory/', views.inventory_view, name='inventory'), path('sales/', views.sales_list_view, name='sales'), path('sales/manage/', views.sales_manage_view, name='manage_sale'), path('sales/manage/<int:pk>/', views.sales_manage_view, name='manage_sale_edit'), path('sales/add/', views.sales_save_view, name='save_sale'), path('sales/detail/<int:pk>/', views.sales_detail_view, name='sale_detail'), path('sales/delete/<int:pk>/', views.sales_delete_view, name='delete_sale'), path('sales/report/', views.sales_report_view, name='sales_report_page'), path('sales/report/<str:report_date>/', views.sales_report_view, name='sales_report') ] all the urls in main urls file are working except for the kbdash/ Visiting kbdash/ and any link under kbdash/ throw Server Error (500) I have no idea why … -
Forbidden (CSRF cookie not set.): api/endpoint/ 403
I'm trying to implement getting information from a form. My stack: Vue and DRF. The problem is that I implemented receiving information from the form to the server, but without a CSRF token. Then I wanted to include the decorator in APIView. ` @method_decorator(csrf_protect, name='dispatch') class LiteContactView(APIView): permission_classes = [permissions.AllowAny] def post(self, request): serializer = LiteContactSerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data['phone_number'], serializer.validated_data['full_name']) message = _('Message was sent succesfully') return Response({'message': message}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ` On vue file i am using axios ` if(!this.error.lenght) { axios .post(`${this.$i18n.locale}/submit-contact/`, this.form) .then(response => { this.form.full_name = '' this.form.phone_number = '' this.message = response.data.message; this.$emit('submitLightForm', response.data) }) .catch(error => { console.log(error) }) } ` My settings.py file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:5173', ] CSRF_TRUSTED_ORIGINS = ['http://localhost:5173'] I tried different options to get a token with a cookie but I couldn’t get it! That's my error Forbidden (CSRF cookie not set.): -
I am trying to transfer data to the server in the database from the front (react)
I'm just learning react and I can't transfer some data to the server in any way, they come with a null value. Here's an example, I select a category from the list, but an empty value (null) comes, that's what json shows in the browser console. The same is true in the database in the column "case_category_id" the value is null Example of output in the browser, after saving the card { "original_name": "7", "author": null, "case_category": null, "article": 100, "pub_date": "2023-11-30T10:24:08.346215Z", "preliminary_hearing": "2023-01-01" } The code itself import React, { useState, useEffect } from 'react'; import axios from 'axios'; import MyInput from './UI/input/MyInput'; import MyButton from './UI/button/MyButton'; const AddBusinessCard = ({ create }) => { const [formData, setFormData] = useState({ original_name: '', author: '', case_category: '', article: '', pub_date: '', preliminary_hearing: '', }); const [categoryList, setCategoryList] = useState([]); useEffect(() => { axios .get('http://localhost:8000/business_card/category/') .then(response => { setCategoryList(response.data); }) .catch(error => { console.error('Error fetching category list:', error); }); }, []); const handleChange = event => { const { name, value } = event.target; setFormData(prevState => ({ ...prevState, [name]: value, })); }; const handleSubmit = event => { event.preventDefault(); if (!formData.case_category) { console.error('Please select a category.'); return; } const formattedData = … -
Optimizing python function
Somebody can tell me why this takes 3 seconds, is to show a list of new products i already have all the fks in prefetch/select related @cached_property def products(self): return Product.catalogo.base() def new_products(self): """ queryset de productos nuevos de la categoría base """ products = self.productos random_qty = 16 products_ids = [x.id for x in products] last_product_id = products_ids[-1] qty = last_product_id - settings.CANT_PRODUCTOS_PARA_NOVEDADES ids = [x.id for x in products if x.id >= qty and x.stockrecords.all() and x.images.all()] if ids and len(ids) >= random_qty: ids = random.sample(ids, random_qty) return [x for x in products if x.id in ids] how can i optimize this