Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to filter django submodel dropdowns to only appear for the current user?
I have a main model named Event. This event has a submodel named Pogram, and the Program model has a submodel called DetailedProgram. I have been able to filter the app to make sure that only the logged in user can post for themself. Also, I have managed to make the user only access Events created by the loged in user. However, I am struggling to find a way to make the user logged in only access the submodel Program's objects as all the object's are being displayed. Please advise. I tried using the very filter (user filter) used on the Program model but to no avail -
django object filter using AND,between date
pls my below code not working but i noticed if i remove statu='Approved' it worked fine but i want it to be part ofthe condition statment. pls help sdate = request.POST['sdate'] edate = request.POST['edate'] acct =int(request.POST['acct']) actyp = request.POST['actyp'] d1 = datetime.strptime(sdate, "%Y-%m-%d") d2 = datetime.strptime(edate, "%Y-%m-%d") now = datetime.now() dte = now.strftime("%Y-%m-%d") stmtacct = Tbltrn.objects.filter(accountno=acct,statu='APPROVED',date__gte=d1,date__lte=d2) context={ 'mysere': stmtacct, 'strdate': sdate, 'endate': edate, 'fname': fname, 'acct': acct, 'actyp': actyp } -
How to serve static files from different locations in NGINX
I want to serve static files from different two Django apps. one static files for the admin app and other static files for the pages app. Note: I am aware of collectstatic command. What I would like to know is that, if there is a way to serve static files from two different directories under /static/ location. If one location failed, check the other location. Locations for static files: /webapps/project/admin/static and /webapps/project/pages/static location /static/ { alias /webapps/project/admin/static/; alias /webapps/project/pages/static/; } This raise an error of duplicate alias directive Here is what I wish to have. To check the files in @static, if file not found check in the @static2 block. server { server_name x.x.x.x; client_max_body_size 8M; access_log /webapps/logs/project/nginx-access.log; error_log /webapps/logs/project/nginx-error.log; location /static/ { try_files $uri @static @static2; } location @static { root /webapps/project/pages/; } location @static2 { root /webapps/project/admin/; } } How should I serve both static files from two directories. -
Trouble deploying Django app to AWS Elastic Beanstalk
I'm having the following issues when running eb deploy: 2024/04/29 18:00:10 [warn] 28747#28747: could not build optimal types_hash, you should increase either types_hash_max_size: 1024 or types_hash_bucket_size: 64; ignoring types_hash_bucket_size Apr 29 18:00:15 ip-172-31-85-53 web[28824]: ModuleNotFoundError: No module named 'authentication' authentication is a Django app. These are the two main errors found from the logs provided after updating the environment from eb deploy. I'm following this tutorial I found: https://testdriven.io/blog/django-elastic-beanstalk/ I've had to change a couple things obviously due to different project structure/details but I'm not understanding why these errors are coming up. I have not yet set up AWS RDS for PSQL, but I plan on doing that once I fix these errors. I am also using React as a frontend but I have not yet configured the environment for that either. Here are some of my config files: # .ebextensions/01_django.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "campusconnect.campusconnect.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "campusconnect.campusconnect.wsgi:application" # .elasticbeanstalk/config.yml branch-defaults: aws-psql: environment: SE-Dev-Project-dev group_suffix: null global: application_name: SE-Dev_Project branch: null default_platform: Python 3.11 running on 64bit Amazon Linux 2023 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: git workspace_type: Application And my project structure: . ├── .ebextensions │ ├── 01_django.config … -
Nginx configuration not working correctly with gunicorn
I have a Django app hosted on a GCP instance that has an external IP, the Django is running using Gunicorn on port 8000, when accessing the Django using EXTERNAL_IP:8000 the site works perfectly, but when trying to access the Django using EXTERNAL_IP:18000 the site doesn't work(This site can’t be reached), how to fix the Nginx configuration? All the IPs will be replaced with the domain once testing is done. In Django settings: ALLOWED_HOSTS = ['*'] gunicorn_config.py command = "/home/path/venv/bin/gunicorn" pythonpath = "/home/path/venv/bin/python" bind = "127.0.0.1:8000" workers = 3 supervisor.conf [program: procurement] directory = /home/path/ command = /home/path/venv/bin/gunicorn namet_system.wsgi:application --bind 0.0.0.0:8000 user = user stdout_logfile = /home/path/logs/gunicorn_supervisor.log redirect_stderr = true environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 nginx_config upstream procurement_server { server 127.0.0.1:8000 fail_timeout=0; } map $http_origin $cors_origin { default "null"; } server { server_name LB_IP1 LB_IP2 EXTERNAL_IP; listen 18000 ; if ($http_x_forwarded_proto = "http") { set $do_redirect_to_https "true"; } if ($do_redirect_to_https = "true") { return 301 https://$host$request_uri; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_set_header X-Forwarded-Port $http_x_forwarded_port; proxy_set_header X-Forwarded-For $http_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://procurement_server; } } -
How do I create/update/retrieve multiple Models in one View in Django Rest Framework
I have a Business model and Order model. Businesses can order furniture in our website. A user creates an account and makes an order. Since he is a new user, he is not associated to any Business. In the order form, he will give the information about his business and some information related to current order. A new Business record and Order record will be created with the given info. There's a foreign key for Business in Order table. If he wants to create a second order, since he has already a business, he will have the business info pre-filled in his form. When he gives the order data and submits, backend won't create a new Business record. It only creates Order record and store the Business reference. How do I achieve this in single endpoint to create update and retrieve? # serializers.py import time class BusinessSerializer(serializers.ModelSerializer): class Meta: model = Business fields = '__all__' def create(self, validated_data): timestamp = int(time.time()) random_number = random.randint(100,999) validated_data['code'] = f'BUSINESS-{timestamp}' validated_data['status'] = 'CREATED' return super().create(validated_data) class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def create(self, validated_data): timestamp = int(time.time()) random_number = random.randint(100,999) validated_data['code'] = f'ORDER-{timestamp}' validated_data['status'] = 'CREATED' return super().create(validated_data) # … -
Django request process data saving
I have django asgi app. And I want to have POST /routes handling, that would be something like: async def routes(request): if is_first_request_from_user(request): generator = RouteGenerator() save_generator_for_user(request, generator) return await generator.first_generate() else: generator = get_generator_for_user(request) return await generator.further_generate() And RouteGenerator object has state and stores some complex data like heap, maps, sets etc. and it is attached to each user and should be stored in local memory. So how to implement it in django? Should I use some kind of django cache? I'm not really good at python, especially django, and for me the most straightforward solution would be to store some global map {request_id: route_generator}, however while googling nowhere was mentioned such a simple approach -
How to build single query in Django with related models and count
I did not use the Django for a years and tried to modify some old codebase today. I have models: class MetaTemplate(CreatedModifiedBase): type = models.CharField(max_length=200) class Project(CreatedModifiedBase): name = models.CharField(max_length=200, unique=True) members = models.ManyToManyField( User, through=ProjectMembership, related_name="annotation_projects_as_member", blank=True, ) metatemplate = models.ForeignKey( MetaTemplate, on_delete=models.SET_NULL, related_name="project", null=True ) class Dataset(CreatedModifiedBase): name = models.CharField(max_length=200) project = models.ForeignKey( Project, related_name="datasets", on_delete=models.CASCADE ) class Task(CreatedModifiedBase): dataset = models.ForeignKey( Dataset, related_name="tasks", on_delete=models.CASCADE, null=True ) class Completion(CreatedModifiedBase): task = models.ForeignKey(Task, related_name="completions", on_delete=models.CASCADE) annotator = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="annotation_completions", null=True, ) I have a method which returns number of incomplete Tasks. def get_incomplete_tasks(self, user, project_id, target_completion_count) -> int: return ( Task.objects.annotate(counts=Count("completions")) .filter( counts__lt=target_completion_count, dataset__project=project_id, ) .exclude(completions__annotator=user) .prefetch_related( "completions", "completions__annotator", "dataset__project" ) .count() ) Now I want to rework this method and return the number of incomplete Tasks for each of the projects in single query without project_id and target_completion_count passed by user. So basically the same logic but per in one query per Project. I wrote this code: t = Task.objects.filter( dataset__project=OuterRef('id') ) completion_count_subquery = t.exclude(completions__annotator=user).prefetch_related( "completions", "completions__annotator").order_by().annotate( counts=Func(F('id'), function='Count')).values('counts') objects = Project.objects.all().annotate(task_count=Subquery(completion_count_subquery)).prefetch_related("members", "metatemplate") But I am not able to include counts__lt=target_completion_count part in the proper way. Also tried this query t = Task.objects.all().annotate(counts=Count("completions")).filter(dataset__project = OuterRef('id'), counts__lt=OuterRef("target_completion_count")).order_by().values("completions") … -
Google provider not showing up in Django admin and getting ImproperlyConfigured error after setting up django-allauth
I'm encountering two issues after setting up Django Allauth for authentication in my Django project: 1. The Google provider option is not showing up in the dropdown list when navigating to the "Add social application" section of the Django admin panel. 2. When attempting to access the sign-in page (/enrolled/sign-in/), I'm getting an "ImproperlyConfigured" error with the message "unknown provider: google". I followed the setup instructions provided in the Django Allauth documentation and added the necessary configuration for the Google provider in my settings file. Despite this, I'm facing these issues. Here is my settings.py file: """ Django settings for temp project. Generated by 'django-admin startproject' using Django 4.2.11. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-x5242^+u0mit3om8z)e=8i$(vi!o@7$ks1om9*@7r(lo(=!3y!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
problem not loading image with name persian in django
problem not loading image with name persian in django enter image description here enter image description here I added these two to the setting file FILE_CHARSET = 'utf-8' DEFAULT_CHARSET = 'utf-8'enter image description here -
Django widget tweaks manually set input field value?
I am looking for an easy way to manually set a form field (ModelForm) value in a Django Template. I've tried this {% render_field my_form.my_field value=200 %} (tried with and without quotes) but it doesn't work, field is still displaying 0. I can't populate those fields in advance (overwriting form initialization in a ModelForm, or similar), because I will need to change input values dynamically later on, based on other input fields (using HTMX). -
how to attach a file, uploaded by customer, to email in Django?
i'm trying to make a form where customer can add a file and send it via page. No file save in database just attach it and send to company email. Here are the details forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=120, widget=forms.TextInput(attrs={'placeholder': 'Your name'})) phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'})) email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'example@example.com'})) customer_details = forms.FileField(required=False, widget=forms.ClearableFileInput( attrs={'multiple': False, 'allow_empty_file': True})) message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Your message'})) emailsender.py from django.core.mail import send_mail class EmailSender: def __send_email(self, subject, message, recipient_list): send_mail( subject=subject, message=message, from_email=EMAIL_HOST_USER, auth_password=EMAIL_HOST_PASSWORD, recipient_list=recipient_list ) def send_submitted_order(self, request, offers): subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}' recipient_list = [RECIPIENT_EMAIL] form = ContactForm(request.POST, request.FILES or None) if form.is_valid(): customer_email = form.cleaned_data['email'] customer_phone = form.cleaned_data['phone_number'] customer_message = form.cleaned_data['message'] **customer_details = form.cleaned_data['customer_details']** message = render_to_string( 'cart/message_for_company.html', {'customer_message': customer_message, 'customer_email': customer_email, 'customer_phone': customer_phone, 'offers': offers} ) self.__send_email(subject, message, recipient_list) def send_message_to_customer(self, request, offers): form = ContactForm(request.POST, request.FILES or None) subject = f'Order {datetime.now().strftime("%Y-%m-%d %H:%M:%S.")}' if form.is_valid(): customer_email = form.cleaned_data['email'] customer_phone = form.cleaned_data['phone_number'] customer_message = form.cleaned_data['message'] **customer_details = form.cleaned_data['customer_details']** message = render_to_string( 'cart/message_for_customer.html', {'customer_message': customer_message, 'customer_email': customer_email, 'customer_phone': customer_phone, 'offers': offers} ) recipient_list = [customer_email] self.__send_email(subject, message, recipient_list) and minimalistic template for render_to_string <h1>Order</h1> {% for offer in offers %} {{ offer.name }} - {{ offer.quantity }} {% … -
I cannot upload multiple files in my html template
I am making a site where you can send your game with multiple additional images. I upload images and they are send to API. Then when you open the game page there is a request to API and it returns the image. The problem is that when I try to upload multiple images only last one uploads. This is my html form {% extends "base.html" %} {% block body %} <form id="chloroform" action="/senddata" method="post" enctype=multipart/form-data > <h2>Загрузить игру</h2> <fieldset> <legend>Основные данные</legend> <label for="title">Название игры:</label> <input type="text" name="title" id="title" maxlength="24" required> </fieldset> <div class="container col-md-6" style="float:right; position: relative; top: -100px; left: 20px"> <p style="outline:2px solid #555; border-radius:5px; width: 300px; height: 300px;"> <img id="frame" src="" class="img-fluid" style="max-width: 300px; max-height: 300px; " /> </p> <div class="mb-5"> <input class="form-control" name="prev" type="file" id="formFile" onchange="preview()" accept="image/png" required> </div> </div> <script> function checkImage(file) { return new Promise((resolve, reject) => { if (file.type === 'image/png') { const img = new Image(); img.onload = () => { if (img.width === img.height) { resolve(); } else { reject(new Error('Изображение должно быть квадратным!')); } }; img.src = URL.createObjectURL(file); } else { reject(new Error('Изображение должно быть в формате PNG!')); } }); } function preview() { const file = event.target.files[0]; checkImage(file) .then(() => … -
Why dropdown field is disappeared in Django Rest Framework when using custom serializer for a field?
I am trying to use Django, DRF, ViewSet and Serializers to build a simple weblog. I have a main app and inside it: main\models.py: from django.db import models from django.contrib.auth.models import User class TimeStampMixin(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Category(TimeStampMixin): name=models.CharField(max_length=255) parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class PostStatus(models.Model): status = models.CharField(max_length=50) def __str__(self): return self.status def get_draft_status(): return PostStatus.objects.get_or_create(status='draft')[0].id class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=200) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) status = models.ForeignKey(PostStatus, on_delete=models.CASCADE, default=get_draft_status) def __str__(self): return self.title class RelatedPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='related_posts') related_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='related_to') def __str__(self): return f"{self.post.title} related to {self.related_post.title}" main\serializers.py: from rest_framework import serializers, status from rest_framework.response import Response from .models import Post, RelatedPost, PostStatus, Category class PostStatusSerializer(serializers.ModelSerializer): class Meta: model = PostStatus fields = '__all__' class RelatedPostSerializer(serializers.ModelSerializer): class Meta: model = RelatedPost fields = '__all__' class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): related_posts = serializers.SerializerMethodField() category = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' def get_related_posts(self, obj): related_posts = obj.related_posts.all() return [{'id': rp.related_post.id, 'title': rp.related_post.title} for rp in related_posts] def get_category(self, obj): if obj.category: … -
How can I display product photos from the database in Django?
I am putting the project on the Python host for the first time, which is written with Django, but when I try to fetch the photos of the products from the database, when I look at it with inspect, it shows the photo address correctly, but still nothing.I also set media root.The main folder of the project is not in public_html and I considered root, but the photos folder is in public_html These are media root and media url... MEDIA_ROOT = '/home/pythoni1/public_html/medias/' MEDIA_URL = '/media/' urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_module.urls')), path('', include('account_module.urls')), path('products/',include('product_module.urls')), path('user-account/',include('user_module.urls')), path('contact-us/',include('contact_us_module.urls')), path('articles/',include('article_module.urls')), path('order/',include('order_module.urls')) ] urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabasename', 'USER': 'mydatabaseuser', 'PASSWORD': 'mydatabase password', 'OPTIONS':{ 'autocommit':True } } } -
Django Rest Framework authentification in viewsets.ViewSet - need different permissions for each method
I'm facing an issue with Django REST Framework and viewsets.ViewSet. I'm trying to use the @permission_classes decorator to secure specific methods within a ViewSet, but it doesn't seem to be working as expected. When I apply the decorator, all methods require authentication, even when I specify different permissions for other methods. However, if I set the permission_classes attribute at the top of the ViewSet, it works as expected, but I need different permissions for each method. Do you have any advice on how I can achieve method-level permissions within a ViewSet? from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.decorators import action, permission_classes from rest_framework.response import Response class ProjectViewSet(viewsets.ViewSet): # Works as expected: all methods require authentication permission_classes = (IsAuthenticated,) @action(detail=False, methods=['get'], url_path='my') def list_investors_projects(self, request): # This method should be protected but allows access without authentication data = { 'message': "This is a custom GET method!", 'status': 'success' } return Response(data) @action(detail=False, methods=['get'], url_path='public', permission_classes=[AllowAny]) def public_projects(self, request): # This method allows public access data = { 'message': "Public projects", 'status': 'success' } return Response(data) I tried using the @permission_classes decorator above the list_investors_projects method to require authentication and custom permissions. I expected that this specific method … -
Mapping DRF GenericViewSet to http verbs via DefaultRouter
My goal is to implement adding a recipe to current user favorites list and removing it using Django Rest Framework 3.12.x. POST api/recipes/{int:recipe_id}/favorite DELETE api/recipes/{int:recipe_id}/favorite Request body is empty. User_id is got from self.context['request'].user.id. I.e. I need to serve POST and DELETE on the same URL. I implemented that against DefaultRouter in conjunction with GenericViewSet, but can't get this implementation serving DELETE. Only POST is served properly. The quesrtion is: what's wrong in the configuration? Why DRF returns 405 "Method Not Allowed" on DELETE calls and returns Http header Allow: POST, OPTIONS? Router configuration: from rest_framework import routers from api.views import FavoriteViewSet _v1_router = routers.DefaultRouter() _v1_router.register( r'recipes/(?P<recipe_id>\d+)/favorite', FavoriteViewSet, basename='favorite') View: class FavoriteViewSet( mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) http_method_names = ('post', 'delete', 'head', 'options',) queryset = Favorite.objects.all() serializer_class = FavoriteSerializer pagination_class = None def get_permissions(self): return super().get_permissions() def get_object(self): return super().get_object() def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) def destroy(self, request, *args, **kwargs): super().destroy(request, *args, **kwargs) def get_serializer_class(self): return super().get_serializer_class() def dispatch(self, request, *args, **kwargs): p1 = hasattr(self, 'get') p2 = hasattr(self, 'post') p3 = hasattr(self, 'delete') p4 = hasattr(self, 'options') return super().dispatch(request, *args, **kwargs) Having spent some time in the Debugger, I figured … -
DjangoAdmin: Use InlineModels without a parent model
I have a model (e.g. Contact with two fields, email and name). I'd like to add a custom view to Django Admin that allows for batch creation of multiple contacts. As they do not have a m2m-relationship, there is no way for me to add them as a InlineModelAdmin into another object. Is there a way to reuse the inline-code from Django admin to add a custom view for batch adding multiple contacts? As a strating point for adding custom views I'm currently at (which simply adds a add-page under the /add/multiple path). class ContactAdmin(admin.ModelAdmin): def get_urls(self): info = self.opts.app_label, self.opts.model_name urls = [ path( "add/multiple/", self.admin_site.admin_view(self.add_multiple_view), name="%s_%s_add_multiple" % info, ) ] return urls + super().get_urls() def add_multiple_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) -
Django formset queryset
I have two apps: accounting and projects. Every consumption item has a fk to project. Every production has a fk to a project. Production order has fk to production. produced product has fk to production order. consumption item has fk to produced product. While creating produced line, I want to create consumption line as formset. However, consumptionitemline_to_consume field should show instances from the related project, not all instances.. Below I tried to filter the dropdown however, it just does not work. here is forms class ProductionProducedLineConsumptionLineForm(forms.ModelForm): class Meta: model = ProductionProducedLineConsumptionLine fields = '__all__' widgets = { 'productionproducedline': forms.HiddenInput(), 'produced_kg_scrap': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), 'produced_kg_wastage': forms.NumberInput(attrs={'class': 'w-full input rounded-md'}), } def __init__(self, *args, **kwargs): production_id = kwargs.pop('production_id', None) # We'll pass this when initializing the formset in the view super(ProductionProducedLineConsumptionLineForm, self).__init__(*args, **kwargs) if production_id: production = ProductionProducedLine.objects.get(id=production_id) project = production.productionorderline.production.project self.fields['consumptionitemline_to_consume'].queryset = ConsumptionItemLine.objects.filter(project=project) # This does not work? ProductionProducedLineConsumptionLineFormSet = inlineformset_factory( ProductionProducedLine, ProductionProducedLineConsumptionLine, fk_name='productionproducedline', form=ProductionProducedLineConsumptionLineForm, # Use the custom form fields=('productionproducedline','productionproducedline_to_consume', 'consumptionitemline_to_consume','consumed_kg_product','produced_kg_scrap', 'produced_kg_wastage','wastage_return_customer'), extra=1, can_delete=True ) Here is view class ProductionProducedLineCreateView(CreateView): model = ProductionProducedLine form_class = ProductionProducedLineForm template_name = 'projects/produced_create.html' def get_form_kwargs(self): """Ensure the form is initialized with necessary kwargs.""" kwargs = super(ProductionProducedLineCreateView, self).get_form_kwargs() if self.kwargs.get('order_line_id'): kwargs['order_line_id'] = self.kwargs['order_line_id'] return … -
django postgreSql database connection problem
django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "Postgres" i will face this problem,I am beginner of django and POSTGRESQL How to solve this error -
Json on the front is incomplete, how to solve it?
I was serializing the data in django to pass it to bff and then to the front, I tested the requests to see if they were all "ok", the result of the direct request to django is ok, the request from bff is also ok, but when I went to see on the front it was incomplete with some of the fields missing, especially those with a compound name django rest api: { "id": 6, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": null }, { "id": 7, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": null }, bff: { "id": 6, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": "" }, { "id": 7, "chatID": XXXXXXX, "chatGroup": "XXXXXTESTXXXX", "firstName": "XXXX", "lastName": "XXXXX", "date": "XXXXXXXXX", "messageUser": "[XXXXXXXXX]", "status": "" }, front-end (Nextjs) { "chatGroup": "", "chatID": 0, "date": "XXXXXXXXX", "firstName": "", "id": 6, "lastName": "", "messageUser": "", "status": "" }, { "chatGroup": "", "chatID": 0, "date": "XXXXXXXXX", "firstName": "", "id": 7, "lastName": "", "messageUser": "", "status": "" } As I'm using typescript I made a type for the message type: export type MessageProps = { … -
Django app; Default User ID and model field 'Trader ID' not equal
I am creating an app to allow users to enter stock trades, for record keeping. I am using Django's default User model for login and authentication. My intention is to allow the logged in user to view only their own 'Entries', which is my model for stock record entries. To this end, I have created a one to Many relationship in my Entry model named 'trader' which points to the User ID (they should be the same). After logging in though, I don't see ANY trades on the screen even though they have been entered. I checked the Database, and the Entry.trader.id is the same number as the User.id (1 in the case of the first user created). Very strange. What I tried: I tried removing this line from my views.py EntryView class: entries = Entry.objects.filter(trader_id=logged_in_user).order_by("entered_date") and replacing it with: entries = Entry.objects.all() This works (proving that the records are there)but now it shows ALL of the entries. My models.py: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User class Entry(models.Model): ONEORB="1-Min ORB" FIVEORB="5-Min ORB" ABCD="ABCD" REVERSAL="Reversal" PROFIT="Profit" LOSS="Loss" RESULT_CHOICES = ( (PROFIT, "Profit"), (LOSS, "Loss") ) STRATEGY_CHOICES … -
django forms.ModelChoiceField not populating for edit form
I'm using same view and template for adding and editing the record in django. when I click on edit, all other fields are populated correctly, but modelChoiceField has no value. I've tried the solution Django ModelChoiceField is not filled when editing but not getting the desired results. Here's how I'm defining the field in model category = forms.ModelChoiceField( queryset=Category.objects.all(), empty_label="Select Category", required=True, to_field_name="name" ) Here's how I'm initializing my form form = myForm(request.POST or None, instance=form_instance, initial=models.model_to_dict(form_instance)) if I print the output from model_to_dict(form_instance) it show {'id': 18, 'title': 'test title', 'description': 'test description', 'material': 'blah blah', 'category': 2, 'user': 3} But on the form, model choice field has empty label. How do I populate it with NAME for category having pk=2 in above case ? -
How can I properly daemonize Celery to ensure it runs continuously without any issues?
My celery works locally but when I try celery daemonization at server side, it does not work. When I run this code I can see there is a successful connection with redis. code enter image description here But I am getting error, failed to start celery service..enter image description here Can someone please help me? I run of ideas how can I solve this issue? My recouces at my instance. 4 GB RAM, 2 vCPUs, 80 GB SSD. -
best method to do Django facial recognition by capturing the customer's
Good afternoon, what would be the best way to capture frames from the user's camera to use a function I have in Django views for facial recognition. What I'm trying now is to open a camera for the user on the web and from there remove the frames, but it's not working correctly as it's giving me the error "TypeError: Object of type bytes is not JSON serializable" and also I wanted the user to have that frame around the face saying that the image is being captured. I will send below what I have in views and in my js I appreciate any help or opinion offered @csrf_exempt def process_frame_faceRecognition(request): print("Processando frame...") if request.method == 'POST': frame_data = request.POST.get('frame_data') print(frame_data) frame_data = frame_data.split(',')[1] # Remover o prefixo 'data:image/png;base64,' frame_data_decoded = base64.b64decode(frame_data) frame_data = np.frombuffer(frame_data_decoded, dtype=np.uint8) frame = cv2.imdecode(frame_data, flags=1) # Agora você pode passar o frame para a função compare_faces() face_recognition = FaceRecognition() result = face_recognition.run_recognition(frame) # Verifique o tipo de resultado antes de retorná-lo if isinstance(result, HttpResponseRedirect): return JsonResponse({'message': 'redirecionamento', 'url': result.url}) else: # Coleta os valores do generator em uma lista result_list = list(result) # Codifica a imagem como base64 _, buffer = cv2.imencode('.png', frame) frame_base64 = …