Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - 403 error while accessing static files in ec2 ubuntu server with nginx
I have used nginx default port 80. Deployed successfully django app. But got 403 error while accessing static files.. I know it is permission related issue. So I tried all the ways. but nothing is workout. gave 777 permission and www-data user. still I got permission denied error. file path structure location /static/ { root /home/ubuntu/FunQuiz-backend/FunQuizAPI/staticfiles/; autoindex on; } -
Is there any way to relay the data(stud.id) to the POST form?
{% for stud in student %} <tr> <td class="text-center">{{stud.id}}</td> <td class="text-center">{{stud.name}}</td> {% if x %} <td class="text-center">{{stud.main_sub}}</td> <td class="text-center">{{stud.fourth_sub}}</td> {% endif %} <td class="text-center"> <div> <a class="btn btn-outline-primary rounded " href="{% url 'updatestudent' stud.id %}" style="width: 0.75in;"> Edit </a> <button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#exampleModal" style="width: 0.75in;"> Delete </button> </div> </td> </tr> {% endfor %} </tbody> </table> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Confirmation</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure want to delete? {{stud.id}} </div> <div class="modal-footer"> <form action="" method="post"> {% csrf_token %} <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <input type="submit" class="btn btn-danger" value="Delete"> </form> </div> </div> </div> </div> Or maybe you could point me to some docs I could read. I'm new into programming and I'm learning based of off what my demo project needs. In this code, I used django templating for loop to loop through all the objects and posted em in a table. table has an option to delete which leads to a popup confirmation. Problem is I couldn't find any way to relay the data from the for loop part to the popup part where the post form is. -
auto-fill a form field with currently logged in user django
i have a form and when rendering should have some of the fields pre-filled and disabled with currently logged-in user, django. This is the rendered django form and under the username field should show only the current logged-in user and not all the registered users. views.py @login_required def teacherRecordForm(request): if request.user.is_authenticated: teacher_form = TeacherRecordForm if request.method == 'POST': teacher_form = TeacherRecordForm(request.POST, request.FILES) if teacher_form.is_valid(): teacher_form.save() messages.success(request, 'Details Saved Successfully') return redirect ('teacher-record-form') else: messages.success(request, 'check your information provided well') return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: return render(request, 'schRecords/teacherRecordForm.html', {'teacher_form':teacher_form}) else: messages.success(request, 'kindly sign in first') return redirect('sign-in') -
In my python django projuct tried to host in godaddy cpanel but the pillow is not installing
In file included from src/libImaging/Imaging.h:688, from src/libImaging/XbmEncode.c:16: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipDecode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipDecode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipDecode.c:18: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" gcc -Wno-unused-result -Wsign-compare -DNDEBUG -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -D_GNU_SOURCE -fPIC -fwrapv -D_GNU_SOURCE -fPIC -fwrapv -O2 -pthread -Wno-unused-result -Wsign-compare -g -std=c99 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Werror=implicit-function-declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF -DHAVE_XCB -DPILLOW_VERSION=\"10.0.0\" -I/usr/include/freetype2 -I/usr/include -I/home/xhpnfadbs797/virtualenv/public_html/shopwithambro.com/3.9/include -I/opt/alt/python39/include/python3.9 -c src/libImaging/ZipEncode.c -o build/temp.linux-x86_64-cpython-39/src/libImaging/ZipEncode.o In file included from src/libImaging/Imaging.h:688, from src/libImaging/ZipEncode.c:17: src/libImaging/ImagingUtils.h:35: warning: 'inline' is not at beginning of declaration cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: unrecognized command line option "-Wno-unused-result" cc1: warning: … -
Django/MSSQL: Issues counting objects depending on attribute
environment: Database: MSSQL Django 3.2.20 mssql-django 1.3 models class ChangeOrder(models.Model): # ...fields... class GroupChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='groupchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... class UserChange(models.Model): order = models.ForeignKey( AssignmentChangeOrder, related_name='userchanges' ) action = models.CharField(max_length=10, choices=['assignment', 'removal']) # ...other fields... objective For each ChangeOrder, I want to annotate/calculate: ant_assignment_count: Count of 'assignment' actions in both GroupChange and UserChange. ant_removal_count: Count of 'removal' actions in both GroupChange and UserChange. query ChangeOrder.objects.annotate( ant_assignment_count=Sum( Case( When(userchanges__action='assignment', then=1), When(groupchanges__action='assignment', then=1), default=0, output_field=IntegerField() ) ), ant_removal_count=Sum( Case( When(userchanges__action='removal', then=1), When(groupchanges__action='removal', then=1), default=0, output_field=IntegerField() ) ) ) objects co = ChangeOrder.objects.create() GroupChange.objects.create(order=co, action='removal', ..) GroupChange.objects.create(order=co, action='removal', ..) UserChange.objects.create(order=co, action='assignment', ..) If I run the query with those created objects I receive ant_assignment_count=2 and ant_removal_count=2. But it should be ant_assignment_count=1 and ant_removal_count=2. I've attempted various methods including annotations, subqueries, and Count with Case statements. However, I'm encountering issues and getting incorrect results. It seems to be a problem with the LEFT OUTER JOIN on GroupChange and UserChange. I'd appreciate any help! -
The cause of the error "List matching query does not exist."
I'm writing a Django auction program, and in the last levels of the program, when I wrote the code to select the winner of the auction and created the corresponding table with sqlite, I encountered this error. After this bug, no products will be displayed on the main page and product information cannot be seen. What is the cause of this error? I changed the names of the columns of the table, but it had no effect, and the rest of the code was working before creating this table. Exception Type: DoesNotExist at /auctions/1 Exception Value: List matching query does not exist. -
Django SearchFilter exists relationship without DISTINCT
Table search is implemented through rest_framework.filters SearchFilter with the addition of DISTINCT, which is not suitable for a large database, how to avoid this, what are the hacks for this class UserList(generics.ListAPIView): queryset = User.objects.order_by('-created') filter_backends=( SearchFilter, DjangoFilterBackend, ) search_fields = ( 'id', 'email', 'comments__id', ) thought about adding annotate(cnt=Count('comments',filter=Q(comments__id__icontains=search)).filter(cnt) to get_queryset, but then it's not clear when to do 'OR' -
Why is the django for traceback happening on my code wsv chapter 7?
File "/Users/russellanderson/Desktop/code/blog/.venv/lib/python3.11/site-packages/django/views/generic/edit.py", line 127, in get_success_url raise ImproperlyConfigured( ^ Exception Type: ImproperlyConfigured at /post/new/ Exception Value: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. -
Search with parent foreignkey, grandparent foreignkey in django-admin
I wanna be able to search a product with the category that isnt directly linked to it but the category is grandfather or great_great grandfather and so on above on the category tree of the category that is actually linked to the product itself. The only way i could implement was with the following which is ofcourse not scalable and proper way to do it: def get_queryset(self, request): queryset = super().get_queryset(request).select_related('brand', 'category', 'category__parent') category_name = request.GET.get('category__name', None) if category_name: # Filter the queryset to include products with the specified category or its ancestors queryset = queryset.filter( Q(category__name=category_name) | Q(category__parent__name=category_name) | Q(category__parent__parent__name=category_name) | # Add more levels as needed based on the depth of your category tree ) return queryset And here are the code as of now: Product``models.py class Product(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True, null=True) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product_images/') category = models.ForeignKey(Category, on_delete=models.SET_NULL,related_name='product_category', null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='product_brand', null=True, blank=True) tags = GenericRelation(TaggedItem, related_query_name='product') ratings = GenericRelation(Rating, related_query_name='product') active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) state = models.CharField(max_length=2, choices=PublishStateOptions.choices, default=PublishStateOptions.DRAFT) publish_timestamp = models.DateTimeField( # means that the publish_timestamp field will not automatically be set to the current date … -
Save the user prompt that is sent from web terminal to django
I am running a terminal on browser using xterm.js. The program sends the input to django working in backend. The code in views.py is a modified version from MahmoudAlyy github page. The input in the pty_input method receives all the keys that user presses. It can be modified to get only the command but it would take a long time and be open to bugs. Is there another way to get only the user prompt by changing frontend or backend code? views.py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, message["rows"], message["cols"]) @sio.event def pty_input(sid, message): if fd: os.write(fd, message["input"].encode()) @sio.event def disconnect_request(sid): sio.disconnect(sid) @sio.event def connect(sid, environ): global fd global child_pid if child_pid: os.write(fd, "\n".encode()) return (child_pid, fd) = pty.fork() if child_pid == 0: subprocess.run("bash") else: print() sio.start_background_task(target=read_and_forward_pty_output) @sio.event … -
How can make api using fastapi for django project
I want my projects to be more faster and i decided to use fastapi for them.But can't import my django models and form to fastapi.can someone help me to make api using fastapi for django projects? any code? (for example blog project) -
Django + Gunicorn: how to run background worker thread?
I need to run a background thread in my Django application. During development i could run a thread that accesses my models launching it from the ready() function inside apps.py: def ready(self): from .tasks.mqtt_worker import MqttHandler mqtt_handler = MqttHandler() th1 = threading.Thread(target=mqtt_handler.task) th1.daemon = True th1.start() In Production using Gunicorn this approach seems to fail.. How can I start a background python thread that accesses some models in my application in production? I am running my app behind nginx like this: /software/cloud/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock iotapp.wsgi:application -
How to edit parents objects as a child?
I have two classes in my project. User has a parent object . class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) parent = models.ForeignKey("self",on_delete=models.DO_NOTHING,related_name='child_sections', blank=True, null=True) class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True)``` Here a parent and the child itself can edit any objects class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ("id","author","caption","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('parent').id == self.context['request'].user.pk return attrs elif attrs.get('id') == self.context['request'].user.pk return attrs raise ValidationError('Unauthorized Request') Here parent can edit its child's object and a user can edit its own object. What I want to do is simple: A child can also edit parents object. Can anyone help me? -
Passing a variable in django class based views by extracting the value from a different model
I have two models namely categoreis and products. on my home page I have listed multiple categories and when I click on any category I want to open new page where products belonging to that category are displayed. I am passing the category_id through the url to products view page. but what I want to extract the category.title by using the category_id and the category model so that I can display it on top of products page. I have attached the code of my model class category(models.Model): title = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title class product(models.Model): name = models.CharField(max_length=50, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,null=True, blank=True ) category = models.ForeignKey(category, on_delete=models.CASCADE) cost = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): # new self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name the best I could do is append the category_id to context, but it isn't helpul in anyway. class products(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_context_data(self, **kwargs): context = super(products, self).get_context_data(**kwargs) context['category'] = self.kwargs['cat_id'] return context I referred to some stackoverflow questions but couldn't find anything helpul. -
How can I pass a list of objects in Django?
stackoverflow! I'm working on small project that make's short links from full urls, but I have the issue. How can I do "GET" method that will be return list of my objects? I wrote "POST" method, but when I tried to write the same thing I got error and my request required to use "full_url" to get data. Model class: class Links(models.Model): full_url = models.URLField(unique=True) short_url = models.CharField( max_length=20, unique=True, db_index=True, blank=True ) requests_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('-created_at'), def save(self, *args, **kwargs): if not self.short_url: while True: self.short_url = ''.join( random.choices( settings.CHARACTERS, k=settings.TOKEN_LENGTH ) ) if not Links.objects.filter( short_url=self.short_url ).exists(): break super().save(*args, **kwargs) def __str__(self) -> str: return f'{self.short_url} -> {self.full_url}' another function from views.py: class LinkAPIView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request): serializer = LinkSerializer(data=request.data) if serializer.is_valid(raise_exception=True): token, status_code = serializer.create( validated_data=serializer.validated_data ) return Response(LinkSerializer(token).data, status=status_code) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Error installing uWSGI always when i try it in linux
when i install uWSGI with: pip install uwsgi raise error: *** uWSGI compiling server core *** [x86_64-linux-gnu-gcc -pthread] core/utils.o x86_64-linux-gnu-gcc: fatal error: cannot execute ‘cc1’: execvp: No such file or directory compilation terminated. ---------------------------------------- ERROR: Failed building wheel for uwsgi my ubuntu: 20.04 python: 3.8.10 also i have installed all required packages like: python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools as general question why i always have problem with uWSGI installation? in every VPS, in every Linux i had error Failed building wheel. I confused why others dont face with this problems! -
xterm.js term.onData is not a function
I am programming a terminal application using xterm.js in frontend and django at backend. Everything works fine but when i try to save the input from the user using onData i get it is not a function error. If you have another approach please tell me. I tried getting current line but run into problems if user press backspace or delete. index html: var socket = io.connect({ transports: ["websocket", "polling"] }); const status = document.getElementById("status") const button = document.getElementById("button") var term = new Terminal({ cursorBlink: true, }); term.open(document.getElementById('terminal')); var curr_line = ''; var entries = []; var currPos = 0; var pos = 0; var prompt_startpos = term._core.buffer.x term.onData(data => { console.log("Data received:", data); socket.emit("pty_input", { "input": data }); }); views py: async_mode = "eventlet" sio = socketio.Server(async_mode=async_mode) fd = None child_pid = None def index(request): return render(request, "index.html") def set_winsize(fd, row, col, xpix=0, ypix=0): winsize = struct.pack("HHHH", row, col, xpix, ypix) fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize) def read_and_forward_pty_output(): global fd max_read_bytes = 1024 * 20 while True: sio.sleep(0.01) if fd: timeout_sec = 0 (data_ready, _, _) = select.select([fd], [], [], timeout_sec) if data_ready: output = os.read(fd, max_read_bytes).decode() sio.emit("pty_output", {"output": output}) else: print("process killed") return @sio.event def resize(sid, message): if fd: set_winsize(fd, … -
Django passing extra context from Form View after working on form fields
So I have a form in which I get some data, and I use this data to retrieve an object from some model. But, I am not able to pass the data I retrieved from this object into the context in the is_valid function. It breaks the success redirect logic. What can I do for this situation? -
How to open any encoding CSV without crashing Python?
I'm working on a Django APP that needs to import a CSV database and generate the products in the system, but depending on the CSV encoding the APP is crashing. I tried a way to read the CSV encoding to vary the way to open it, but it still keeps crashing. -
ModuleNotFoundError: No module named 'log_request_id.filters'
While setting up the environment for project, I am getting this error. ModuleNotFoundError: No module named 'log_request_id.filters' LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "tenant_context": {"()": "tenant_schemas.log.TenantContextFilter"}, "request_id": {"()": "**log_request_id.filters**.RequestIDFilter"}, }, ... } I have tried installing, django_log_request_id and log_request_id, also tried to do some changes. -
How to check if an entry is created with one object in another model in entire django project?
Suppose I have a warehouse model. Now before deleting this warehouse object i wanna check that if this particular object is used in some other model or not? class Warehouse(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=250, default=0) email = models.EmailField(max_length=50, default=0) contact = models.CharField(max_length=50, default=0) address = models.CharField(max_length=500, default=0) now I have 1500 different models in my project so i cannot write a query to check whether it's pk exists in them or not so what's the fastest way to do this ? -
my generic view inherited from CreateView in django does not show model fields to fill out when I run my django project
I create an app in django named 'sampleapp' then in models.py I define my model as follows: from django.db import models from django.urls import reverse class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) mobile = models.CharField(max_length=10) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) and also in forms.py: from .models import Employee from django import forms class EmployeeForm(forms.ModelForm): class Meta: # To specify the model to be used to create form model = Employee # It includes all the fields of model fields = '__all__' then in views.py: from django.shortcuts import render from .models import Employee from .forms import EmployeeForm from django.views.generic.edit import CreateView from django.urls import reverse_lazy class EmployeeCreate(CreateView): model = Employee fields = '__all__' and in urls.py file: from django.urls import path from .views import EmployeeCreate urlpatterns = [ path('', EmployeeCreate.as_view(), name='EmployeeCreate') ] and also I put employee_form.html (an empty html file) in 'myproject/template/sampleapp/employee_form.html'. But when I run my project and go to url "http://127.0.0.1:8000/" I receive an empty html file, a page without any field to fill out (like first_name field last_name field and so on). How can I create an Employee object using django generic view 'CreateView'? -
cannot import name 'load_dotenv' from 'dotenv' with django docker
I try to dockerize django. So I have this Docker file: # pull official base image FROM python:3.9-alpine3.13 # set work directory WORKDIR /usr/src/app EXPOSE 8000 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add linux-headers postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . COPY ./requirements.dev.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh # copy project COPY . . # run entrypoint.sh CMD ["python3", "manage.py", "runserver"] and Docker compose: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - .:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" env_file: - ./.env volumes: dev-static-data: and my requirements.txt looks like: Django>=4.0.4 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-environ django-dotenv http://github.com/unbit/uwsgi/archive/uwsgi-2.0.zip I can build the docker container. But I can't run it. If I do a docker-compose up. I get this error:" Traceback (most recent call last): dwl_backend-app-1 | File "/usr/src/app/./manage.py", line 5, in <module> dwl_backend-app-1 | from DierenWelzijn.settings import base dwl_backend-app-1 | File "/usr/src/app/DierenWelzijn/settings/base.py", line 15, in <module> dwl_backend-app-1 | … -
My code doesnt work. Please check and help me
When you click the Изменить(Edit) button, nothing happens, it seems to be written correctly, but it does not work.I expect that when I click the Изменить(Edit) button, I can change the existing task, save it, and in case of accidental clicking exit. urls.py: from django.urls import path from . import views app_name = 'todoist' urlpatterns = [ path('', views.index, name='index'), path('add', views.add, name='add'), path('delete/<int:today_id>/', views.delete, name='delete'), path('update/<int:today_id>/', views.update, name='update'), path('edit/<int:today_id>/', views.edit, name='edit'), ] views.py: from django.shortcuts import render,redirect from .models import Today from django.views.decorators.http import require_http_methods def index(request): todos = Today.objects.all() return render(request, 'today.html', {'todos':todos}) @require_http_methods(['POST']) def add(request): tasks = request.POST["tasks"] task = Today(tasks=tasks) task.save() return redirect('todoist:index') def delete(request, today_id): todo = Today.objects.get(id=today_id) todo.delete() return redirect('todoist:index') def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.save() return redirect('todoist:index') def edit(request, today_id): todo = Today.objects.get(id=today_id) todo.edit_mode = True todo.save() return redirect('todoist:index') today.html: <title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="{% url 'todoist:add' %}" >{% csrf_token %} <input type="text" name='tasks' pattern=".{2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> <ol> {% for todo in todos %} <div> {% if todo.edit_mode %} <form action="{% url 'todoist:update' today_id=todo.id %}" method="POST"> {% csrf_token %} <input type="text" name="tasks" value="{{ todo.tasks }}"> <button type="submit" class="save btn … -
Post method in Django not allowed
I am trying to send post request via Swagger but I am getting Method Not Allowed Error. Url I use is /add. I think the code is fine but there has to be something I am missing. router = Router() @router.post("/add", response={200: None}) def add_new_breached_data(request, data: DataBreachDto): add_new_breach(data) return 200 Data send in request (DataBreacheDto is created for this type of data): { "platform": "Test", "name": "Test1", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "date": "2023-08-11T09:56:41.604Z", "size": 500 }