Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set Nginx reverse proxy for local Docker Django
I'm developing a docker project with nginx and django services. I've django.conf.template parametrised to pass environment variables dynamically depends on environment. django.conf: upstream django_app { server ${DJANGO_PRIVATE_IP}:${DJANGO_PORT}; } server { listen 80; listen 443 ssl; listen [::]:443 ssl; server_name ${NGINX_SERVER_NAME}; ssl_certificate /etc/nginx/certs/elitecars_cert.pem; ssl_certificate_key /etc/nginx/certs/elitecars_privkey.pem; access_log /var/log/nginx/nginx.django.access.log; error_log /var/log/nginx/nginx.django.error.log; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://django_app; } } The template works well because i can see the env vars values with more /etc/nginx/conf.d/sites-available/django.conf command upstream django_app { server django:8000; } server { listen 80; listen 443 ssl; listen [::]:443 ssl; server_name 0.0.0.0 127.0.0.1 localhost; ... But when i tried to access through the browser but doesn't work. Any idea? Anybody could help me please ? Thanks in advance. -
Request timeout DJANGO API when uploading files, even if the file is 1 pixel only
so I am working on a android studio app, and I am having trouble uploading images from the app to my host using my DJANGO API. This is literally my endpoint: @api_view(['POST']) def changeProfile(request): user_id = int(request.data.get('userId', '')) pfp_file = request.FILES.get('pfp', None) pfb_file = request.FILES.get('pfb', None) data = {'rescode': '0001', 'message': 'Profile updated'} # Set CORS headers response = Response(data) response = Response(data) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Headers'] = 'content-type' response['Access-Control-Allow-Methods'] = 'POST, OPTIONS' return response I have made the request from Postman, from the android app even from a js file in the same directory as the API. All had the request "pending" and after 2 minutes it just gave error 500 timeout. It isn't due to the file size cause I even tried with a 1 by 1 image and it still had the same problem. It is also not lack of host resources like RAM or CPU cause I have checked them while the request was pending and it just stayed the same. And the weirdest part is that neither the client or server side have errors on the logs. -
How to set calender form in list_filter for datetime field in django admin?
models.py: class XYZ(models.Model): title = models.CharField(max_length=256) start = models.DateTimeField() end = models.DateTimeField() def __str__(self): return self.title admin.py: class XYZAdmin(admin.ModelAdmin): list_filter = (start,) admin.site.register(XYZ,XYZAdmin) and it's return now I want to change this filter to a pop-up calender and select custom start datateime and filter them. like this image: -
what does static() in django.conf.urls do?
I don't quite understand what it does from the doc what this function does and why it is useful. From the code snippet it provides from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ALso, what is this MEDIA_URL and MEDIA_ROOT? -
How can I change the type of a field in a linked model?
I have two models: the first is called 'PurchaseList', it includes a field, called 'recipe'. The field 'recipe' is a ForeignKey for building up the link to the second model, called 'Recipe' by creating a new field called 'is_in_shopping_cart': class PurchaseList(models.Model): author = models.ForeignKey('User', on_delete=models.CASCADE, verbose_name='Автор', related_name='added_to_cart') recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE, verbose_name='Рецепт', related_name='is_in_shopping_cart') class Meta: verbose_name = 'Список покупок' verbose_name_plural = 'Списки покупок' ordering = ['recipes'] def __str__(self): return self.recipe class Recipe(models.Model): tags = models.ManyToManyField(Tag, verbose_name='Теги') author = models.ForeignKey('User', related_name='recipes', on_delete=models.CASCADE, verbose_name='Автор') ingridients = models.ManyToManyField(Product, through='IngredientToRecipe', verbose_name='Ингредиент') name = models.CharField(max_length=16, verbose_name='Наименование') image = models.ImageField( upload_to='recipes/images/', default=None, verbose_name='Изображение' ) text = models.TextField(verbose_name='Описание') cooking_time = models.IntegerField( verbose_name='Время приготовления в минутах') pub_date = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') class Meta: verbose_name = 'Рецепт' verbose_name_plural = 'Рецепты' ordering = ['-pub_date'] def __str__(self): return self.title My target is to make the field 'is_in_shopping_cart' a BooleanField. So the question is how to determine the type of a field formed from a related model in the main model. I've found this way of solving the problem: @property def is_in_shopping_cart(self): return PurchaseList.objects.filter(author=self.author).exists() But i'm not sure if it works. Moreover, my friend advised me to try include attribute called 'field' to the field 'recipe' but I haven't found anything about … -
pyCharm does not find library file in django program
In a Django programm pyCharm (prof.) highlights utils_modal in a %load% statement with the info "unresolved library 'utils_modal'". My Django program has this structure djProgram | +-+- app_1 | +-- __init__.py | +-- templates | +-- app_1 | +-- template.html | +-+- app_2 | +-- __init__.py ... +-- utils +-- templatetags +- utils_modal.py utils is a non app folder, just a library for some modals used in the apps. This folder is mentioned in settings.py in the TEMPLATES structure: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # some definitions ], 'libraries': { 'utils_modal': 'utils.templatetags.utils_modal', }, }, }, ] template.html starts like this: {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% load utils_modal %} {# <-- Here is the pyCharm warning "Unresolved library 'utils_modal'" #} {% block content %} <!-- HTML code --> {% endblock %} What mistake have I made here? Thanks in advance. I am working with Windows 11, pyCharm professional 2023.3.2, Django 4.2.7 -
Toast message color Django
In A django App I want to return a message from views and show it using toast. and my main page is: <div class="toast-container p-3"> <div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div id="toast-body" class="toast-body"></div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> </div> <div class="col-md-3"> <div id="Chamber_list"> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" style="...">{{ message }}</div> {% else %} <div class="alert alert-success" style="...">{{ message }}</div> {% endif %} {% endfor %} {% endif %} {% include 'Home/MOG_Division/rooms/Detaile/Chamber_list.html' %} </div> </div> And this is my views.py code > def edit_actl(request, pk): theroom = get_object_or_404(room_actual, pk=pk) form_erAO = False if request.method == "POST": form = room_actualForm(request.POST, instance=theroom) try: if form.is_valid(): form.save() response_data = {'success': True,'message': 'Room updated successfully'} response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204) response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage": f"{theroom.room} {theroom.first_name} updated." }) return response except ValueError: form_erAO = 'Check your input dates' response_data = {'error': True, 'message': 'Room Already Occupied, Try another range'} response = HttpResponse(json.dumps(response_data), content_type='application/json',status=204) response['HX-Trigger'] = json.dumps({"roomListChanged": None, "showMessage":'Try another range'}) return response else: form = room_actualForm(instance=theroom) return render(request, 'Home/MOG_Division/rooms/Detaile/Actul_form.html', { 'form': form, 'theroom': theroom, 'form_erAO' : form_erAO }) … -
How do I Go About correcting certain css style in my django project not taking effect after deployed on Vercel
This is what it looks like on my local machin This is what i am getting after being uploaded to Vercel How do I Go About correcting certain css style in my django project(URLSHORTNER) not taking effect after deployed on Vercel So what possibly could go wrong in this code. here is the link to the code https://github.com/aaronicks/urlshortner/tree/gh-pages/shortner -
Python Opencv, send data to website via port
I have a python opencv code for age detection. import cv2 import math import time import argparse def getFaceBox(net, frame,conf_threshold = 0.75): frameOpencvDnn = frame.copy() frameHeight = frameOpencvDnn.shape[0] frameWidth = frameOpencvDnn.shape[1] blob = cv2.dnn.blobFromImage(frameOpencvDnn,1.0,(300,300),[104, 117, 123], True, False) net.setInput(blob) detections = net.forward() bboxes = [] for i in range(detections.shape[2]): confidence = detections[0,0,i,2] if confidence > conf_threshold: x1 = int(detections[0,0,i,3]* frameWidth) y1 = int(detections[0,0,i,4]* frameHeight) x2 = int(detections[0,0,i,5]* frameWidth) y2 = int(detections[0,0,i,6]* frameHeight) bboxes.append([x1,y1,x2,y2]) cv2.rectangle(frameOpencvDnn,(x1,y1),(x2,y2),(0,255,0),int(round(frameHeight/150)),8) return frameOpencvDnn , bboxes faceProto = "opencv_face_detector.pbtxt" faceModel = "opencv_face_detector_uint8.pb" ageProto = "age_deploy.prototxt" ageModel = "age_net.caffemodel" genderProto = "gender_deploy.prototxt" genderModel = "gender_net.caffemodel" MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746) ageList = ['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)'] genderList = ['Male', 'Female'] #load the network ageNet = cv2.dnn.readNet(ageModel,ageProto) genderNet = cv2.dnn.readNet(genderModel, genderProto) faceNet = cv2.dnn.readNet(faceModel, faceProto) cap = cv2.VideoCapture(0) padding = 20 while cv2.waitKey(1) < 0: #read frame t = time.time() hasFrame , frame = cap.read() if not hasFrame: cv2.waitKey() break #creating a smaller frame for better optimization small_frame = cv2.resize(frame,(0,0),fx = 0.5,fy = 0.5) frameFace ,bboxes = getFaceBox(faceNet,small_frame) if not bboxes: print("No face Detected, Checking next frame") continue for bbox in bboxes: face = small_frame[max(0,bbox[1]-padding):min(bbox[3]+padding,frame.shape[0]-1), max(0,bbox[0]-padding):min(bbox[2]+padding, frame.shape[1]-1)] blob = cv2.dnn.blobFromImage(face, 1.0, (227, 227), MODEL_MEAN_VALUES, swapRB=False) genderNet.setInput(blob) … -
Django Rest -api User registration
I've been trying to implement register method on UserView , to create new user each time I call Post request , But I got this error in postman "detail": "Method \"POST\" not allowed." views.py class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializers @action(detail=True, methods=["post"]) def register(self, request): serializer = UserSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND even when I set detail=False , I got this error too ,even though I dont have any many-to-many relationship between any tow models.. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. Serializer.py class UserSerializers(ModelSerializer): class Meta: model = User fields = "__all__" # exclude the 'password' field from the serialization extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user -
Django Azure deployment : Failed to build pycairo\nERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based
I am trying to deploy on Azure web apps, I am getting an error around pycairo, I have tried using containers to work around that , containers are not working and even worse they don't show what the problem is. So I have reverted to Azure Web apps cause atleast I can tell the issue from the logs. In detail the error looks like: Failed to build pycairo\nERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects\n\n[notice] A new release of pip is available: 23.0.1 -> 23.3.2\n[notice] To The web app runs smooth on my local computer, the problem comes on deployment. Whats even worse is even If I uninstall pycairo, the error will persist. Almost like there is no way around it. I have long engaged microsoft Azure support team for days now but there is no solution from their side. And thats why I am appealing to you my coding super heros, to finally end my struggle, this problem has literally stolen a week of my time and afteer spending a long time. The stack used is Django and postgres Deploying on Azure using both Web Apps and containers service. I have changed python … -
Convert string to boolean using database expression in Django (for generated field)
I have the following models code: class Product(models.Model): ... barcode_data = models.CharField( max_length=255, blank=True, default="", ) @property def is_scannable(self): if self.barcode_data: return True else: return False Basically, if barcode_data is not empty, is_scannable returns True. I want to turn is_scannable into a generated field, something like this: class Product(models.Model): ... barcode_data = models.CharField( max_length=255, blank=True, default="", ) is_scannable = models.GeneratedField( expression=..., output_field=models.BooleanField(), db_persist=True, ) I've read the docs here: https://docs.djangoproject.com/en/5.0/ref/models/database-functions/, but it seems like there isn't really a function to convert a string to boolean based on whether it is empty or not. Is there a way to do this? -
Basecamp 3 API upload/insert image error 422 : Unprocessable Entity in Django
so i have a django project that will insert a comment with image to basecamp 3. So after i got a key token (Authorization using Oauth 2) i need to insert a comment with image to basecamp todos. The image is from url contained in JSON that user input. The JSON is look like this { "uuid":"763eadb9-7c6b-4383-9013-34859e0ab062", "event":"capture.new", "id":"1", "url":{ "id":"2", "url":"https://pagescreen.io", "http_code":"200", "title":"Pagescreen (test)", "description":"" }, "permalink":"https://i.pagescreen.io/i/123.png", "generated":"1", "status":"1", "requested_on":"2022-12-14T07:05:10+00:00", "last_updated":"2022-12-14T07:05:38+00:00", "options":{ "delay":"0", "format":"png", "fullpage":"1", "viewport":{ "width":"1440", "height":"960" } }, "automation_id":"1", "file":{ "width":"1440", "height":"11216", "size":"639570" }, "colors":{ "rgb(109, 118, 139)":304, "rgb(255, 255, 255)":169, "rgb(51, 51, 51)":4, "rgba(0, 0, 0, 0)":523, "rgb(0, 0, 0)":82, "rgb(239, 239, 239)":5, "rgb(33, 68, 146)":27, "rgb(0, 131, 221)":37, "rgb(120, 129, 149)":27, "rgba(255, 255, 255, 0.063)":2, "rgba(255, 255, 255, 0.314)":2, "rgba(255, 255, 255, 0.5)":2, "rgb(255, 194, 10)":5, "rgb(0, 26, 62)":42, "rgb(70, 188, 102)":11, "rgb(238, 82, 83)":5, "rgb(255, 165, 0)":6, "rgb(61, 129, 214)":22, "rgb(0, 122, 255)":4, "rgb(30, 144, 255)":8, "rgb(248, 248, 248)":6, "rgb(240, 240, 240)":7, "rgb(80, 102, 144)":15, "rgba(0, 0, 0, 0.1)":1, "rgb(0, 201, 183)":4 }, "navigation":{ "previous":{ "id":"1" }, "next":null } } So from that JSON i saved the image from permalink ("permalink":"https://i.pagescreen.io/i/123.png") to my local storage project. Then after saved the image, i upload/attach it … -
django - similar management commands for different django apps
I am using django now, I have created a django-project with three django-apps in it. Each app can be used in isolation, without the others, but all three apps are working together somehow. For each app I have custom commands for unit-, integration- and end-to-end-tests. project/ app1/ management/commands/ unittest.py integrationtest.py etoetest.py app2/ management/commands/ unittest.py integrationtest.py etoetest.py app3/ management/commands/ unittest.py integrationtest.py etoetest.py What I want to know, is there a way to run manage.py inside the project and give it some kind of argument to specify the app for which a command has to be executed? I want to do something like this: ./manage.py unittest app1 --arg0 ... If there is a way, where in the project should the solution live? I tried implementing djangos AppCommand or playing with different settings.py to execute the desired commands. But each of the two solutions did not feel right and did not really integrate well into the overall architecture of the project. -
Where should the virtual environment folder be kept within a django project?
I have a project directory that looks like this my_awesome_project (top level folder) my_project_folder (generated by django) my_project_folder manage.py .. other app folders venv (virtual environment folder) Is this good? I really don't know, and want to hear how other's deal with where their virtual environment folder exists. I couldn't think of other ways to structure it. -
Django Rendering HTML files ISSUE
This might be something simple, but this is an error I've never faced before. Instead of rendering the template normally, Im getting plain HTML Code... Just like a Plain Text File, without a single error, it just suddenly started showing plain HTML text. Not getting a single error message... -
I get data of last form in django when I am using pagination
views.py def quiz (request): questions = Question.objects.order_by("?")[0:101] paginator = Paginator(questions , 1) page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) if request.method == "POST" : user_timer = request.POST.get("timer") total=len(questions) score=0 wrong=0 correct=0 for q in questions : user_answer = request.POST.get(str(q.pk)) if user_answer : print(user_answer) if q.answer == user_answer : score += 5 correct += 1 else : wrong += 1 score += 0 percent = correct / total * 100 profile = Profile.objects.get(user=request.user) profile.score += score # type: ignore profile.save() context={'score':score , 'wrong':wrong, 'correct':correct,'percent' : percent, 'timer':user_timer , 'total' : total} return render(request, "quizApp/result.html", context) return render(request, "quizApp/quiz.html", {"paginator":paginator , "page_obj":page_obj, "questions":questions}) How I get marge two forms in pagination ? I want get answers of form has pagination but I get data of last form in pagination. How can I do this ? -
Plotting a bar graph in django using matplotlib
I want a bar graph of expense vs date in my django webapp using matplotlib. There can be multiple entries of expense for a single date. The html page shows 'barcontainer object of 2 artists' . How to solve this question. -
django app localhost refused to connect docker
I'm trying to setup my django project with docker. It will have multiple containers one is for code that is server, worker for celery, redis for redis, db for postgres and there is nginx. Every one of them are running without any error but the localhost:8080 is not accessible. I tried accessing localhost:8000 directly and it is still not accessible. Here's all the relevant configuration files of docker. the docker-compose.yml is as: version: '2' services: nginx: restart: always image: nginx:1.23-alpine ports: - 8080:8080 volumes: - /default.conf://etc/nginx/conf.d - static_volume:/app/django_static server: restart: unless-stopped build: context: . dockerfile: Dockerfile entrypoint: /app/server-entrypoint.sh volumes: - static_volume:/app/django_static expose: - 8000 environment: DEBUG: "True" CELERY_BROKER_URL: "redis://redis:6379/0" CELERY_RESULT_BACKEND: "redis://redis:6379/0" DJANGO_DB: postgresql POSTGRES_HOST: db POSTGRES_NAME: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_PORT: 5432 worker: restart: unless-stopped build: context: . dockerfile: Dockerfile entrypoint: /app/worker-entrypoint.sh volumes: - static_volume:/app/django_static environment: DEBUG: "True" CELERY_BROKER_URL: "redis://redis:6379/0" CELERY_RESULT_BACKEND: "redis://redis:6379/0" DJANGO_DB: postgresql POSTGRES_HOST: db POSTGRES_NAME: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_PORT: 5432 depends_on: - server - redis redis: restart: unless-stopped image: redis:7.0.5-alpine expose: - 6379 db: image: postgres:13.0-alpine restart: unless-stopped volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres expose: - 5432 volumes: static_volume: {} postgres_data: {}version: '2' services: nginx: restart: always image: nginx:1.23-alpine ports: - … -
DO Spaces on Django Cookiecutter Docker - AWS Connection Issue
I am trying to run DO Spaces on a Django/Docker. (setup via Django-Cookiecutter.) I know all this data is good. DJANGO_AWS_ACCESS_KEY_ID='DO00CBN....BATCXAE' DJANGO_AWS_SECRET_ACCESS_KEY='vkmMV3Eluv8.....U1nvalkSFugkg' DJANGO_AWS_STORAGE_BUCKET_NAME='my-key' DJANGO_AWS_DEFAULT_ACL = 'public-read' DJANGO_AWS_S3_REGION_NAME = 'sgp1' DJANGO_AWS_S3_CUSTOM_DOMAIN = 'https://my-key.sgp1.digitaloceanspaces.com' in production.py AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate", } AWS_S3_MAX_MEMORY_SIZE = env.int( "DJANGO_AWS_S3_MAX_MEMORY_SIZE", default=100_000_000, # 100MB) AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) AWS_S3_CUSTOM_DOMAIN = env("DJANGO_AWS_S3_CUSTOM_DOMAIN", default=None) # aws_s3_domain = AWS_S3_CUSTOM_DOMAIN or f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" aws_s3_domain = AWS_S3_CUSTOM_DOMAIN or f"{AWS_STORAGE_BUCKET_NAME}.digitaloceanspaces.com" I chaged the '.s3.amazonaws.com' to '.digitaloceanspaces.com' which gives me 'https://my-zzz.sgp1.digitaloceanspaces.com' But nothing i do or change makes a difference and I always get this error. botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://my-key.s3.sgp1.amazonaws.com/static/sass/project.scss" It seems that the connection is always being overwritten by the '.s3.sgp1.amazonaws.com' What can I do to change this setting which seems to happen in boto? remember this is via Docker. Can it be done via an enviorment in the production.yml? Or in the AWS Dockerfile? Thanks! -
Celery workers do not perform django db update tasks
I am working on a dashboard which requires running long background tasks, and eventually updating a model in database. I am using Celery to perform the background operations Here is my task function in tasks.py @shared_task() def generate_content_async(system_prompt, user_prompt, section_id): data = get_data() # long running operation section = Section.objects.get(id = id) section.data = data section.save() return f"Section with section id: {id} updated" Please note that I am only updating the value of data in Section model. Everything in the code is working fine, and there are no issues, the background task finishes with success, but the database update does not work. What would be the reason for such an issue? TIA I have tried using transactions to perform any database operations after commit, but did not work (this should not be an issue, as there are no ongoing transactions in my case). -
Django - Uploading image through custom models in admin not working
I'm currently working on a Django project, and for this I need to add a way of inputting images to each custom page through the admin panel. However, when I attempt to add this functionality and fill in the form on the admin page, I get shown this: This is what my models.py looks like: from django.db import models from django.urls import reverse # Create your models here. class Bird(models.Model): image = models.ImageField(help_text='Upload Image') breed = models.CharField(max_length=200, help_text='Enter Breed') breed_sub_category = models.CharField(max_length=200, help_text='Enter Breed Subtype') description = models.CharField(max_length=5000, help_text='Enter Description') price = models.FloatField(help_text='Enter Price Here') age_in_years = models.IntegerField(max_length=200, help_text='Enter Age in Years') age_in_months = models.IntegerField(max_length=200, help_text='Enter Age in Months') tame = models.BooleanField(help_text='Is the bird tame?') def get_absolute_url(self): return reverse('model-detail-view', args=[str(self.id)]) def __str__(self): return self.image return self.breed return self.price return self.age_in_years return self.age_in_months return self.breed_sub_category return self.tame return self.description And this is what my admin.py looks like: from django.contrib import admin from .models import Bird # Register your models here. admin.site.register(Bird) -
Django not updating html templates in browser
I set up Django with cookiecutter and am running the project with docker compose. Everything worked fine, however, when I update an .html template file. The change isn’t reflected on the webpage. I made sure that DEBUG = TRUE and refreshed/cleared my browser cache. When I navigate the to the html file through the django sidebar I can see the changes there but not on the actual webpage (see attached screenshot). I confirmed DEBUG =TRUE and cleared my chache/did a hard refresh with now luck. I'm on a windows pc. Thank you in advance. Github Docker compose file. version: '3' volumes: dtj_local_postgres_data: {} dtj_local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: dtj_local_django container_name: dtj_local_django depends_on: - postgres - redis - mailpit volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - '8000:8000' command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: dtj_production_postgres container_name: dtj_local_postgres volumes: - dtj_local_postgres_data:/var/lib/postgresql/data - dtj_local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres docs: image: dtj_local_docs container_name: dtj_local_docs build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./dtj:/app/dtj:z ports: - '9000:9000' command: /start-docs mailpit: image: docker.io/axllent/mailpit:latest container_name: dtj_local_mailpit ports: - "8025:8025" redis: image: docker.io/redis:6 container_name: dtj_local_redis celeryworker: <<: *django image: dtj_local_celeryworker container_name: dtj_local_celeryworker … -
Im trying to deplay a django project on Heroku but I get the following error. /bin/bash: line 1: gunicorn: command not fot found
Log from Heroku 2024-01-25T22:53:03.888631+00:00 app[web.1]: /bin/bash: line 1: gunicorn: command not found 2024-01-25T22:53:03.939373+00:00 heroku[web.1]: Process exited with status 127 2024-01-25T22:53:03.967679+00:00 heroku[web.1]: State changed from starting to crashed 2024-01-25T22:53:03.974999+00:00 heroku[web.1]: State changed from crashed to starting 2024-01-25T22:53:09.010573+00:00 heroku[web.1]: Starting process with command `gunicorn Website.wsgi:application` 2024-01-25T22:53:09.615178+00:00 app[web.1]: /bin/bash: line 1: gunicorn: command not found 2024-01-25T22:53:09.650096+00:00 heroku[web.1]: Process exited with status 127 2024-01-25T22:53:09.670492+00:00 heroku[web.1]: State changed from starting to crashed 2024-01-25T22:53:10.709561+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=uchennasporfolio-e180324e16c1.herokuapp.com request_id=0f77cc0c-29eb-4fbe-a84f-4569840f965d fwd="96.246.176.87" dyno= connect= service= status=503 bytes= protocol=https 2024-01-25T22:53:11.629206+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=uchennasporfolio-e180324e16c1.herokuapp.com request_id=9afb6ed6-0121-4818-8779-752e3d3f7478 fwd="96.246.176.87" dyno= connect= service= status=503 bytes= protocol=https Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "==5.0.1" django-cors-headers = "==4.3.1" djoser = "==2.2.2" djangorestframework = "==3.14.0" requests = "==2.31.0" django-heroku = "==0.3.1" asgiref = "==3.7.2" certifi = "==2023.11.17" cffi = "==1.16.0" charset-normalizer = "==3.3.2" cryptography = "==42.0.0" defusedxml = "==0.8.0rc2" dj-database-url = "==2.1.0" django-templated-mail = "==1.1.1" djangorestframework-simplejwt = "==5.3.1" idna = "==3.6" oauthlib = "==3.2.2" packaging = "==23.2" psycopg2 = "==2.9.9" pycparser = "==2.21" pyjwt = "==2.8.0" python3-openid = "==3.2.0" pytz = "==2023.3.post1" requests-oauthlib = "==1.3.1" social-auth-app-django = "==5.4.0" social-auth-core = "==4.5.1" sqlparse = "==0.4.4" typing-extensions = "==4.9.0" tzdata = "==2023.4" … -
How do you use short-term AWS credentials with django-storages?
I want to migrate away from using long-term access keys to further harden my security. I am seeking to implement short term security credentials for the AWS services I am using, such as S3. Specifically, I have an IAM user which can assume a role which gives it access to S3. This role is only assumed for a limited amount of time before it expires and then needs to be reassumed. I am wondering if anyone has successfully implemented this pattern using django-storages, and if they can provide advice? It seems like there is support for a config called AWS_SESSION_TOKEN here but there is no documentation for it. Additionally, there is a config called AWS_S3_SESSION_PROFILE, but I can't tell if this is related to what I'm trying to do.