Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to annotate, filter then get ForeignKey field relations in Django (FilteredRelation or another method)?
I'm trying to annotate ForeignKey relations and then use new annotated field in loop From docs: >>> from django.db.models import FilteredRelation, Q >>> Restaurant.objects.annotate( ... pizzas_vegetarian=FilteredRelation( ... "pizzas", ... condition=Q(pizzas__vegetarian=True), ... ), ... ).filter(pizzas_vegetarian__name__icontains="mozzarella") That works. But if i do: >>> from django.db.models import FilteredRelation, Q >>> rests = Restaurant.objects.annotate( ... pizzas_vegetarian=FilteredRelation( ... "pizzas", ... condition=Q(pizzas__vegetarian=True), ... ) ... ) ... for rest in rests: print(rest.pizzas_vegetarian) I get AttributeError: "Restaurant object has no attribute 'pizzas_vegetarian'" I need access to that "pizzas_vegetarian" in separate code blocks. Is it possible with FilteredRelation? Wich method should i use to get it? -
How can I change CustomUser model fields in view and forms
I am building a scoring system and I want to register a score for those who are active on the website, for example, when someone leaves a comment, get 5 points, but I didn't succeed and I tried several methods. models.py class CustomUser(AbstractUser): activity_point = models.PositiveIntegerField(default=0) First method in views.py class NewsDetailView(generic.DetailView): model = News template_name = 'news/news_details.html' def get_context_data(self, **kwargs): context = super().get_context_data() if self.request.user.is_authenticated: context['comment_form'] = CommentForm() return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): news = self.get_object() form.instance.author = request.user form.instance.news = news self.request.user.activity_point += 5 # Here form.save() return redirect(reverse('news_detail', kwargs={ 'pk': news.uid })) Second method in views.py class CitizenNewsCreateView(mixins.LoginRequiredMixin, generic.CreateView): model = News template_name = 'news/news_create.html' form_class = CitizenReporterForm success_url = reverse_lazy('citizen_report_list') def get_queryset(self): # Here user = CustomUser.objects.filter(username=self.request.user.username) change_activity_point = user.activity_point + 5 return change_activity_point def form_valid(self, form): form.instance.author = self.request.user form.instance.active = False form.instance.citizen = True return super(CitizenNewsCreateView, self).form_valid(form) I expect its change the activity point to 5. -
Parameters to FilterView from template redirect
I've read through all similar Q&As but can't figure out how to achieve what I'm wanting. My base.html has a dropdown menu based on academic years: <div class="dropdown"> <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> <svg class="bi pe-none me-2" width="16" height="16"><use xlink:href="#archive"/></svg> <strong>Select Year</strong> </a> <ul class="dropdown-menu dropdown-menu-dark text-small shadow"> {% for year in years %} <li><a class="dropdown-item"href="{% url 'administration.home_selected' year %}">{{year}}</a></li> {% endfor %} </ul> </div> administration.home_selected is a function based view and receives the parameter of year to show the desired data relating to that academic year: url.py path( "home_selected/<int:year>", views.home_selected, name="administration.home_selected", ), How do I replicate the same functionality when a navigation tabs within the home_selected.html is selected and relates a FilterView: path( "learners/<int:year>", views.FilteredLearnerListView.as_view(), name="administration.learners", ), The view is currently coded to show only current year data but I'd like to be able to do the same as I have with the function based view to show the correct data depending on the year selected from the base.html views.py class FilteredLearnerListView(SingleTableMixin, FilterView): table_class = LearnerTable model = Learner context_object_name = "learner_list" current = AcademicYear.objects.filter(is_current=True).get() contracts_list = Contract.objects.filter(academic_year=current).values_list( "id", flat=True ) contracts_list = list(contracts_list) contracts = Contract.objects.filter(academic_year=current).values() groups = Group.objects.filter(contractId__in=contracts_list) queryset = Learner.objects.filter(groupId__in=groups) template_name = … -
Django - Custom Error Templates not rendering
I have some custom templates in my django app. But these are not being rendered and instead displays the basic template: 500 Internal Server Error Exception inside application. Daphne This is my setup: Views.py (app level: main): def custom_500(request): return render(request,'main/500.html', status=500) templates (app level: main with path: templates->main->500html) 500.html custom template file urls.py (project level) from main.views import custom_400, custom_500 from django.conf.urls import handler500, handler400 handler500 = 'main.views.custom_500' settings (folder) staging.py: DEBUG = False ALLOWED_HOSTS = ['domainname.com' ] SECURE_SSL_REDIRECT = True I also have a base.py in my setting folder, but cannot see anything I should report on there. I tried to list all the checks I have tried: In heroku app shell: print(settings.ALLOWED_HOSTS) # returned the domain name print(settings.DEBUG) # returned false print(os.getenv('DJANGO_SETTINGS_MODULE')) # mysite.settings.staging print(settings.CSRF_COOKIE_SECURE) # true (just in case I would the app would be treated as non prod) print(settings.SECURE_SSL_REDIRECT) # true (just in case I would the app would be treated as non prod) and finally: >>> from django.shortcuts import render >>> from django.test import RequestFactory >>> request = RequestFactory().get('/') >>> render(request,'main/500.html', status=500) #returned: <HttpResponse status_code=500, "text/html; charset=utf-8"> I am running out of idea, and I am sure its probably something simple. I am hoping … -
Why do migrations run faster under `./manage.py test` compared with `./manage.py migrate`?
Why do migrations run faster under ./manage.py test compared with ./manage.py migrate? I'm not running an in memory database for unit tests or anything like that. Both the proper app and the unit test db use the same mysql docker container. I am using the NoseTestRunner. This came up because I am trying use the Pytest runner but I found that it was much slower. I know that ./manage.py test is in fact running the migrations, there are no shortcuts like that. I have not technically verified that all cases run the same number of migrations. I'm guessing some database optimization is being applied, like removing constraints or something. I have these two dependencies installed. django-nose==1.4.7 Django==3.2.25 -
Is there are any way to add 2 models as auth-user-model?
i have created 2 apps user and a vendor. This is the error i am facing. " AttributeError at /users/admin/login/ Manager isn't available; 'auth.User' has been swapped for 'vendors.Vendor' Request Method: POST Request URL: http://127.0.0.1:8000/users/admin/login/ Django Version: 5.1.3 Exception Type: AttributeError Exception Value: Manager isn't available; 'auth.User' has been swapped for 'vendors.Vendor'" Can i add both the Vendor and user ? -
Write a datetime to the database using model.DateTimeField() in Python Django, the UTC timezone is not correctly displayed in the database
settings.py TIME_ZONE = "Asia/Taipei" USE_I18N = True USE_TZ = True models.py from django.db import models class ApiLog(models.Model): endpoint = models.CharField(max_length=255) method = models.CharField(max_length=10) request_body = models.TextField() response_body = models.TextField() timestamp = models.DateTimeField() class Meta: db_table = 'api_log' managed = False # 若資料表為手動建立,將 managed 設為 False def __str__(self): return f"{self.method} {self.endpoint} at {self.timestamp}" views.py def simple_api(request): endpoint = request.path method = request.method request_body = request.body.decode('utf-8') if request.body else "" if method == 'GET': response_data = {'message': 'This is a GET request'} elif method == 'POST': try: data = json.loads(request.body) response_data = {'message': 'Data received', 'data': data} except json.JSONDecodeError: response_data = {'error': 'Invalid JSON format'} else: response_data = {'error': 'Method not allowed'} response_body = json.dumps(response_data) # def UTC+8 tz = pytz.timezone('Asia/Taipei') # get utc+8 time current_utc_plus_8_time = timezone.now().astimezone(tz) print("Current UTC+8 Time:", current_utc_plus_8_time) # record ApiLog ApiLog.objects.create( endpoint=endpoint, method=method, request_body=request_body, response_body=response_body, timestamp=current_utc_plus_8_time ) return JsonResponse(response_data) Based on this design, I expect the recorded timestamp in the database to be in the format “yyyy-MM-DD HH:mm:ss.ssssss+08:00.” However, when querying directly with a SELECT statement in the database, the result is converted to UTC+0. I’ve tried several methods to resolve this issue. For example: In Java, using mybatis mapper @Mapper public interface ApiLogMapper { @Insert("INSERT INTO … -
Importing module within the celery task
I wonder whether there could be difference between the following code snippets from some_module.sub_module import some_function @app.task(soft_time_limit=16, time_limit=18) def call_function(): some_function() and @app.task(soft_time_limit=16, time_limit=18) def call_function(): from some_module.sub_module import some_function some_function() I'm using celery with Django and there are around 16 celery processes. Is there some difference between th abovementioned pieces of the code? I feel like there can be some difference. What if inside some_module.sub_module module there is a variable? Will all workers share it? Or absolutely everything is separated? Thank you. -
Multiple forms that are different in a view Django
I was wondering if there was a way to have multiple different forms in a single view and to press a single submit button for the information to be stored. I have the following forms, the first one is my general form that should be created first: class GeneralForm(forms.ModelForm): name = forms.CharField(max_length=50) TYPE_CHOICES = ( ("C","C"), ("E","E") ) STATUS_CHOICES = ( ("A", "A"), ("F", "F"), ) type=forms.ChoiceField(choices=STATUS_CHOICES) number=forms.CharField(max_length=50) TURN_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3") ) turn = forms.ChoiceField(choices=TURN_CHOICES) class Meta: model = models.General fields=["name","type","number","turn"] The second one needs an instance of the first one and so does the third: class TypeOneForm(forms.ModelForm): num_chairs=forms.IntegerField() num_instalations = forms.IntegerField() total = forms.IntegerField() num_programs = forms.IntegerField() class Meta: model = models.TypeOne fields=["num_chairs","num_instalations","total","billetes_cien"] class TypeTwoForm(forms.ModelForm): num_available_seats=forms.IntegerField() num_available_instalations = forms.IntegerField() total = forms.IntegerField() num_new_programs = forms.IntegerField() class Meta: model = models.TypeTwo fields=["num_available_seats", "num_available_instalations","total","num_programs" ] These are my models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class General(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) name = models.CharField(max_length=100) TYPE_CHOICES = { "C": "C", "E": "E", } type = models.CharField(max_length=10, choices=TYPE_CHOICES) STATUS_CHOICES = { "A": "A", "F": "F", } status = models.CharField(max_length=10, choices=STATUS_CHOICES) number … -
MemoryError inside celery, but no error outside
I'm using Django 5.1.3 and Celery 5.4.0. I have one task. If I run it without Celery, then everything is OK. If I run it with the help of Celery, I get MemoryError. What is the reason for this? Can I tune somehow Celery to avoid this error? It would be good if the behavior was consistent. Thank you. -
Django app in docker with gunicorn gives "Error handling request (no URI read)"
I'm running a django application using gunicorn inside a docker container, but I'm encountering an error on request. The application fails with the following error log: [2024-11-13 18:50:11 +0000] [9] [ERROR] Error handling request (no URI read) Traceback (most recent call last): File "/usr/local/lib/python3.13/site-packages/gunicorn/workers/sync.py", line 133, in handle req = next(parser) ... SystemExit: 1 But the request is eventually processed and a response is provided, but it takes a time. Here is mt dockerfile: FROM python:3.13.0-alpine3.20 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app RUN apk update && \ apk add --no-cache jq python3-dev build-base gcc jpeg-dev zlib-dev libpq-dev COPY Pipfile.lock . RUN jq -r '.default | to_entries[] | .key + .value.version ' Pipfile.lock > requirements.txt && \ pip install -r requirements.txt COPY . . ENTRYPOINT ["sh", "./entrypoint.sh"] Here is my docker-compose.yml: services: app: build: . container_name: app volumes: - .:/app - ./src/media:/app/src/media ports: - "8000:8000" depends_on: - db env_file: - .env restart: always db: image: postgres:17.0-alpine3.20 container_name: postgres_db volumes: - postgres_data:/var/lib/postgresql/data env_file: - .env restart: always volumes: postgres_data: I'm starting gunicorn with this command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 How to solve this problem? Thanks! -
Ninja POST 422 (Unprocessable Entity) [duplicate]
Does anyone know why this happened? I can upload the picture just fine in swagger UI but I always got 422 http response. @http_post("/profile", response=dict) def upload_profile_image(self, request, file: UploadedFile = File(...)): """Upload profile image for business.""" try: business = Business.objects.get(user=request.user) except Business.DoesNotExist: return JsonResponse({"msg": "You don't have business yet."}, status=404) business.image.save(file.name, ContentFile(file.read()), save=True) image_url = request.build_absolute_uri(business.image.url) # Full URL print('put URL', image_url) return { "msg": f"{file.name} uploaded.", "business": image_url } Front end (Next.js) const handleSubmit = async () => { const formData = new FormData(); if (selectedFile) { formData.append('profile_image', selectedFile); // Match field name expected in backend } try { const response = await fetch(`http://127.0.0.1:8000/api/business/profile`, { method: "POST", body: formData, }); if (!response.ok) { console.log("Failed to save edited business"); return; } } catch (error) { console.log("Error saving edited queue:", error); } }; I even tried upload the same image that works on swagger but it doesn't too and I don't think it's because the image size. Error: "POST - BusinessController[upload_profile_image] /api/business/profile" ([{'type': 'missing', 'loc': ('file', 'file'), 'msg': 'Field required'}],) Unprocessable Entity: /api/business/profile [13/Nov/2024 22:18:17] "POST /api/business/profile HTTP/1.1" 422 83 -
I encountered a 502 Bad Gateway error on my deployed Django website
I encountered a 502 Bad Gateway error on my deployed Django website. The site was working fine until I made some modifications to enable email functionality with my website's extension. It seems that Gunicorn is not running due to a 'permission denied' error. when I'm trying to make mails with my website extension and do reboot my website has been disabled here is the error that I encounted : root@vps-etu:~# source /www/wwwroot/django-project/f37529200a260f346c11edf_venv/bin/activate (51273d353f37529200a260f346c11edf_venv) root@vps-etu:~# cd /www/wwwroot/django-project (51273d353f37529200a260f346c11edf_venv) root@vps-etu:/www/wwwroot/django-project# sudo systemctl status gunicorn × gunicorn.service - gunicorn daemon for Django project Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor pres> Active: failed (Result: exit-code) since Wed 2024-11-13 15:14:54 CET; 3h 1> Process: 131999 ExecStart=/www/wwwroot/django-project/f37529200a260f346> Main PID: 131999 (code=exited, status=3) CPU: 1.115s Nov 13 15:14:52 vps-etu systemd[1]: Started gunicorn daemon for Djang> Nov 13 15:14:54 vps-etu systemd[1]: gunicorn.service: Main process ex> Nov 13 15:14:54 vps-etu systemd[1]: gunicorn.service: Failed with res> Nov 13 15:14:54 vps-etu systemd[1]: gunicorn.service: Consumed 1.115s> lines 1-11/11 (END) (51273d353f37529200a260f346c11edf_venv) root@vps-etus:/www/wwwroot/django-project# sudo journalctl -u gunicorn -n 50 --no-pager Nov 13 12:27:22 mail.etu.dz systemd[1]: Started gunicorn daemon for Django project. Nov 13 12:27:22 mail.etu.dz systemd[76558]: gunicorn.service: Changing to the requested working directory failed: Permission denied Nov 13 12:27:22 mail.etu.dz systemd[76558]: gunicorn.service: Failed at step … -
Nginx can not find static files in my docker instance
Hi I have a Django application that I'm preparing for deployment on a local network using docker. My Nginx proxy is unable to find the static files here is my docker-compose-deploy.yaml file: services: app: build: context: . volumes: - ./inventory/static:/vol/web/static - ./qr_codes:/vol/web/qr_codes proxy: build: context: ./nginx volumes: - static:/app/static/ ports: - "8080:8080" depends_on: - app db: image: postgres restart: always volumes: - ./data/db:/var/lib/postgresql/data ports: - "5432:5432" environment: POSTGRES_DB: Inventory POSTGRES_USER: postgres POSTGRES_PASSWORD: 123456 pgadmin: image: dpage/pgadmin4 restart: always ports: - "5050:5050" environment: PGADMIN_DEFAULT_EMAIL: jacob@me.com PGADMIN_DEFAULT_PASSWORD: 123456 PGADMIN_LISTEN_ADDRESS: 0.0.0.0 PGADMIN_LISTEN_PORT: 5050 volumes: static: postgres_data: here is my DockerFile for my Django app: # Use the official Python image from the Docker Hub FROM python:3.8-alpine # Set environment variables ENV PATH="/scripts:${PATH}" # Install dependencies COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install --no-cache-dir -r /requirements.txt RUN apk del .tmp # Create and set permissions for directories RUN mkdir -p /app/vol/web/static /app/vol/web/qr_codes RUN adduser -D user RUN chown -R user:user /app/vol RUN chmod -R 755 /app/vol # Copy project files COPY ./ /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* # Set the user to 'user' USER user # Command to run the … -
On every api request list in add_where method get appended it is not resetting
I am trying to create custom manager in django rest framework that interacts with athena. Although I am facing strange issue that everytime I hit the endpoint with filters it gets appended in list where_conditions=[] on each request. It should not happen that actually makes the query that converts into SQL invalid. i want to reset the where_conditions list on each request. filter_class/base.py from apps.analytics.models.filter.fields.filter import FilterField from apps.analytics.models.filter.fields.ordering import OrderingField from apps.analytics.models.filter.fields.search import SearchField from apps.analytics.models.manager.query.utils import ModelQueryUtils class BaseFilterClass: _ordering_filter_query_key = "ordering" _search_filter_query_key = "search" def __init__(self, request): self._request = request @property def filter_params(self): if getattr(self.Meta, "filter_fields", None): req_query_params = {**self._request.query_params} for i in req_query_params: if isinstance(req_query_params[i], list): req_query_params[i] = req_query_params[i][0] if req_query_params and req_query_params.get("search"): del req_query_params["search"] req_query_params_key = set(req_query_params.keys()) valid_filter_params = self.Meta.filter_fields.declared_filter_params.intersection(req_query_params_key) params = {key: self.Meta.filter_fields.get_processed_value(key.split('__')[-1], req_query_params[key]) if "__" in key else req_query_params[key] for key in valid_filter_params} return ModelQueryUtils.FilterInput(params, ModelQueryUtils.FilterInput.JoinOperator.AND) @property def ordering_params(self): if getattr(self.Meta, "ordering_fields", None): req_query_params_ordering_params = self._request.query_params and self._request.query_params.get( self._ordering_filter_query_key) if req_query_params_ordering_params: declared_ordering_params = self.Meta.ordering_fields.declared_ordering_params return ModelQueryUtils.OrderInput( [str(param) for param in req_query_params_ordering_params.split(",") if ((param.startswith("-") and param[1:]) or param) in declared_ordering_params]) @property def search_params(self): if getattr(self.Meta, "search_fields", None): req_query_params_search_param = self._request.query_params and self._request.query_params.get( self._search_filter_query_key) params = {} if req_query_params_search_param: for key in self.Meta.search_fields.declared_search_params: params[key] = … -
i cant send email with aws-ses with python
setting.py = EMAIL_BACKEND = 'django_amazon_ses.EmailBackend' AWS_SES_REGION = env('AWS_SES_REGION') AWS_SES_SENDER_MAIL = env('AWS_SES_SENDER_MAIL') AWS_SES_SENDER = env('AWS_SES_SENDER') AWS_ACCESS_KEY = env('AWS_ACCESS_KEY') AWS_KEY_ID = env('AWS_KEY_ID') views.py = try: subject = f"Registration Confirmation for {event.title}" message = f""" Hello {request.user.username}, You have successfully registered for the event: {event.title} Event Details: Date: {event.date} Location: {event.location} Description: {event.description} Thank you for joining! """ send_mail( subject, message, settings.AWS_SES_SENDER_MAIL, [request.user.email], fail_silently=False ) return Response({ 'message': 'Event joined and email sent.', 'email_status': 'sent' }, status=status.HTTP_200_OK) except Exception as e: return Response({ 'message': 'Event joined but email could not be sent.', 'email_error': str(e) }, status=status.HTTP_200_OK) else: return Response({'error': 'Event member limit reached. Cannot join.'}, status=status.HTTP_406_NOT_ACCEPTABLE) I am trying to send an e-mail when a function runs in views.py. I get HTTP 200, although there is no problem in the code, my email is not delivered, but I do not receive any errors Can anyone help? -
How to bold text in template using django template tags
For example if I want to put an 'About' section or a 'Terms of Use' section in my website and want some of the subheadings to be bolded or made into headers. How could I use template tags to achieve this? My plan is to write the About section or Terms of Use in my models and use template tags to format the subheadings and any text that should be bolded. Is there a better way to do this? -
Django + React (Vite)
I’m currently trying to set up Django as a backend with React (using Vite) for the frontend, and I’m running into a few questions about the best way to get them working smoothly together. Has anyone done this and could share some advice? Specifically: What’s the most effective way to connect Django’s backend to a React frontend? Should I be focusing on Django REST framework for handling data, or are there other approaches that work well? How do you usually handle user authentication between Django and React, especially if social authentication is involved? Are there any good tutorials, articles, or videos you’d recommend for getting the whole setup right, including managing serialization, data flow, and development environments? Thanks so much for any help or pointers you can share! -
How to parse the result of applicant__count in Model.objects.values("applicant", 'counter').annotate(Count("applicant")) to counter field?
I have a model with these fields although there are other fields but this is my MRE: class Application(models.Model): applicant = models.ForeignKey(User, on_delete=models.CASCADE, to_field='email') company = models.CharField(max_length=100) counter = models.PositiveIntegerField(editable=False, default=0) I want to find the number of applications in the table for each applicant and parse the value automatically to the counter field. In my views.py, I have been able to use: model = Application.objects.values('applicant','counter').annotate(Count("applicant")) which returns correct values: {'applicant': 'test@users.com', 'counter': 1, 'applicant__count': 2} {'applicant': 'second@user.org', 'counter': 1, 'applicant__count': 4} But I am unable to extract the value of `applicant__count` and parse it directly to the counter field in models.py. I tried using the update, update_or_create method but I'm not able to update the model. I also tried django signals pre_save and post_save but they keep incrementing every value. For example, one applicant can have many job applications but instead of returning the total number of job applications for an applicant, django signals increments all the applications in the table. Is there any way to automatically save the result of `applicant__count` to my counter field? I would really appreciate any help. -
docker static files django not serving
I'm trying to set up my Django application in Docker with Nginx to serve static and media files, and Traefik to act as a reverse proxy. I've been struggling to get static and media files to load correctly, despite trying multiple configurations. I want Nginx to handle static and media files while Traefik manages the reverse proxy and SSL. Below is my docker-compose.yml file. docker-compose.yml # PostgreSQL Database Service db: image: postgres:16-alpine restart: unless-stopped environment: POSTGRES_USER: ${DATABASE_USER} POSTGRES_PASSWORD: ${DATABASE_PASSWORD} POSTGRES_DB: ${DATABASE_NAME} volumes: - postgres_data:/var/lib/postgresql/data - ./pg_hba.conf:/var/lib/postgresql/data/pg_hba.conf networks: - backend-network healthcheck: test: [ "CMD-SHELL", "pg_isready -U ${DATABASE_USER}" ] interval: 10s timeout: 5s retries: 5 deploy: resources: limits: cpus: '1.0' memory: 2G # Redis Cache Service redis: image: redis:7-alpine restart: unless-stopped command: [ "redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD}" ] volumes: - redis_data:/data networks: - backend-network healthcheck: test: [ "CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "PING" ] interval: 10s timeout: 5s retries: 5 deploy: resources: limits: cpus: '0.5' memory: 512M # Django Web Application Service web: image: ganiyevuz/tana-backend:latest restart: unless-stopped command: > /bin/bash -c " ./wait_for_db.sh db 5432 && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn conf.wsgi:application --bind 0.0.0.0:8000 --workers 4 --threads 4 " volumes: - static_volume:/app/static - media_volume:/app/media expose: - "8000" … -
Best practices for using @property with Enum values on a Django model for DRF serialization
Question: I'm looking for guidance on using @property on a Django model, particularly when the property returns an Enum value and needs to be exposed in a Django REST Framework (DRF) serializer. Here’s my setup: I’ve defined an Enum, AccountingType, to represent the possible accounting types: from enum import Enum class AccountingType(Enum): ASSET = "Asset" LIABILITY = "Liability" UNKNOWN = "Unknown" On my Account model, I use a @property method to determine the accounting_type based on existing fields: # Account fields ... @property def accounting_type(self) -> AccountingType: """Return the accounting type for this account based on the account sub type.""" if self.account_sub_type in constants.LIABILITY_SUB_TYPES: return AccountingType.LIABILITY if self.account_sub_type in constants.ASSET_SUB_TYPES: return AccountingType.ASSET return AccountingType.UNKNOWN In Django views, I can use this property directly without issues. For example: account = Account.objects.get(id=some_id) if account.accounting_type == AccountingType.LIABILITY: print("This account is a liability.") Problem: When trying to expose accounting_type in DRF, using serializers.ReadOnlyField() does not include the property in the serialized output: class AccountDetailSerializer(serializers.ModelSerializer): accounting_type = serializers.ReadOnlyField() class Meta: model = Account fields = ['accounting_type', 'account_id', ...] I found that switching to serializers.SerializerMethodField() resolves the issue, allowing me to return the Enum value as a string: class AccountDetailSerializer(serializers.ModelSerializer): accounting_type = serializers.SerializerMethodField() class Meta: model … -
minio.error.S3Error: S3 operation failed; code: AccessDenied with root user access key
I have docker cluster with several containers such as minio as file storage and backend on django and it roughly looks like this: files: image: minio/minio container_name: files env_file: .env command: server /data --console-address ":9001" healthcheck: test: curl -I ${MINIO_EXTERNAL_ENDPOINT}/minio/health/live interval: 5s timeout: 5s retries: 5 volumes: - s3:/data ports: - 9000:9000 - 9001:9001 backend: build: ./backend container_name: backend env_file: .env volumes: - ./scripts/backend:/app/scripts healthcheck: test: curl --fail ${BACKEND_HC} || exit 1 interval: 10s timeout: 5s retries: 5 ports: - 8000:8000 depends_on: files: condition: service_healthy Everything was OK until today, when my SSD died and i was forced to use the older one. It has only 119 Gb of "real" space so i did Troubleshoot -> Purge Data in docker desktop (curse you, wsl/docker). And then cloned my project expecting it to start as usual. And then i was hit with the error in title. Here is useful part of stack trace: backend | [2024-11-13 15:50:41 +0700] [13] [INFO] Worker exiting (pid: 13) backend | [2024-11-13 15:50:41 +0700] [14] [ERROR] Exception in worker process backend | Traceback (most recent call last): ... backend | application = get_wsgi_application() backend | ^^^^^^^^^^^^^^^^^^^^^^ backend | File "/usr/local/lib/python3.11/site-packages/django/core/wsgi.py", line 12, in get_wsgi_applicati on backend … -
PyCharm 2024.2 not running Django tests correctly
Our project has extensive unit tests derived from rest_framework.test's APITestCase. This has always worked well - right-clicking on any Test file, class, or method, and selecting run has always generated a test configuration which has run the test effectively. But with the release of PyCharm 2024.2, this has mysteriously stopped working. I'm wondering if I'm overlooking a configuration setting or file somewhere. I have 2024.1.7 and 2024.2.4 both installed currently. In 2024.1.7, the test command issued by PyCharm is of this form, which works: python -u /home/vagrant/.pycharm_helpers/pycharm/django_test_manage.py test tests.api.test_my_code.MyCodeTest /opt/my-project-path In 2024.2.4, I get this command instead: python -u /home/vagrant/.pycharm_helpers/pycharm/django_test_manage.py /opt/my-project-path tests.api.test_my_code.MyCodeTest /Users/apollo/code/my-project-path I'm using a Vagrant virtual machine on my Mac to run my local server code. /opt/my-project-path is the path in the virtual server, while /Users/apollo/code/my-project-path is the path on my Mac. But more importantly, where did the word test go in this command, and how do I get it back?? The django_test_manage.py execution quite sensibly responds with: Unknown command: '/opt/my-project-path' -
Django REST & react-admin: Content-Range header missing
Using react-admin's ra-data-simple-rest DataProvider I would like to make a request to a django REST api. In Django I built the following custom pagination class which is supposed to expose the Content-Range header required by the DataProvider: from rest_framework import pagination from rest_framework.response import Response class ContentRangeHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): total_items = self.page.paginator.count # total no of items in queryset item_starting_index = self.page.start_index() - 1 # In a page, indexing starts from 1 item_ending_index = self.page.end_index() - 1 content_range = 'posts: {0}-{1}/{2}'.format(item_starting_index, item_ending_index, total_items) headers = {'Content-Range': content_range} return Response(data, headers=headers) In Django settings I put the following: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': '<myProject>.pagination.ContentRangeHeaderPagination', 'PAGE_SIZE': 10 } CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:5173', ] CORS_ALLOW_HEADERS = ( "accept", "range", "content-range", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) I keep getting the Error "The Content-Range header is missing in the HTTP Response. The simple REST data provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?" Any ideas what I am doing wrong? Unfortunately the ra-data-django-rest-framework Data … -
Django : Update sqlite database from html template
I've a database table called 'FormDB. I've written a program for CURD operation. For each row of db data there're two buttons 'EDIT' and 'DELETE'. The edit button is functioning when i give <form action = "" method = "POST"> in the HTML template. but when I redirect to the page where all the db data is showing, it's creating a new row of data instead of updating the existing value. view.py def EditData(request, id): a = FormDB.objects.get(id=id) nameupdate = a.name form = DjangoForm(request.POST) if request.method == "POST" and form.is_valid(): newname = form.cleaned_data['name'] b = FormDB.objects.get(id=id) b.name = newname b.save() return render(request, "editform.html", {'nameupdate' : nameupdate}) editform.html <body> <h1>EDIT PAGE</h1> <form action = "" method = "POST"> {% csrf_token %} {% if nameupdate %} <label>Enter new name: </label> <input type="text" name = "name" placeholder = {{ nameupdate }} REQUIRED> <input type="submit" value = "Submit Changes" ><br> {% endif %} </form> So, when I click on Submit Changes, it should redirect to the page where all dbdata is showing with updated value.