Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a list of category pills for a media blog?
Why isn't it possible for two media articles, created from a Django model (called MediaModule), who have two separate sets of categories? I have a TextField which contains a list of related categories, separated by a comma. I just want to be able to list those categories in my Django template. Why do my articles keep getting the same categories despite having a separate word list in my Django database? models.py: from django.db import models import uuid, random, string def generate_unique_id(charlimit): '''This will generate a random set of numbers and letters which will be used to generate a unique URL for each object in the model. ''' random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=charlimit)) # Generates a random string return f"{random_string}" def generate_unique_uuid(): '''This will generate a random set of numbers and letters which are to be derrived from the UUID methodology, which will be used to generate a unique URL for each object in the model. ''' return str(uuid.uuid4())[:8] # Create your models here. class MediaModule(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_identifier = models.CharField(max_length=50, default=generate_unique_id(12), unique=True, editable=False) article_headline = models.CharField(max_length=100) article_body = models.TextField() article_synopsis = models.TextField(null=True) article_journalist = models.CharField(max_length=20) article_date = models.DateTimeField(auto_now=True) article_image = models.ImageField(upload_to='assets') article_image_summary = models.TextField(default="", null=True, blank=True) … -
Why is the data not displayed in django rest framework?
Good afternoon I ran into the problem that the data on the page with json is not displayed. models class Example (models.Model): Text = models.TextField(null=True) def __str__(self): return self.Text[0:50] serializers class ExampleSerializer(ModelSerializer): class Meta: model= Example fields='__all__' View class ExampleAPI(viewsets.ModelViewSet): queryset= Dictionary.objects.all() serializer_class = ExampleSerializer def get_paginated_response(self, data): return Response(data) url routExample= routers.SimpleRouter() routExample.register(r'ExampleAPI', views.ExampleAPI) urlpatterns = [ path("ExampleAPI/", include(routExample.urls)), ] But the data is still not displayed but they are present in admin And even the linked model has data in json format -
I have bugs in Voice recognition using tflight model in python using django
import os import numpy as np from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import tensorflow as tf from django.shortcuts import render from django.conf import settings import logging # 모델 파일 경로 설정 logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) def initialize_interpreter(): interpreter = tf.lite.Interpreter(r"C:\Users\Yaggo\OneDrive\Desktop\py\django\advan\audio_project\model.tflite") interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() return interpreter, input_details, output_details def home(request): return render(request, 'audio_app/audio_recorder.html') @csrf_exempt def upload_audio(request): try: if request.method == 'POST' and request.FILES.get('audio_data'): audio_file = request.FILES['audio_data'] audio_data = np.frombuffer(audio_file.read(), dtype=np.int16) # 데이터 길이가 int16의 크기로 나누어 떨어지는지 확인 if len(audio_data) % 2 != 0: audio_data = audio_data[:-1] # 마지막 바이트 제거 # 데이터 정규화 및 모델 입력 크기 조정 audio_data = audio_data.astype(np.float32) / 16384.0 #32768.0 interpreter, input_details, output_details = initialize_interpreter() print(f"Model input shape: {input_details[0]['shape']}") if audio_data.size < input_details[0]['shape'][1]: audio_data = np.pad(audio_data, (0, input_details[0]['shape'][1] - audio_data.size), 'constant') elif audio_data.size > input_details[0]['shape'][1]: audio_data = audio_data[:input_details[0]['shape'][1]] audio_data = np.reshape(audio_data, input_details[0]['shape']) # TensorFlow Lite 모델 실행 interpreter.set_tensor(input_details[0]['index'], audio_data) interpreter.invoke() # 예측 결과 가져오기 output_data = interpreter.get_tensor(output_details[0]['index'])[0] print("Model output:", output_data) logger.debug(f"Model output: {output_data}") return JsonResponse({ 'audio_data': audio_data.tolist(), # audio_data 값을 반환 'predicted_indices': output_data.tolist() # JSON 직렬화 가능한 형태로 변환 }) else: return JsonResponse({'error': 'No audio file provided'}, status=400) except Exception as e: logger.error('Error processing audio file: %s', str(e)) return JsonResponse({'error': … -
Django q in python anywhere ignores every functionality inside of it but finished without issue just in sync: True - mode
I have a extremely strange behaviour with my django q taks. When i start running a task, all the actions inside the function that is wropped with the async_task - wrapper will be ignored BUT just when set "sync": False / default. If i set sync: True everything works perfectly (but sync). Here is my base config: Q_CLUSTER = { 'name': 'DjangoRedis', 'workers': 1, # one worker will get worked on by time 'timeout': 1200, 'retry': 1400, #"recycle": 500, # ow many tasks each worker should handle before taking a break. # "cpu_affinity": 1, requires psutil "max_attempts": 4, "save_limit": 0, "guard_cycle": 1, #"sync": False, #"compress": True, #"catch_up": True, # if sys break catched tasks get restarted -> default true 'queue_limit': 70, 'bulk': 5, "poll": 0.2, # How often to check for new tasks. 'redis': { 'host': REDIS_PUBLIC_ENDPOINT, # 'port': REDIS_PORT, 'db': 0, 'password': REDIS_DB_PASSWORD, #'socket_timeout': None, } } I also ahve prepared a gist file here shows the simplified workflow: https://gist.github.com/wired87/5e64fc79d3aa84cdad87ef7803f508ce But i think the behaviour must come form somewhere else. play around with dj q fields checked all tasks djangos admin terminal -> the task is alltimes successfull -
How does state parameter protects in Oauth 2.0?
Good afternoon Please clarify to me how the state parameter in the URL protects when using oauth 2.0. When a client wants to authenticate in My Django application, it issues a request to the oauth server with an encrypted or signed state parameter. On the authentication server, the client enters the username and password and if they match, the authentication server redirects the client back to my application using a GET request containing the “code” parameter and the same state . My application receives this request, checks the state and sends a new request to the authentication server containing the “code”, state and secret (which I received in advance from the administration of the authentication server). The authentication server checks the secret and state and issues an access token to my application. Question: What function does state perform? If I understand correctly, between steps 1 and 2 my request can be intercepted and state can simply be easily copied, even in encrypted form, and pasted into a fake request. The authentication server does not check the state for a signature and does not try to decrypt it... What does it protect against? I try tio understand how it works -
In my django project I added this in my allowed host but still getting this error I am using zappa for uploading into AWS Lambda [closed]
django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'xyz.ap-south-1.amazonaws.com'. You may need to add '.xyzamazonaws.com' to ALLOWED_HOSTS. [1717411490792] [ERROR] 2024-06-03T10:44:50.778Z c139cd72-2799-426b-8699-df103ac5ec01 Invalid HTTP_HOST header: 'xyz.ap-south-1.amazonaws.com'. You may need to add 'xyz.amazonaws.com' to ALLOWED_HOSTS. -
Validating fields with PrimaryKeyRelatedField
I am working with a DRF serializer which includes a field with the PrimaryKeyRealtedField. import stripe from rest_framework import serializers from subscriptions.models.subscription_product import SubscriptionProduct class SubscriptionCheckoutSessionSerializer(serializers.Serializer): url = serializers.CharField(read_only=True) success_url = serializers.CharField(write_only=True, required=False) cancel_url = serializers.CharField(write_only=True, required=False) subscription_product = serializers.PrimaryKeyRelatedField( queryset=SubscriptionProduct.objects.all() ) def create(self, validated_data): print(validated_data) subscription_product = validated_data["subscription_product"] print(subscription_product) stripe_price = subscription_product.stripe_price print(stripe_price) print(stripe_price.stripe_id) session = stripe.checkout.Session.create( success_url=validated_data.get("success_url", None), cancel_url=validated_data.get("cancel_url", None), mode="subscription", line_items=[ { "price": stripe_price.stripe_id, "quantity": 1, } ], ) print(session) return session The print statements all print their expected output and the created session is a valid one. However, I get a 500 status code with the following error: KeyError: "Got KeyError when attempting to get a value for field subscription_product on serializer SubscriptionCheckoutSessionSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the Session instance.\nOriginal exception text was: 'subscription_product'." Does anyone know what this error actually means and how to solve it? I don't understand how it's possible that the print statements work as expected but I still get a key error. -
not able to quit django server on windows pc
I installed Django just 10 minutes back on my Windows 11 PC and I was trying out this command from a tutorial in a virtual environment i created using anaconda python manage.py runserver and this is what i got Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. June 03, 2024 - 16:21:24 Django version 4.2.13, using settings 'chaiaurDjango.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. now my keyboard doesn't have the break key and I am trying both ctrl+c and ctrl +z but the server wont quit, and neither the command prompt is taking any inputs its just stuck there whatever I type doesn't show on the command prompt, How do i quit the server -
django.db.utils.OperationalError: no such column: media_mediamodule.article_pill
I had decide to add a new views to my Django model name MediaModule. Previously, and as per procedure, you add a new field, give is a default value to it can populate the new field with a value for all existing objects in your Model. However Django is telling me that my new field does not exist: django.db.utils.OperationalError: no such column: media_mediamodule.article_pill This takes place when I run py manage.py makemigrations I thought it was a migrations issue, so I deleted all migration files from the migrations folder and deleted everything except for the __init__.py file. I commented out the relevant field & it has no issue. I checked the database schema and it returned the following result: ('CREATE TABLE "media_mediamodule" ("uuid" char(32) NOT NULL PRIMARY KEY, "article_headline" varchar(100) NOT NULL, "article_body" text NOT NULL, "article_synopsis" text NULL, "article_journalist" varchar(20) NOT NULL, "article_date" datetime NOT NULL, "article_image" varchar(100) NOT NULL, "article_image_summary" text NULL, "article_identifier" varchar(50) NOT NULL UNIQUE)',) >>> But it wouldn't include the new field because it would not allow me to further diagnose the issue until I removed it. Why is this happening? I have cleared the cache, I have cleared the migration history and initiated a … -
Django Session And Cookie
I need a usage example of django session and cookies. Not about Django's interval use of cookies for authentication purposes. request.session.set() request.session.get() request.cokkie how to do all these things??! How to set a session variable properly? How to get that variable in different view? And in client side (frontend) with js? And so for cookies.. -
"django.db.utils.OperationalError: no such column: media_mediamodule.article_new_field" umm... duh?
Yet, another stupid, pointless message from the wonderful Django. Why am I getting the following message when I run the makemigrations command: django.db.utils.OperationalError: no such column: media_mediamodule.article_new_field Is this not a "Duh" moment? I'm trying to add a new bloody category and it's telling me that the column does not exist. Well it would bloody exist if you stopped faffing with silly, pointless "error" messages, and let me add the bloody column. It's like going into a supermarket for a pack of sugar and the store tells you that you don't have a pack of sugar. Um duh - that's why I'm going to the supermarket. from django.db import models import uuid, random, string def generate_unique_id(charlimit): '''This will generate a random set of numbers and letters which will be used to generate a unique URL for each object in the model. ''' random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=charlimit)) # Generates a random string return f"{random_string}" def generate_unique_uuid(): '''This will generate a random set of numbers and letters which are to be derrived from the UUID methodology, which will be used to generate a unique URL for each object in the model. ''' return str(uuid.uuid4())[:8] # Create your models here. class … -
What should I learn after python? [closed]
I'm a beginner programmer. I started with Python, and it's been a month and some since I finished the full Python tutorial. I've also worked on some projects on my own, and not only that, I've modified some projects from other ideas as well. So, what should I learn next? Although I'm not quitting Python, my friend suggested that I should learn Django, but I'm not really into web development. Maybe I'm interested in A.I. or machine learning. So, for that, what should I learn next? My bachelor's in computer science will be held next August. Should I learn other languages like Java or C++, or should I stick with one and focus on related studies? What's your opinion? What should I learn next in programming after completing a Python tutorial if I'm interested in AI and machine learning? -
Numbering 1-4 in django template
I want to increase the number 1 to 4 in django template. How will I do it? enter image description here <span class="number">1</span> I thought it was a work of For Loop, but I couldn't with that. I need help. -
Is there a way to limit the default number of items shown in the Django admin UI to not show all?
I have filters for year_record, age_category, and malnutrition_category. I want the default data shown in my Django admin UI list to correspond to the first value in each filter list. Additional data should only appear when filters are applied or when searching class ProvincialLevelAdmin(ImportExportModelAdmin): resource_classes = [ProvincialLevelResource] list_display = ( 'id', 'province_name', 'percentage', 'forcast_accuracy', 'malnutrition_category', 'year_record', 'age_category', 'level_category', 'provincial_level_coordinate', 'prevalence_category', ) list_filter = ('year_record', 'age_category',,'malnutrition_category') search_fields = ('province_name',) list_per_page = 25 actions = [duplicate_model] My goal is to limit the default data shown in my list because I have a large dataset, and it becomes slow when I am in the ProvincialLevelAdmin list -
Stripe Checkout Session: No session_id Provided in Request After Successful Payment in Django
I'm working on a Django project where users can purchase subscriptions to various packages using Stripe Checkout. However, after a successful payment, I'm encountering an issue where the session_id is not being provided in the request when redirected to the payment_success view. here are the models.py: class Package(models.Model): name = models.CharField(max_length=255) description = models.TextField() price_monthly = models.DecimalField(max_digits=10, decimal_places=2) price_annually = models.DecimalField(max_digits=10, decimal_places=2) tax_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=0) def __str__(self): return self.name class Subscription(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=255) stripe_subscription_id = models.CharField(max_length=255) package = models.ForeignKey(Package, on_delete=models.CASCADE) interval = models.CharField(max_length=10) # 'monthly' or 'annual' active = models.BooleanField(default=True) Here are the relevant views: def package_list(request): packages = Package.objects.all() return render(request, 'subscriptions/package_list.html', {'packages': packages}) def create_checkout_session(request, package_id, interval): package = get_object_or_404(Package, id=package_id) if interval not in ['monthly', 'annually']: return redirect('package_list') if interval == 'monthly': price = package.price_monthly_including_tax() stripe_interval = 'month' else: price = package.price_annually_including_tax() stripe_interval = 'year' session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'cad', 'product_data': { 'name': package.name, }, 'unit_amount': int(price * 100), # Stripe expects the amount in cents 'recurring': { 'interval': stripe_interval, }, }, 'quantity': 1, }], mode='subscription', success_url=request.build_absolute_uri('/subscriptions/payment-success/?session_id={{CHECKOUT_SESSION_ID}}'), cancel_url=request.build_absolute_uri('/subscriptions/packages/'), customer_email=request.user.email if request.user.is_authenticated else None, ) return redirect(session.url, code=303) def payment_success(request): session_id = request.GET.get('session_id') if not session_id: logger.error("No … -
Print hello world in your root folder to know your web server supports python?
How to pint hello wold in python on a web server ? i'm new to pyhon and i want to see a python file running on my web server . This problem can be for any starters and can help many users to identify with their web servers if they can run python scripts. -
How to enter a Hatch shell development environment in the VS Code debugger launch profile when debugging django
I need to run the command 'hatch shell' to enter my hatch development environment before running the server command 'py manage.py runserver'. I can't find out how to do this using the VS code debugger profile specified in the launch.json file below. { "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/testproject/manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true } ] } I tried to run 'hatch shell' as a preLaunchTask but that runserver command did not run in the shell environment. -
Django: How to undo ModuleNotFoundErrors due to multiple site-packages locations
When I run my Django project, why does it check for site packages in a folder other than where my project is located? The correct location where the project and package files are located is: C:\Users\mattk\Box\WeConsent But in the error thread below, it seems to be searching in two separate locations for my library files: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe # my packages are not located here C:\Users\mattk\Box\WeConsent\manage.py runserver localhost:8000 # my packages are located here. Where in PyCharm can I specify to ignore this location: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe when loading my packages? from traceback in Terminal: C:\PythonProjects\VoterSay7\venv\Scripts\python.exe C:\Users\mattk\Box\WeConsent\manage.py runserver localhost:8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\core\management\commands\runserver.py", in inner_run autoreload.raise_last_exception() File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\PythonProjects\VoterSay7\venv\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\mattk\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in … -
NumPy Error will appear and uninstalling and reinstalling is the only way to fix it
I currently have a Django app and I will randomly run into this below error. The app will run fine, sometimes when I make a change to the code, the below error will show, even if the changes weren't related to NumPy or Pandas. If I uninstall and then reinstall Pandas and NumPy, it'll fix the error. ImportError: Unable to import required dependencies: numpy: Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there. I am using a virtual environment Django 4.2.5 and tried pretty much every recent version of NumPy and Pandas -
Django can not render the result
i have created the feedback app on learning system however i can not render the feedback page that return feedback details when i click the feedback link it does not return anything as shown below. enter image description here Below is the view.py # feedback/views.py from django.shortcuts import render, redirect from django.contrib import messages from accounts.models import User def feedback_view(request): feedback_data = User.objects.filter(username=request.user) context = { "feedback_data": feedback_data } return render(request, "feedback/feedback.html", context) @property def feedback_save(request): if request.method != "POST": messages.error(request, "Invalid Method.") return redirect('feedback') else: feedback = request.POST.get('feedback_message') feedback_data = User.objects.get(username=request.user.id) try: add_feedback = FeedBack(username=feedback_data, feedback=feedback, feedback_reply="") add_feedback.save() messages.success(request, "Feedback Sent.") return redirect('feedback') except: messages.error(request, "Failed to Send Feedback.") return redirect('feedback') model.py from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class FeedbackMessage(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.TextField() feedback_reply = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() feedback.html {% extends 'base.html' %} {% block page_title %} Feedback Message {% endblock page_title %} {% load static %} {% block main_content %} this is a test <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Leave a Feedback Message</h3> </div> <!-- … -
OSError at /en/reset_password/ [Errno 101] Network is unreachable
So I am making a django project on Google Cloud, I have added a forgot password feature from Django's built-in feature and I already tried it locally. But when I tried it on the cloud it gave me this error.... OSError at /en/reset_password/ [Errno 101] Network is unreachable Request Method: POST Request URL: http://34.128.98.45:8000/en/reset_password/ Django Version: 5.0.3 Exception Type: OSError Exception Value: [Errno 101] Network is unreachable Exception Location: /usr/lib/python3.10/socket.py, line 833, in create_connection Raised during: django.contrib.auth.views.PasswordResetView Python Executable: /home/rsa-key-20240516/env/SlangID/bin/python Python Version: 3.10.12 Python Path: ['/var/www/html/SlangID/src', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/rsa-key-20240516/env/SlangID/lib/python3.10/site-packages'] Server time: Sun, 02 Jun 2024 11:55:50 +0000 I really don't understand what to do I already tried adding a firewall rule to allow smtp connections like this image.... Even after that it still gave me the same error, chatGPT (I was desperate) reccomended to try ping IP 8.8.8.8. When I tried pinging it works well.... :~$ ping 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=122 time=1.91 ms 64 bytes from 8.8.8.8: icmp_seq=2 ttl=122 time=0.552 ms Then I tried pinging telnet smtp, like this... ~$ telnet smtp.gmail.com 587 Trying 74.125.130.108... Connected to smtp.gmail.com. Escape character is '^]'. 220 smtp.gmail.com ESMTP d9443c01a7336-1f632356aa0sm47645545ad.74 - gsmtp which … -
getting an empty folder in django new project
I created a virtual environment than I installed Django successfully but when I try to create a project with Django-admin start-project project-name Django create an empty folder? I'm expecting a folder with file with manage.py in the folder -
how do I run python code and opencv in the views file django?
#My views file in django from django.shortcuts import render from .forms import ImageForm from .models import Image def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance #at this point, I want to pass to the function a photo that has just been sent to the ######form return render(request, 'polling/pool.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'polling/pool.html', {'form': form}) Python code def scan_photo(group, name_photo): '''Сканирует карточки на фото''' global answers, input_field, label_entry_get answers = [] #label_entry_get['text'] = f'{input_field.get()}' #name = str(str(name_photo) + ".jpg") frame = cv2.imread(name_photo, cv2.IMREAD_COLOR) cv2.imshow('gfgfgg', frame) for identification, answer in recognizes_cards(frame, group): if identification <= len(group): answers.append((identification, answer)) print('Сканирование завершено') print('Результаты:') for identification, answer in answers: print(f'Студент: {group[identification - 1]["name"]} {group[identification - 1]["surname"]}, Ответ: {answer}') print(answers) -
How to properly dockerize Celery with Django?
I am having a little trouble dockerizing Celery alongside my Django project. Recently I had the need to add Celery to my projects, and I have worked with it prior, but not in a Docker environment. I am looking for a proper way to dockerize my Celery worker that works alongside my configuration. This is my django dockerfile: FROM python:3.9.13-slim CMD ["mkdir", "app/backend/"] WORKDIR /app/backend/ COPY ./backend/ . ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip && \ pip install -r requirements.txt && \ python manage.py collectstatic --noinput && \ chmod +x scripts/entrypoint.sh CMD ["scripts/entrypoint.sh"] This is my entrypoint script (all it does is start the gunicorn server): #!/bin/bash APP_PORT=${PORT:-8000} gunicorn project.wsgi:application --reload --bind "0.0.0.0:${APP_PORT}" This is my docker-compose: version: '3.8' services: backend: container_name: project-backend build: context: . dockerfile: docker/backend/Dockerfile volumes: - static:/app/backend/static ports: - "8000:8000" depends_on: - database redis: container_name: project-redis image: redis:alpine database: image: postgres:15 container_name: project-postgres volumes: - postgres_data:/var/lib/postgresql/data env_file: - ./backend/project/.env ports: - "8001:5432" frontend-nginx: container_name: project-frontend-nginx build: context: . dockerfile: docker/frontend-nginx/Dockerfile volumes: - node_modules:/app/frontend/node_modules - static:/app/backend/static ports: - "80:80" depends_on: - backend - database volumes: static: postgres_data: node_modules: Ignore the other services in the docker-compose, this is all the other stuff needed for my project … -
Method \"POST\" not allowed. django rest framework
I dont know, after a certain moment the part of my api stopped working. So i have my apiview written and it has post function, but when i knock on an endpoing i get error that post method is not allowed, but other parts of api work fine so i definetely have something wrong with postview project.urls `from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/', include('authentification.urls')), path('api/v1/', include('posts.urls')), # This includes the posts app URLs path('api/v1/payments/', include('payments.urls')), path('api/v1/support/', include('support.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` posts.urls from django.urls import path from .views import Lenta_View, Post_View, Profile_View, Settings_View, Like_View, Posts_search, Bookmark_View, Separated_lenta urlpatterns = [ path('', Lenta_View.as_view(), name='lenta'), path('<slug:filter>/', Separated_lenta.as_view(), name='lenta'), path('posts/', Post_View.as_view(), name='post_list_create'), path('posts/<int:id>/', Post_View.as_view(), name='post_detail'), path('profile/', Profile_View.as_view(), name='profile_mine'), path('profile/<slug:username>/', Profile_View.as_view(), name='profile_other'), path('settings/', Settings_View.as_view(), name='settings'), path('like/', Like_View.as_view(), name='like_all'), path('like/<int:id>/', Like_View.as_view(), name='like_add'), path('search', Posts_search.as_view(), name='search'), path('bookmarks/', Bookmark_View.as_view(), name='bookmark_list'), path('bookmarks/<int:id>/', Bookmark_View.as_view(), name='bookmark_add'), ] Post_View class Post_View(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def get(self, request, *args, **kwargs): id = kwargs.get("id") user = request.user if id is None: return Response({'message': "You haven't provided an …