Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Next.js want to convert image frame stream to a video on the frontend
I am using Django to stream image frames using return StreamingHttpResponse(run_live_demo(camera, model, conf_thresh), content_type="multipart/x-mixed-replace; boundary=frame",) When run_live_demo runs captures image from camera and yields the image. In my front-end where I am using next.js/react, I want to fetch the images but store the frames and play it is a video where it shows the current image by default but we can go back to older frames like a live video would work. I have tried lot of things, and am very confused on how to do this. To make it clear it is a live url and I cannot stop it and make it a mp4 and display that, because it suppose to be live. I tried to make it a video. import { useEffect } from "react"; function LiveStream() { useEffect(() => { const mediaSource = new MediaSource(); const videoPlayer = document.querySelector("#videoPlayer"); videoPlayer.src = URL.createObjectURL(mediaSource); mediaSource.addEventListener("sourceopen", () => { const sourceBuffer = mediaSource.addSourceBuffer( 'video/mp4; codecs="avc1.640028" ); const stream = new ReadableStream({ start(controller) { const xhr = new XMLHttpRequest(); xhr.open("GET", "http://127.0.0.1:8000/stream/0/default/0.7/0.7/0"); xhr.responseType = "text"; xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) { const contentType = xhr.getResponseHeader("Content-Type"); const boundary = contentType.match(/boundary=(.+)/)[1]; let buffer = ""; let boundaryIndex; xhr.responseType = … -
Single Form In Multiple Views
I have a form created in my forms.py file that I want to display on multiple pages of my app. The form: class Meta: model = Lead fields = ( 'first_name', 'last_name', 'address', 'city', 'state', 'zip', 'phone', 'email_address', 'date_delivery', ) widgets = { 'first_name': forms.TextInput(), 'last_name': forms.TextInput(), 'address': forms.TextInput(), 'city': forms.TextInput(), 'state': forms.TextInput(), 'zip': forms.NumberInput(), 'phone': forms.NumberInput(), 'email_address': forms.EmailInput(), 'date_delivery': forms.DateInput(), } The view: class CreateLeadView(CreateView): model = Lead form_class = LeadForm template_name = 'my_app/quote.html' Basically, I have several other views I want this form to appear on. What is the best way to accomplish this? -
How to check if a date is still less than 5 days in django query?
I am trying to check if the date an order was created is still less than 5 days, then i want to display a New Order Text. This is how i have tried doing this def vendor_orders(request): five_days = datetime.now() + timedelta(days=5) new_orders = CartOrder.objects.filter(payment_status="paid", date__lte=five_days).order_by("-id") This is returning all the orders in the database that the date is less than 5 days, which means all orders both old and new are being returned and this is not what i am expecting. If i manually create an order and set the date manually to some date in the future e.g July or August, it does not return that order. Please how can i go about this logic? all i want to do is display an order as new orders if the date which the order was created is not yet older than 5 days. Template Update i want to check if the order is a new order then i display a new badge Views.py @login_required def vendor_orders(request): five_days = datetime.now() - timedelta(days=5) # this is 5 days ago new_order = CartOrder.objects.filter(payment_status="paid", vendor=request.user.vendor, date__gte=five_days).order_by("-id") order = CartOrder.objects.filter(payment_status="paid", vendor=request.user.vendor).order_by("-id") context = { "order":order, "five_days":five_days, "new_order":new_order, } return render(request, "vendor/vendor-order.html", context) {% for … -
How do I install Haystack without CUDA?
I have integrated the Haystack vector search library into my Django application, and now I'm going through and attempting to turn the project into a Docker container. Everything is working okay, but I have noticed that when I build my Docker container, a lot of time is being spent on downloading and installing NVIDIA CUDA python packages. I am not deploying my containers on a platform with GPUs, and so I would like to install Haystack without installing the CUDA python packages. -
Profile matching query does not exist
Hi have getting error of Profile matching query does not exist and here is my codeenter image description here Hi have getting error of Profile matching query does not exist and here is my code[enter image description here] -
the second form on the Django page is not being processed
I'm writing a site on Django and I ran into a problem. I have a page on the site that has a form. Then I added functionality so that when a button is pressed on this page, a modal window will appear, which also has a form. But if I want to send data from the form that is in the modal window, I am sent data from the form that is on the page, even if there is no data there and the button was not pressed. How can I change this behavior? This is my views.py file: @login_required(login_url='signin') def update_password_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = UpdatePasswordForm(request.POST) if form.is_valid(): user_password = form.cleaned_data['password'] current_user.set_password(user_password) current_user.save() messages.success(request, "Your password has been updated successfully") else: print(form.errors) else: form = UpdatePasswordForm() img_base64, totp_secret = form_qrcode_service(current_user) return render(request, 'account/update-password.html', {'form': form, 'second_form': InputTokenForm(request.POST or None), 'qr_code': img_base64, 'totp_secret': totp_secret}) def input_code_form_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = InputTokenForm(request.POST) if form.is_valid(): print(form.cleaned_data['code']) else: print(form.errors) return redirect('update-password', url_username=url_username) update_password_view should be responsible for processing the form on the main page, and … -
Post matching query does not exist. When post exists in DB
I'm creating a simple blog with a Django backend using MongoDB to store blog posts and their metadata. Everything worked find when I was testing with a local mongodb instance, but when I switched to an atlas hosted database I started getting the following error. The current Post model is ` class Post(models.Model): _id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField( max_length=50, help_text='Post title. equivalent to obsidian file name') publish_date = models.DateField() last_edited = models.DateField(auto_now=True) content = models.TextField(blank=False) summary = models.TextField(blank=True) tags = models.CharField(max_length=20, blank=False) choices = [ ('published', 'published'), ('draft', 'draft'), ('private', 'private') ] status = models.CharField( choices=choices, default='published', max_length=20, blank=False,) class Meta: pass def get_absolute_url(self): return reverse('post', args=[self._id]) def __str__(self): return self.title To debug I overrode the get_object method as follows: ` def get_object(self, *args, **kwargs): kwargs = self.kwargs kw_id = kwargs.get('pk') all_results = Post.objects.filter() print(all_results.first()._id == str(kw_id)) result = Post.objects.get(_id=str(kw_id)) print("result:", result) return result assuming there is only one test post in the DB, all_results = Post.objects.filter() returns the post, but some of its element (e.g. all_results.first().content are None even though it is populated in the DB. the main problem is that when trying to filter or get based on the value of the _id field … -
How to pass form data to another Django class
Не могу решить проблему связанный с ошибкой Please tell me what is my mistake? from django.urls import path from .views import * app_name = 'data_array_do' urlpatterns = [ path('planFormView/', PlanFormView.as_view(), name='planFormView'), path('planListView/', PlanListView.as_view(), name='planListView'), ] from .forms import * from .models import * from django.shortcuts import render, redirect from django.views import View from django.urls import reverse from django.db.models import Q class PlanFormView(View): form_class = Filter template_name = 'planFormView.html' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): year = str(form.cleaned_data['year']) version = str(form.cleaned_data['version']) url = reverse('data_array_do:planListView', kwargs={"year": year, "version": version}) return redirect(url) return render(request, self.template_name, {'form': form}) class PlanListView(View): template_name = 'planListView.html' def get(self, request): year = request.GET.get('year', '') version = request.GET.get('version', '') if not year or not version: return render(request, self.template_name, {'error_message': 'Нет данных'}) my_data = FifthLevelCollection.objects.filter(Q(level_four_collection__third_level_collection__second_level_object__first_level_object__reporting_year__title=year) | Q(version=version)) return render(request, self.template_name, {'my_data': my_data}) from django import forms from .models import * # Форма для переменных фильтрации class Filter(forms.Form): year = forms.ModelChoiceField(label="Отчетный год", queryset=Year.objects.all()) version = forms.ModelChoiceField(label="Версия плана", queryset=Version.objects.all()) The user on the page fills out the form and sends it, then based on the form data, the data from the database is filtered and displayed on the page. … -
Caught in loop where timestamp value is overriding every other item's value in a list
New to Django and have been stuck on this issue for a couple days now. I am trying to display timestamp data for when an item was created in my database. I have two Django classes that look like this: class Game(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True, max_length=500) image = models.URLField(blank=True, null=True, max_length=500) genre = models.CharField(blank=True, null=True, max_length=200) platform = models.CharField(blank=True, null=True, max_length=200) developer = models.CharField(blank=True, null=True, max_length=200) publisher = models.CharField(blank=True, null=True, max_length=200) added_by = models.CharField(max_length=64) def __str__(self): return f"ID# { self.id }: { self.title }" class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now_add=True) The Game model stores data about a game, and when I click a button I will add a game into my playinglist model, which should automatically get the time it was inserted into that model. To add a game into my playinglist I am using this function: def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) game = Game.objects.get(id=game_id) if obj: obj.delete() game playing_game return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game playing_game return redirect("profile") And to display all the items in that respective user's Playlist I am using this … -
Django - Upload a file and populate field model with file name
I'm using Django and want to build an upload file page. When user upload a file, it stores it in a folder. I wan't to get the original file name to populate a field in my model (SourceFile.file). File is well uploaded, but I can't reach request.FILES properties, even with request.FILES.get('uploaded_to') or request.FILES['uploaded_to'] to fill in SourceFile.file with file name. How to achieve this ? My source is official documentation. models.py from django.db import models class SourceFile(models.Model): file = models.CharField() uploaded_to = models.FileField(upload_to ='/uploads/') serializers.py from rest_framework import serializers from .models import * class SourceFileSerializer(serializers.ModelSerializer): class Meta: model = SourceFile fields = ['file', 'uploaded_to'] views.py class SourceFileViewSet(viewsets.ModelViewSet): serializer_class = SourceFileSerializer def list(self, request): return Response("GET API") def upload_file(request): if request.method == "POST": form = SourceFile(request.POST, request.FILES) # Nothing happened file_uploaded = request.FILES.get('uploaded_to') file_name = file_uploaded.name request.POST['file'] = file_name # if form.is_valid(): form.save() return HttpResponseRedirect("/success/url/") else: form = SourceFile() return render(request, "upload.html", {"form": form}) -
How to access relation 'belongs to' from template?
I was wondering if there's a way to access the relation 'Belongs To' using Jinja in a Django project. What I mean is: I have this model representing Student: class Student(models.Model): name = models.CharField(max_length=200, verbose_name="Name:") ... and I have this model representing Enrollment, this class has a foreign key related to student: class Enrollment(models.Model): enroll_number = models.CharField(max_length=10, verbose_name='Number:') ... student= models.ForeignKey(Student, on_delete=models.CASCADE, related_name='enroll_student', verbose_name='Student:') ... If a pass sothing like enroll = Enrollment.objects.get(id=1) and pass to template {{"enroll": enroll}} I know that I can, using Jinja, access student with: {{enroll.student}} But, if I only the student (student = Student.objects.get(id=1)) and pass {{"student": student}} to template, how can access the enrollments with Jinja: something like: {{student.enroll}} (This doesn't work) Even If there's know way, what would be the best practice to resolve this in Django? Laravel, for instance allows us to define a function on the model that we can access in the template. Does anybody could help? -
Django: How to filter django objects based on month?
I am trying to get/count how many orders that were made in a month, i have written some logic to do this, but the issue is this: It does not count how many total orders were made in a month, it spreads different orders on the same month. To be more explicit, look at the reponse below: This is how to the queryset looks now <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> This is how to the expected queryset should look <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 2}]> The 'month':4 is 'month':April and 'month':6 is 'month':June This is the code i have written to do this, but does not work models.py class CartOrder(models.Model): vendor = models.ManyToManyField(Vendor) ... date = models.DateTimeField(auto_now_add=False) views.py import calendar from django.db.models.functions import ExtractMonth orders = CartOrder.objects.annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id')).values('month','count') print(orders) terminal <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> -
How to more concisely make Google authorization on Django Rest Framework?
Began to study DRF. Now I have reached the topic "Google authorization". I started looking for materials on this topic, but there are a lot of them and some of them are already outdated. I'm looking for a more up-to-date description of how it's done now. It would be ideal to find a description with an example "for dummies", where everything is described in great detail. A little about the test project: for the user, a model based on AbstractUser is used now local registration and authorization is used using "Simple JWT" Request: djoser topics do not touch yet I read the topic "Authentication" on the official website of the DRF, I mainly considered "drf-social-oauth2", but I didn’t really understand -
Execute python on Django Queryset
Is there a way to execute python code on a Django Queryset? I am storing data in the db as bytes and I want to convert them to "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB". Is there any way I can convert the them before passing to the view? def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['user'] = ( DataVolume.objects.values('user') .order_by('user') .annotate( imgs=Sum('imgs'), size=SumConvertBytes('user_bytes'), ), ) -
Can I create multiple objects in django admin?
The questions is really simple. I have ItemPicture model which is class ItemPicture(models.Model): name = models.CharField(null=True, max_length=255) picture = models.ImageField(upload_to='shop/static/shop/images/') def __str__(self): return str(f"{self.name} id={self.pk}") def get_url(self): return self.picture.url How can I create, for example, 5 objects at once with django admin? I should be able to upload 5 photos and give them 5 names. django-bulk-admin and django-mass-edit didn't work for me -
sending value form views.py to html using jsonresponse
he=llo, i want to get a value from my view to html using jsonreponse, the problem is that my code work fine in views.py and i can print the data , but when i call the data in ajax it doesn't work it just give 0 as result ( because i declare round_surf = 0 at the beginning ) this the views.py code : def resultat (request): round_surf = 0 info = parametre.objects.filter(pk=1).values()[0] SEUIL = info['PAR_SEUIL'] COLOR = info['PAR_COLOR'] NBR_PAQ = info['PAR_NBRE_PAQUET'] SUR = info['PAR_SUR'] if request.method=="POST": if request.POST.get('captured_image'): captured_image = request.POST.get('captured_image') imgstr = re.search('base64,(.*)', captured_image).group(1) imgstr = base64.b64decode(imgstr) tempimg = io.BytesIO(imgstr) im = Image.open(tempimg) image = ImageOps.grayscale(im) # Appliquer un seuil pour convertir les pixels en valeurs binaires threshold = 100 # Choisir un seuil approprié image = image.point(lambda x: 0 if x < threshold else 1, '1') # Récupérer la longueur et la largeur de l'image width, height = image.size # Calculer le nombre total de pixels total_pixels = width * height image = image.convert('RGB') # Initialiser le compteur de pixels noirs black_pixels = 0 # Parcourir chaque pixel de l'image for x in range(width): for y in range(height): # test if the pixel is white if image.getpixel((x, … -
Custom functionality for editing popup text (like wikipedia link popups) in Summernote
I am trying to implement a feature into admin panel using Summernote to be able to add and edit popup information for parts of text like in Wikipedia. Wikipedia example I have found information on how to add custom buttons to summernote text editor, however implementation of functionality for described feature is too specific to be even referenced anywhere. I expect on a button press to appear a window (like for link insertion that is already implemented in Summernote) with fields for icon appearing in text and image/text appearing in popup. Populating those fields will add code to the editor, that is interpreted as an icon in text, hovering over which will show a popup window with before mentioned content. Maybe someone knows what documentation can help with implementation of such feature. -
ImportError: cannot import name 'displayadmin' from 'organizationsapp.models'
I'm new to python and django. admin.py in organizationsapp: from django.contrib import admin from .models import displa class displayadmin(admin.ModelAdmin): list_display = ['des','pic'] admin.site.register(displa,displayadmin) models.py in organizationsapp: from django.db import models class displa(models.Model): des = models.TextField(max_length=100,blank=True,null=True) pic = models.ImageField(upload_to='display/', blank=True) class Meta: verbose_name = 'ad' verbose_name_plural = 'ad' It says: ImportError: cannot import name 'displayadmin' from 'organizationsapp.models' import name 'displayadmin' from 'organizationsapp.models'? import name 'displayadmin' from 'organizationsapp.models'? -
How to pass link to file in Django views
I am very new to Django and trying display an image on an html page by passing the path to the src from the view. I have this in the 'task1.html' file <figure><img src={% static '{{ main_figure }}' %}></figure> <p>{{ description }}</p> and this in the 'views.py' file def task1(request): return render( request, "App/Tasks/task1.html", { 'main_figure' : "assets/placeholder_img.png", 'description' : "Placeholder image and text" } ) But the image does not show. If I remove the 'main_figure' : "assets/placeholder_img.png", line and change <figure><img src={% static '{{ main_figure }}' %}></figure> to <figure><img src={% static 'assets/placeholder_img.png' %}></figure> the image displays, so the issue seems to be with the views function. I have tried passing different parts of the src from the view, e.g. <img src={{ main_figure }}> with 'main_figure' : "{% static 'assets/placeholder_img.png' %}", and <img src={% static 'assets/{{ main_figure }}.png' %}> with 'main_figure' : "placeholder_img", but it always shows the little image not found icon. Any help would be greatly appreciated, thanks very much. -
How to modify or cancel the soft_time_limit for a running Celery task in Django?
Using Celery with Django, I encountered an issue while using the soft_time_limit on a task. Is there any way to stop or increase the soft_time_limit when a task is being executed? For example, after some lines of code are executed, can I increase the soft_time_limit for that particular task or cancel it altogether so that I can run the task without restrictions? I have tried modifying the soft_time_limit using update_state and signal, but it doesn't seem to work. I also tried using os.kill(os.getpid(), signal.SIGUSR1) to kill the current process, but it still raises the SoftTimeLimitExceeded exception. Any help or suggestions on how to achieve this would be greatly appreciated. Thank you. import signal from celery.exceptions import SoftTimeLimitExceeded @app.task(bind=True, soft_time_limit=10) app.task() def func(self) try: ..... ..... ..... some code app.current_task.request.timelimit = [None, None] or os.kill(os.getpid(), signal.SIGUSR1) .... some code except SoftTimeLimitExceeded: .... -
Django Modals To Admin Site
I want to Show Language of Book In Each BookInstance Table? How Do i do it. Please Guide me Everything Else is Working Fine. Here is the code :- Modals.py Modals.py Admin.py Admin.py Note :- i am new to django -
Django | Error in migration from sqlite3 to MySQL
I want to change my database from sqlite3 to mysql, but every time I do so, I encounter an error whenever I try to retrieve data from the database: Even when I try to log in to admin panel, I get the same error! (createsuperuser works fine): Here are my models: class Website(models.Model): name = models.CharField(max_length=500) URL = models.CharField(max_length=500) Logo = models.CharField(max_length=1000,null=True,blank=True) class Data(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE , null=True, blank=True) Target_website= models.CharField(max_length=500,null=True,blank=True) URL = models.CharField(max_length=500,null=True,blank=True) Title = models.CharField(max_length=1000, unique=True) Description = models.TextField(null=True,blank=True) Keywords = models.TextField( null=True,blank=True) Text = models.TextField( null=True,blank=True) Links = models.TextField( null=True,blank=True) Images = models.TextField( null=True,blank=True) Videos = models.TextField( null=True,blank=True) Claps = models.IntegerField(default=0) TimeStamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Title def change_claps(self, x): self.Claps += x self.save() class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=14) password = models.CharField(max_length=20) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) #auto_now = True if you want to add a field like "updated_on" favourite_posts = models.ManyToManyField(Data, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Claps(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_likes') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_likes') class Fav(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_favs') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_favs') Here are my serializers: from rest_framework import … -
What is your way of setting up a new project with Django? Using Docker, Github?
i was just wondering what's your way of starting a new project with django? Do you develop the project and then setup docker or you do it all at the beginning? I know there is no right or wrong but only what's right for us. But i've been struggling finding my way to optimise creating an app using all those services such as docker or railway.app Thanks for your feedbacks -
How to recreate my table in database in Django
i created a table in sqlite3 database by migrate command and then deleted it manually from database how can i recreate the table in database I tryed maigrate command again but its show No migrations to apply. pls someone tell how do i recreate the table in automatic way(by commands) -
Additional arguments to get_queryset in view
I’m looking at code which has: get_queryset(self, *args, **kwargs): return (super().get_queryset(*args, **kargs).order_by(self.name)) What is the purpose of the args and kwargs here and why not do this instead: get_queryset(self): return MyModel.objects.order_by(self.name))```