Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Django Dynamic Inline Forms as like admin (using Class Based Views)?
I have 2 Models class Section(models.Model): SECTION_CHOICES_CLASS_6_7_8 = [ ("A", "Section A"), ("B", "Section B"), ("C", "Section C"), ] SECTION_CHOICES_CLASS_9_10 = [ ("Sc", "Science"), ("Co", "Commerce"), ("Ar", "Arts"), ] name = models.CharField( max_length=2, verbose_name="Section", choices=SECTION_CHOICES_CLASS_6_7_8 + SECTION_CHOICES_CLASS_9_10, ) description = models.TextField( null=True, blank=True, help_text="Section Description, e.g. 'Section A of Class 6, total 30 students'", ) class_name = models.ForeignKey( Class, on_delete=models.CASCADE, help_text="Class", verbose_name="Class", ) teacher = models.OneToOneField( "Teacher", on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Section Teacher", ) seat = models.PositiveIntegerField(default=0) subjects = models.ManyToManyField(Subject, through="SectionSubject") class SectionSubject(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) teachers = models.ForeignKey(Teacher, on_delete=models.CASCADE) period = models.IntegerField( default=0, validators=[MaxValueValidator(10), MinValueValidator(0)] ) time = models.TimeField( null=True, blank=True, ) After configuring the admin, Using Tabular Inline How can I achieve the same kinda UI functionality in the template. Or suggest me a better way to make it comfortable for user. I've tried the inlineformset_factory forms.py class SectionSubjectForm(forms.ModelForm): class Meta: model = SectionSubject fields = "__all__" widgets = { "subject": forms.Select(attrs={"class": "form-select"}), "teachers": forms.Select(attrs={"class": "form-select"}), "period": forms.TextInput(attrs={"class": "form-control "}), "time": forms.TextInput(attrs={"class": "form-control "}), } SectionSubjectInlineFormset = inlineformset_factory( Section, SectionSubject, form=SectionSubjectForm, extra=1, can_delete=True, can_delete_extra=True, ) views.py class SectionCreateView(SuccessMessageMixin, CreateView): form_class = SectionForm template_name = "dashboard/section/section_add_or_update.html" success_message = "Section created successfully" def get_context_data(self, **kwargs): context … -
Open the link in new tab instead of the default action of a bootstrap template
I am using a bootstrap MyResume And there is this section This is the piece of code for it <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-1.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 1</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-1.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 1"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-2.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 3</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-2.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-3.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 2</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-3.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="App 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-4.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 2</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-4.jpg" data-gallery="portfolioGallery" class="portfolio-lightbox" title="Card 2"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" class="portfolio-details-lightbox" data-glightbox="type: external" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-5.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 2</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-5.jpg" … -
The dropdown in side-bar not working in django
i created a side-bar in my django template, the side bar is displayed, but the dropdown is not working, i checked every thing like code or environments and didn't found any reason for this problem . here is my code: sidebar.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Sidebar Menu for Admin Dashboard</title> <!--<link rel="stylesheet" href="style.css" />--> <!-- Fontawesome CDN Link --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" /> <script src="static/js/sidebar.js"></script> <style> .sidenav { height: 100%; width: 200px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; padding-top: 20px; } .sidenav a, .dropdown-btn { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 20px; color: #818181; display: block; border: none; background: none; width:100%; text-align: left; cursor: pointer; outline: none; } .sidenav a:hover, .dropdown-btn:hover { color: #f1f1f1; } .dropdown-container { display: none; background-color: #262626; padding-left: 8px; } .fa-caret-down { float: right; padding-right: 8px; } </style> </head> <body> <div class="sidenav"> <a href="#">Home</a> <button class="dropdown-btn">Dropdown <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> <a href="#">Contact</a> </div> <script> var dropdown = document.querySelector('.dropdown-container'); var dropdownBtn = document.querySelector('.dropdown-btn'); dropdownBtn.addEventListener('click', function() { dropdown.classList.toggle('show'); }); dropdown.addEventListener('click', function() { dropdown.classList.remove('show'); }); </script> … -
How to dump custom annotated fields to JSON fixture (Django)
I want to change token field to facebook_token in fixtures. I would be glad if your help me please 😁 models.py class FacebookAdAccounts(models.Model): id_ad = models.CharField(max_length=255) name_ad = models.CharField(max_length=255) currency = models.CharField(max_length=255, default='USD') is_active = models.BooleanField(default=True) business_account = models.ForeignKey(FacebookBusinessAccounts, on_delete=models.CASCADE, blank=True, null=True) token = models.CharField(max_length=510, blank=True, null=True) def __str__(self): return f'{self.id_ad} {self.name_ad} - {self.name_ad}' class FacebookTokens(models.Model): token = models.CharField(max_length=510) user_id = models.CharField(max_length=255) Given this model, I want to make fixtures of FacebookAdAccounts model to JSON format. I have this result: [ { "model": "facebook.FacebookAdAccount", "pk": 1, "fields": { "id_ad": "id_ad1", "name_ad": "name_ad_1", "currency": "USD", "is_active": true, "business_account": null, "token": "TOKEN_USER#1" }, ... ] I expect this result: [ { "model": "facebook.FacebookAdAccount", "pk": 1, "fields": { "id_ad": "id_ad1", "name_ad": "name_ad_1", "currency": "USD", "is_active": true, "business_account": null, "facebook_token": 4 }, ... ] I have tried this: FacebookAdAccounts._meta.model_name = "FacebookAdAccount" FacebookAdAccounts._meta.app_label = "facebook" subquery = FacebookTokens.objects.filter(token=OuterRef("token")).values("pk")[:1] queryset = FacebookAdAccounts.objects.annotate( facebook_token=Subquery(subquery) ) # I want facebook_token field to also be serialized json_data = serializers.serialize("json", queryset, indent=4) file_path = "data2.json" with open(file_path, "w") as file: file.write(data) -
problem in real time match-making and lobby implementation
I want to implement a real time match making using web sockets for a 2 playered game . I checked if there any waiting player by querying the data base (if channel_name``_2 = null). if yes connect incoming channel with waiting channel in database . However this fails in real time .for example consider two clients wanted to connect and there is single waiting player in db .Both get connected .here is my implementation. consumers.py import json import random from channels.generic.websocket import AsyncWebsocketConsumer from django.db import IntegrityError from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from .models import Game from .generator import Generator class LobbyConsumer(AsyncWebsocketConsumer): @database_sync_to_async def anyWaitingPlayer(self): return Game.objects.filter(channel_name_2=None).count() > 0 @database_sync_to_async def addPlayerToLobby(self , id , channel_name_1): try: Game.objects.create(gameid=id , channel_name_1 =channel_name_1).save() except IntegrityError as e: print(f"IntegrityError: {e}") @database_sync_to_async def waitingPlayerRoom(self , channel_name_2): waiting_games = Game.objects.filter(channel_name_2=None) earliest_game = waiting_games.earliest('time') id = earliest_game.gameid updated_record = Game.objects.get(gameid = id ) updated_record.channel_name_2 = channel_name_2 updated_record.save() return id @database_sync_to_async def getGroupId(self , channel_name): if Game.objects.get(channel_name_1 = channel_name).gameid == None : return Game.objects.get(channel_name_2 = channel_name).gameid async def connect(self): # Get the unique channel name # if Any waiting player , pair new player with waiting player if await self.anyWaitingPlayer(): id =await self.waitingPlayerRoom(self.channel_name) await … -
Filter queryset from filename field based on two words that appear one after the other Django
I have a Files table, which contains various fields, one of which is a filename. Within each one of the files in this table, there is a specific file that I'd like to retrieve, which is basically a terms and conditions. This filename will always have the words 'terms' and 'conditions' within the filename itself, and it will always be in that order. However, there could be other words surrounding both 'terms' and 'conditions'. For example, a filename could be 'my new terms and conditions' or 'my even better terms blah blah conditions'. I'm trying to write a queryset that will retrieve such a file using Regex but I'm not able to do so. So far, I have something like: file = Files.objects.filter( Q(filename__iregex=r'(^|\W){}.*({}|$)'.format("term", "condition")) ).first() but this doesn't work. -
pytest-django cannot find my existing module
to give a bit of context, I'm learning test unit in django and made an overly simple app to get started (Attach is the structure of my project). Here is my problem: When launching my unit tests on my django app, I get a ModuleNotFoundError event though the module exists. Sample of code: from django.shortcuts import get_object_or_404, render from .models import Book def book_infos(request, pk): book = get_object_or_404(Book, pk=pk) return render(request, "book_infos.html", {'book': book}) And the test associated: import pytest from django.urls import reverse from django.test import Client from django_pytest.library.models import Book from pytest_django.asserts import assertTemplateUsed @pytest.mark.django_db def test_book_infos_view(): client = Client() Book.objects.create(author="Jules Verne", title="20 milles lieues sous les mers") path = reverse('infos', kwargs={'pk': 1}) response = client.get(path) content = response.content.decode() expected_content = "<p>Jules Verne | 20 milles lieues sous les mers</p>" assert content == expected_content assert response.status_code == 200 assertTemplateUsed(response, "book_infos.html") My pytest.ini is as follow [pytest] pythonpath = . library tests DJANGO_SETTINGS_MODULE = django_pytest.settings python_files = test_*.py When I run pytest tests/library/test_views.py from django-pytest I get this result: platform win32 -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0 django: version: 4.2.7, settings: django_pytest.settings (from ini) rootdir: ...\django-pytest\django_pytest configfile: pytest.ini plugins: django-4.6.0 _ ERROR collecting tests/library/test_views.py _ ImportError while importing test module … -
Communication between AWS App Runner & EC2 instance
I've read about this subject in a couple of questions, but I haven't found the solution yet. So, I'm reasking almost the same question, as many others have done before: I have a Django app deployed on an App Runner server, and I have a backend process (in Python too) deployed on an EC2 instance. I need to be able to communicate values between this two servers, so when the user interacts with the django app, this calls the EC2 backend, processes the info and returns an output. Currently, I'm trying this like so: On my Django app I have this code. On button click it executes the ecconsult(): from django.shortcuts import render, HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json import requests def home(request): return render(request, 'index.html') def ecconsult(request): data_to_send = "communication test" response = requests.post('http://specific_host:specific_port/api/procesar', json=data_to_send) if response.status_code == 200: jsondatabe = response.text response_data = {'jsondatabe': jsondatabe} else: print('Error al procesar la call del backend') return render(request, 'index.html', response_data) And on my EC2 BackEnd server, I recieve the data like so: from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app, resources={r"/api/*": {"origins": "Django_app_domain"}}) @app.route('/') def hello(): print("accesing from outside") return … -
Trouble with Docker and Colima: Django Container Not Reflecting Code Changes Until Docker Restart
I'm using colima version 0.5.6 to run Docker. I have three containers: Django, .... I'm encountering a problem with the Django container.When I edit the code and save it, no changes appear on the interface, even after refreshing the page. The only way to see the changes is by executing the following command: docker restart django. the same config works. with docker descktop. i checked the yaml file and it already contains this line :restart: unless-stopped in the container config: services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: local_django container_name: django depends_on: - mysql volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.s3 - ./.envs/.local/.mysql ports: - "8000:8000" command: /start restart: unless-stopped platform: linux/x86_64 -
I got this 'TypeError: unsupported operand type(s) for +=: 'CartItems' and 'int' ' error while i am trying to add items to the cart
Views.py: def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItems.objects.get(product=product, cart=cart) cart_item += 1 cart_item.save() except CartItems.DoesNotExist: cart_item = CartItems.objects.create(product=product, quantity=1, cart=cart) cart_item.save() return redirect('cart_app:cart_details') i need cart_item incremented by one when an item is added to the cart -
How do I change the 12 hour format in django?
I have a DateTimeField in my model. When I add this field to admin.py , then the format shows as 4:00 pm , how can this be changed to 16:00? creation_date = models.DateTimeField(auto_now_add=True,) If I do this def time(self): return self.creation_date.timezone().strftime('%Y-%m-%d %H:%M:%S') that time field is not sorted -
what is the proper way to use aggregate in a complicated structured Django models
I have a Django app that represents a football league and should show scores points and other stuff, I need to create a function based on the models in this app to get the sum of goals, points, matches won, and positions in the current season, here are my models : **models.py class TeamName(models.Model): """ Stores Available team name to be picked later by users """ name = models.CharField(max_length=33, verbose_name=_( "Team Name"), help_text=_("Name of the team to be used by players")) logo = models.FileField(upload_to="uploads", verbose_name=_( "Logo Image"), help_text=_("The File that contains the team logo image"), null=True) def image_tag(self): """ This method created a thumbnil of the image to be viewed at the listing of logo objects :model:'teams.models.TeamName' """ return mark_safe(f'<img src="/uploads/{self.logo}" width="100" height="100" />') image_tag.short_description = _("Logo") image_tag.allow_tags = True class Meta: """ Defines the name of the model that will be viewied by users """ verbose_name = _("1. Team Name") def __str__(self) -> str: """ Make sure to view the name as string not the id or pk """ return str(self.name) class TeamStrip(models.Model): """ Stores Available team Strip to be picked later by users """ image = models.FileField(upload_to="uploads/uploads", verbose_name=_( "Team Strips"), help_text=_("A Strip to be used later by users")) … -
No data displayed in template from Django TemplateView
I am new to Djago and am trying to show the detail of an object from a list. Everything works from the code below except for the small matter of the detaill not being displayed. Here is my view `class PieceDetail(TemplateView): template_name = 'cabinets/piece_detail.html' def get_context_data(self, **kwargs): id = kwargs.get('pk') piece = get_object_or_404(Piece, pk=id) pprint(piece.pk) serializer = PieceSerializer(piece) pprint(serializer.data) return {'serializer': serializer, 'cabinets/piece_detail': piece.pk} Here is the urlpath('piece_detail/int:pk/', views.PieceDetail.as_view(), name = 'piece_detail'),` Here is the html {% extends "shared/base.html" %} {% load static %} {% block content %} </br> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <div class="btn-toolbar mb-2 mb-md-0"> <div class="btn-group me-2"> <a href="/cabinet/piece_list" ><button class="btn btn-primary"> Back </button></a> </div> </div> <br class="modal-body py-0"> <p>{{ serializer.data.id }}</p> <div class="container"> <div class="form-group"> {{ piece.description }} </div> <div class="form-group"> {{ piece.quantity }} </div> </div> </div> <p>The quantity shown is that usually used during construction of components</p> </div> {% endblock %} and here is some pprint output from the terminal on show detail selected 1 {'description': 'door rail', 'quantity': 2} [03/Nov/2023 12:16:05] "GET /cabinet/piece_detail/1/ HTTP/1.1" 200 14603 I have tried various different methods to get the data from the view to the template, but it still seems to go … -
How to implement accurate (hight resolution) zoom on DICOM images?
I use Pydicom and matplotlib to read and display DICOM images in a djANGO PROJECT inspired by Gregorio Flores dicom_django_viewer (thank to him). He use wheelzoom to add zoom fonctionnality but it seems that dicom image loss resolution when zoom is applied. Is there an efficient solutio to implement zoom on DICOM images? -
Infinite redirect loop on login after upgrade from Django 3.2 to 4.2
I've just upgraded from Django 3.2 to 4.2. All my tests now pass and runserver starts without issues. But then I get an infinite redirection loop when I try to display the home page: [03/Nov/2023 10:52:39] "GET /home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/home/ HTTP/1.1" 302 0 [03/Nov/2023 10:52:39] "GET /accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/accounts/login/%25253Fnext%25253D/home/ HTTP/1.1" 302 0 etc. until the browser detects the loop. Can anybody encountered this before tell me what is the change from Django 3.2 to 4.2 which causes this? I don't really know where to start looking. The exact same code base running in a Django 3.2 virtualenv is unbroken. -
DRF - detail not found if annotate a field from a non-existing-relation
I have a model with a nullable relation. class Relation(models.Model): name = CharField(max_length=255) class MyModel(models.Model): name = CharField(max_length=255) relation = ForeignKey(Relation, null=True, on_delete=models.SET_NULL) I pass the name of the relation into my Serializer. class MyModelSerializer(serializers.ModelSerializer): relation_name = serializers.CharField(read_only=true) class Meta: model = MyModel fields = '__all__' I annotate the relation name in the queryset of my viewset. class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all().annotate(relation_name=F('relation__name') serializer_class = MyModelSerializer Now when I try retrieve an instance of MyModel, which has not a relation to Relation, I got the response: { "detail": "Not found." } Otherwise, if the instance has a relation, the response looks like: { "id": 1, "name": "Test MyModel", "relation": 1, "relation_name": "Test Relation" } I've expected, that the response without a relation would look like: { "id": 1, "name": "Test MyModel", "relation": null, "relation_name": null } Does anyone have in the past a problem with annotation of non existing relation and has an idea how to deal with that? Best regards -
ContentNotRenderedError / image field in serializer (DRF)
I have a model for random Products which has an image field and a default image. I want to make it such that the client doesn't have to send an image when creating a new product through the API (using DRF). Below are the model, serializer and view # Model ... total_stock = models.PositiveIntegerField(default=0) product_image = models.ImageField(upload_to='images', blank=True, default='/static/images/default_product.png') # Serializer class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False) class Meta: model = Product fields = [ 'total_stock', 'product_image'... ] # View class ProductCreate(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer = ProductSerializer() In order for the view to accept a payload without an image, I have to modify the serializer like this: class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) # added "required=False" But when I do that, I get the error: The response content must be rendered before it can be iterated over. Request Method: GET Request URL: http://127.0.0.1:8000/product/create/ Django Version: 4.0.5 Exception Type: ContentNotRenderedError Exception Value: The response content must be rendered before it can be iterated over. Exception Location: .../lib/python3.10/site-packages/django/template/response.py, line 127, in __iter__ Python Executable: /.../bin/python Python Version: 3.10.4 ... All the other questions I have investigated are with respect to queries but I'm not making a query … -
Nuxt2-Keycloak-Django Rest Framework Authentication
I've integrated keycloak authentication in my nuxt2 application using nuxt-auth, here my auth configration in nuxt.config.js auth: { strategies: { oidc: { scheme: "openIDConnect", clientId: process.env.KEYCLOAK_CLIENT_ID, endpoints: { configuration: `/keycloak/`, }, responseType: "code", grantType: "authorization_code", scope: ["openid", "profile", "email"], codeChallengeMethod: "S256", token: { property: "access_token", type: "Bearer", name: "Authorization", maxAge: 300, }, refreshToken: { property: "refresh_token", maxAge: 60 * 60 * 24 * 30, }, // acrValues: "1", }, }, redirect: { login: "/", logout: "/", home: `/user`, }, }, Now I want to authenticate my django rest framework API with this client keycloak accesstoken I tried django-oauth-toolkit package for keycloak authentication. and configration INSTALLED_APPS = [ ... "oauth2_provider", "rest_framework", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), } OAUTH2_PROVIDER = { "SCOPES": { "openid": "OpenID Connect", "profile": "User profile information", "email": "User email address", } } while I tried to call my api with the nuxt keycloak access token it returns me 401-Authentication credentials were not provided. Please help me with this scenario or tell me if it possible to authenticate django APIs with nuxt keycloak accesstoken NB: Client used in nuxt and django are different. -
how to customize nested fields serializer through another serializer in drf
File class and Animation are related together And I want to somehow implement the following code serial = AnimationSerializer(instance=Animation.objects.get(id=animationn_id), fields=["duration", "age_rating", {"file": ["name", "description"]}]) or serial = FileSerializer(instance=File.objects.get(id=file_id), fields=["name", "description", {"animations": {"fields": ["duration", "made_by"], "many": True, "read_only": False}}]) actually i don't want write several serializer class. I want to write as little code as possible to achieve this goal. I want to implement the methods of creation and retrieval and update for two models using 2 serializers so that I can use one of the two serializers to create, retrieve, and update instances of that one model. i have two simple model : class File(models.Model): video = 1 PDF = 2 word = 3 all_types = ( (video, "video"), (PDF, "PDF"), (word, "word"), ) type = models.PositiveSmallIntegerField(choices=all_types) name = models.CharField(max_length=30) description = models.CharField(max_length=50) class Animation(models.Model): file = models.ForeignKey("File", on_delete=models.CASCADE, related_name="animations") duration = models made_by = models..CharField(max_length=30) age_rating = models.PositiveSmallIntegerField(validators=[validators.MaxValueValidator(24)]) and i have these serializer class: class DynamicFieldsCategorySerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed … -
Unknown output_field type in Subquery in Django
I have the following models: class Parent1(models.Model): name = models.CharField(max_length=255) class Parent2(models.Model): parent1 = models.ForeignKey(Parent1) label = models.CharField(max_length=255) class Child(models.Model): parent1 = models.ForeignKey(Parent1) parent2_label = models.CharField(max_length=255) # other fields I am trying to execute the below queries: parent1 = Parent1.objects.first() sq = Child.objects.filter(parent1=OuterRef("parent1"), parent2_label=OuterRef("label")) parents_2 = Parent2.objects.filter(parent1=parent1).annotate(children=Subquery(sq)) So basically what I am trying to execute is if Child model had a fk to Parent2 then I would have prefetched the related child instances of the Parent2 instances. Now at present there is no fk relation between Child and Parent2. The relation is based on the label field between those two. fk will be added later but before that for backwards compatibility I have to execute this query. Now when I try to execute this query then I am getting the following error: FieldError: Cannot resolve expression type, unknown output_field I am using Postgresql db. Now what will be the output_field for the above query that I have to pass? -
save() causing the creation of a new record when trying to update an existing record
So I have the following model: class Session(models.Model): sessionid = models.CharField(max_length=10, primary_key=True) forgepass = models.ForeignKey(ForgeProfile, on_delete=models.CASCADE) programid = models.ForeignKey(TrainingProgram, on_delete=models.PROTECT) program_day = models.IntegerField() hours = models.IntegerField() session_date = models.DateField(default=timezone.now()) verified = models.BooleanField(default=False) def save(self, *args, **kwargs): session_count = Session.objects.all().count() self.sessionid = 'S' + self.forgepass.forgepass + id_gen(session_count) super().save(*args, **kwargs) def __str__(self): return '{} - {}'.format(self.sessionid, self.session_date) When updating an existing record on the backend, a new record will be created with a new sessionid and the updated values instead, while keeping the old record. What exactly am I missing here? -
Django: Streams from cameras stop if there are two of them on a page
I made an application that shows the image from the camera after detection and calculation in real time. I show the video on the site. If I show a stream from one camera <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> it works perfectly. If there are two streams, but from the same camera - ideal. <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> If two streams are from different cameras, it freezes almost completely. I open each stream separately - perfect. http://127.0.0.1:8000/video_feed/ http://127.0.0.1:8000/second_video_feed/ What could be the reason? Even tried threading, but to no avail. The final version of views.py I enclose from django.views.decorators import gzip from .object_counter import CountObject_Camera1, VideoCapture_Camera1, CountObject_Camera2, VideoCapture_Camera2 from django.shortcuts import render import cv2 import threading rtsp_url1 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" rtsp_url2 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" count_object_instance1 = CountObject_Camera1(rtsp_url1) count_object_instance2 = CountObject_Camera2(rtsp_url2) video_capture1 = VideoCapture_Camera1(rtsp_url1) video_capture2 = VideoCapture_Camera1(rtsp_url2) lock1 = threading.Lock() lock2 = threading.Lock() @gzip.gzip_page def video_feed(request): def generate(camera_instance, count_object_instance, lock): while True: with lock: frame = camera_instance.read() annotated_frame = count_object_instance.process_frame(frame) _, buffer = cv2.imencode('.jpg', annotated_frame) frame_bytes = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n') return StreamingHttpResponse(generate(video_capture1, count_object_instance1, lock1), content_type='multipart/x-mixed-replace; boundary=frame') def … -
Drawing price history chart in Django
i am trying to draw a chart with django, the django view will fake some data(price and timestamp) html will draw line chart using chartjs. The console display chart.js:19 Uncaught Error: This method is not implemented: Check that a complete date adapter is provided. even though i follow this chartjs getting start and include <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> i also run npm install moment chartjs-adapter-moment --save-dev and npm install chart.js My views: def price_history(request, product_id): form = ProductNameForm() product = Product.objects.get(pk=product_id) # Create some dummy price history data for testing price_history_data = [] today = datetime.now() for i in range(1, 11): # Generate data for the last 10 days date = today - timedelta(days=i) price = float(product.current_price - (randint(1, 10) * 10)) # Example: Randomly decrease price price_history_data.append({ 'timestamp': date.strftime('%Y-%m-%d'), 'price': price, }) return render(request, 'price_history.html', {'product': product, 'price_history_data': price_history_data, 'form':form}) My template: {% block content %} <div class="container"> <h1>Price History</h1> <!-- Price history chart container --> <!-- Price history chart container --> <canvas id="priceChart" width="400" height="200"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script> <script> // Extract timestamps and prices let timestamps = {{ price_history_data | safe }}; let prices = timestamps.map(entry => entry.price); timestamps = timestamps.map(entry => entry.timestamp); // Get the canvas element … -
I can't log in with a registered user
I can register my users, but I can't log in with these users. After registering the users, they are automatically logged in, so this is the only moment I can access the Profile area. After logging out, I can't log in any user except my superuser. I have try several ways and can't seem to figure it out. here are my files: #models.py from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("O endereço de email é obrigatório") user = self.model( username=username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username=username, email=email, password=password, ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Cadastro(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=75, unique=True) data = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "username" EMAIL_FIELD = "email" REQUIRED_FIELDS = ["email"] def __str__(self): return self.username #forms.py from django import forms from base.models import Cadastro from django.contrib.auth.forms import AuthenticationForm class CadastroForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Cadastro fields = ("username", "email", "password") class LoginForm(AuthenticationForm): username = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), required=True ) password = forms.CharField( widget=forms.PasswordInput(attrs={"class": … -
How to set refresh token expire of drf social oauth2?
How can we set refresh token expire of drf social oauth2. I try to use this but not work(Work only access token). OAUTH2_PROVIDER = { 'REFRESH_TOKEN_EXPIRE_SECONDS': 1, #set to 1 second for test 'ROTATE_REFRESH_TOKEN': false, } Anyone can help?