Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamically form
I have the following My models: # База товаров / Base products class Products(models.Model): name = models.CharField(max_length=150, verbose_name='Название') def __str__(self): return self.name class Meta: ordering = ('name',) verbose_name = 'База товаров' verbose_name_plural = 'База товаров' # Закупили / Base purchases class Purchases_item(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE, verbose_name='Товар') quantity = models.PositiveIntegerField(default=0, verbose_name='Кол-во') untils = models.ForeignKey(Untils, on_delete=models.CASCADE, verbose_name='Ед. измерения') price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Цена себестоимости') total_price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Общая сумма') def __str__(self): return str(self.product) def save(self, *args, **kwargs): super(Purchases_item, self).save(*args, **kwargs) val = self.price * self.quantity if self.total_price != val: self.total_price = self.price * self.quantity self.save() class Meta: ordering = ('product', 'price', 'total_price') verbose_name = 'Покупка по позициям' verbose_name_plural = 'Покупки по позициям' # Список который мы закупили записываем на склад / Purchases List # По факту это склад списком class Purchases(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, verbose_name='Дата') # переделать на defaul и отключить auto now add company = models.CharField(max_length=150, verbose_name='Компания', null=True, blank=True, default=None) product = models.ManyToManyField(Purchases_item, verbose_name='Товар(ы)') total_price = models.DecimalField(max_digits=150, decimal_places=0, verbose_name='Общая сумма', default=0) def __str__(self): return self.company def save(self, *args, **kwargs): super(Purchases, self).save(*args, **kwargs) if self.total_price != sum(product.total_price for product in self.product.all()): self.total_price = sum(product.total_price for product in self.product.all()) self.save() class Meta: ordering = ('date', … -
CommandError: No fixture named 'fixture' found
I'm trying to use loaddata to load some fixtures into a Django 2.2.10 project. According to the documentation, the command should look like this: python manage.py loaddata fixture app/fixtures/*.json However, when I run this command I get the following error: CommandError: No fixture named 'fixture' found. I figured the word "fixture" was being interpreted as a path to the fixture, so I removed it and it worked: python manage.py loaddata fixture app/fixtures/*.json I still find it weird though that the documentation tells me to do something that doesn't work. Am I missing something? I'm worried that I might have something wrong in my setup that is going to come back to haunt me in the future. -
ImportError: cannot import name 'Celery' from 'celery'
ImportError: cannot import name 'Celery' from 'celery' The code is running fine in my local machine. when i run this code on azure server then create this issue. here below is my project file structure in below screenshot. __init__.py file: from __future__ import absolute_import from core.celery import app as celery_app __all__ = ['celery_app'] celery.py file: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) task.py file: from celery import shared_task from time import sleep from azure.datalake.store import core, lib, multithread from django.core.mail import send_mail token = lib.auth() adls_client = core.AzureDLFileSystem(token, store_name='bnlweda04d3232gsdfs') @shared_task def sleepy(duration): sleep(duration) return None @shared_task def send_email_task(subject,message,from_email,recipient_email,fail_silently): sleep(30) send_mail( subject,message,from_email,recipient_email,fail_silently ) return 'Mail sent success' I'm using celery version: 4.4.0 and python version: 3.8.10 -
How to convert drop down choice column to text field in Django forms
I am trying to make patient registration form in my project where Django automatically gives drop down choice list for the foreign key columns. How do I make that column into a text field as I need user to enter patient id instead of choosing from the long drop down list. I tried something but it didn't work for me. Please help if possible. from django import forms from HMSapp.models import Registration from django.core.exceptions import ValidationError class RegistrationForm(forms.ModelForm): Pid=forms.CharField() class Meta: model=Registration fields='__all__' def clean_Pid(self): patient_id=self.cleaned_data['Pid'] try: Pid=Registration.objects.get(id=patient_id) return Pid except: raise ValidationError('Patient id does not exist') -
Can't display foreign key related object in Django DetailView
I've got a booking class which is related to Customer and Barber models. I can display all bookings using the detail view, however, can't figure out how to display a booking/bookings that a specific barber has. Basically, I want to get a booking or multiple bookings of a barber based on the ID given to the url. Here is my model: customer_id = models.ForeignKey(User, on_delete = models.CASCADE,) barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE) timeslot = models.DateTimeField('appointment') def __str__(self): return f"{self.customer_id} {self.barber_id} {self.timeslot}" def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) My view: class GetBarberBooking(DetailView): model = Booking template_name = "barber_booking.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['barber'] = Booking.objects.filter( id=self.kwargs.get('<str:pk')) return context My url path: path('barber-booking/<str:pk>/', views.GetBarberBooking.as_view(), name='barber-booking'), -
Django migrations with Docker compose and volumes
I am using Django with Docker compose and all the persistent files are saved in a volume. My issue is that I am also saving my database in the volume: how does this influence migrations? I've added an new schema and there seems no way to reflect this change in the DB. When I apply the migrations on my local environment, it works, the migrations are correctly applied and I can see the new db schema, but this is because I've created a local folder app/static, which reflects the volume name of the docker-compose. Now, since the db is in that folder, it works, as the migrations are applied to the db. When I deploy my application, the db inside of the app/static remains the same old db, with the same old entries and the same old schemas. How can I apply the migrations so that the db inside of the volume app/static reflects the new changes, without losing the old entries? As a practical example I have added a new model Action, which is not existent on the server. So the DB has all the schemas but Action. Locally, I run makemigrations and migrate, producing the migration files (which … -
Why is Chart.js not rendering? Error: Uncaught ReferenceError: Chart is not defined
I am trying to implement chart.js in my django project, and I am starting with the example graph used on the chart.js website, before then amending the data and tweaking it. However, I can't yet get the default chart to pull through, and keep getting the error message: Uncaught ReferenceError: Chart is not defined This makes me think that the library isn't installed correctly, but I have used a few different CDNs and can't get it to work, any help would be much appreciated! html template: {% extends 'base.html' %} {% load static %} {% block content %} <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Weight', 'Run Distance', 'Run Time', 'Date'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: … -
Django - ckeditor disappears after adding youtube plugin
I am trying to build a blog webpage and also i want to share my youtube tutorials in my page so i need this plugin so much. when i add this plugin to my project, ckeditor disappears. Can somebody help me to fix this? models.py class Makale(models.Model): kategori = models.ForeignKey(Kategori, on_delete=models.SET_NULL, null=True) # altKategori = models.ManyToManyField(AltKategori) baslik = models.CharField(max_length=50) kisaIcerik = models.TextField(max_length=300) tamIcerik = RichTextField(external_plugin_resources = [( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )]) settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom' : [ ['Bold', 'CodeSnippet', 'Font', 'FontSize', 'TextColor', 'BGColor', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'Italic', 'Underline', 'Link', 'Unlink', 'RemoveFormat', 'Source', 'Image', 'Youtube'] ], 'extraPlugins' : ','.join(['codesnippet', 'youtube']), 'width': 'auto', }, } when i remove youtube plugin from ckeditor_configs on settings.py it works perfect. The problem is on Youtube plugin. I don't know how to fix that. -
Test doesn't remove generated files using factory_boy in django
I'm using factory_boy to generate arbitrary data to run tests. but after each test it doesn't delete files automatically. Is there anything I should add? Any suggestion is highly appreciated Model for test class TrackFactory(factory.django.DjangoModelFactory): class Meta: model = "tracks.Track" id = factory.Faker("uuid4") filename = "Track 01 - track" created_by = factory.SubFactory(UserFactory) file = factory.django.FileField(filename="test.mp3") track_length = 145 @classmethod def _create(cls, model_class, *args, **kwargs): instance = cls.build(*args, **kwargs) instance.save() return instance Test class TestViewDeleteTrack(AuthorizedApiTestCase): def setUp(self): self.url = reverse(list-track) self.user_data = UserFactory() self.data = TrackFactory(created_by=self.user_data) self.client.force_authenticate(user=self.user_data) def test_list_tracks(self): self.get_and_assert_equal_status_code(status.HTTP_200_OK) def test_delete_track_valid_pk(self): self.delete_and_assert_equal_status_code( "delete-track", self.data.pk, status.HTTP_204_NO_CONTENT, ) custom methods for testing used above def get_and_assert_equal_status_code(self, status_code): response = self.client.get(self.url) self.assertEqual(response.status_code, status_code) return response def delete_and_assert_equal_status_code(self, url_name, pk, status_code): url = reverse(url_name, kwargs={"pk": pk}) response = self.client.delete(url) self.assertEqual(response.status_code, status_code) -
Heroku project deploy issue
I have 2 projects made on django. I tried to deploy both of them to Heroku, but every time i'm trying - i'm getting an error like this: -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed (It's the situation when i choose a heroku/python as project buildpack) Another one occurs when i try to deploy project without selected buildpack: -----> Building on the Heroku-22 stack -----> Determining which buildpack to use for this app ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed In both variants i use "Deploy method: GitHub repo". You can check out one of my projects here: https://github.com/Fakemrx/Train-Travel-Project All information about my issue i found yet is that i need to have some "special" files in project folder (not in subfolders!) that will mean for Heroku tha it's python project. I already tried to use third-party builpacks but got no results. *I'm trying to deploy my project not from command prompt, but from Deploy menu on Heroku (https://dashboard.heroku.com/apps/some-custom-app-name/deploy/github). -
How can i display the category for a particular product in the product list page? - Django
I am trying to display a product list page with products attributes along with category which is a MPTT field. I want to display the category assigned to that particular product in the product list page. How can i achieve this? Models class Category(MPTTModel): """ Inventory Category table implimented with MPTT """ name = models.CharField( max_length=100, null=False, unique=False, blank=False, verbose_name=_("category name"), help_text=_("format: required, max-100"), ) slug = AutoSlugField(populate_from='name') cat_img = models.ImageField(upload_to='images/categories/') parent = TreeForeignKey( "self", on_delete=models.PROTECT, related_name="children", null=True, blank=True, unique=False, verbose_name=_("parent of category"), help_text=_("format: not required"), ) class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = _("product category") verbose_name_plural = _("product categories") def __str__(self): return self.name class Product(models.Model): """ Product details table """ product_id = models.UUIDField(default=uuid.uuid4, editable=False) sku = models.CharField(max_length=255, blank=True, null=True) name = models.CharField( max_length=255, unique=False, null=False, blank=False, verbose_name=_("product name"), help_text=_("format: required, max-255"), ) slug = AutoSlugField(populate_from='name') price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) description = models.TextField( unique=False, null=True, blank=True, verbose_name=_("product description"), help_text=_("format: required"), ) prd_img = models.ImageField(upload_to='images/products/', null=True, blank=True) category = TreeManyToManyField(Category, null=True, blank=True) modifier_group = models.ManyToManyField(ModifierGroup, null=True, blank=True) def __str__(self): return self.name Views @login_required(login_url='/login/') def productList(request): products = Product.objects.all() context = {'products':products} template = 'product/product/products.html' return render(request,template,context) Template <td class="text-end pe-0" data-order="37"> <span class="fw-bold ms-3">{{product.category.name}}</span> </td> Template Result … -
Alter primart key in django model, must start with 1001
I am working on a project, in which we have requirement that we have to start our primary key by 1001. The framework used is Django here. So, we have to create a migration having id as alter field. But I don't know how to alter sequence of primary key. From some articles, I use auto_increment but it gives error of undefined. Thanks -
Multiple files in a single field model of Django
I am making a site in which user uploads it's pdf and back of the site we generate audio file for each page and now we want to save it on the database(mysql). Now the problem starts we have model in django and model have the fields which are for a single input. for example class Info(models.Model): phone_img = models.ImageField(upload_to='pics') Name = models.CharField(max_length=70) RAM = models.IntegerField(default= None) ROM = models.IntegerField(default= None) Cost = models.IntegerField(default= None) Link = models.URLField(max_length=250) Now if we use models.FileField(upload_to='files') then it will upload files to a files folder but I have several files then how to upload that files, because we can't create fields for that and if we create fields for that then it's not fix that the user uploaded pdf have the same no. of pages as we have fields. -
ModuleNotFoundError: No module named 'myApp' deploying django on planethoster with n0c
I'm struggling with n0c and wsgi (with passenger), it works in developpment but not while deploying The error message /opt/passenger/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Traceback (most recent call last): File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/opt/alt/python310/lib64/python3.10/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 719, in _load File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/ambnvnpa/kriill/passenger_wsgi.py", line 1, in <module> import kriill.src.kriill.wsgi File "/home/ambnvnpa/kriill/kriill/src/kriill/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/opt/alt/python310/lib64/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'home' passenger_wsgi.py I added the multiple dots at the difference of the tutorial (https://kb.planethoster.com/guide/astuces-techniques/installer-django-sur-world/) because of my folder architecture. import kriill.src.kriill.wsgi … -
How to use Django backend templet variable in JS
I want to use backend data in the js file. return render(request, "class.html", {'all_classes':all_class}) I want to use it in the JS 'all_classes'. I know for the HTML - <select name="subject_class" type="text" class="form-control" required > {% for class in all_classes %} <option value="{{ class.class_name }}">{{ class.class_name }}</option> {% endfor %} </select> but please give me an idea for the javascript. -
Get all tags, if post has tags then mark as selected and remaining as not selected in django
While editing post to update i'm getting only selected tags for that post, how can i get all tags and with selected option for particular post. For example i have 4 tags and 1 tag is assigned to a post, when i edit that post to update i should get assigned tag as selected and remaining 3 tags as not selected. so that i can assign remaining tags to post if i wanted. And is there any way that i can create extra tags while updating post. For reference i've uploaded image below in that i got only selected tag i want to show remaining non selected tags also. models.py class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Card(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=150, unique=True) desc = models.TextField() img = models.ImageField(upload_to='uploads/') date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(blank=True, null=True) published = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title views.py @login_required(login_url = '/login/') def edit(request, pk): edit_list = Card.objects.get(id=pk) edit_tags = Card.objects.filter(id=pk) tag = Tag.objects.all() context = { 'edit_list': edit_list, 'edit_tags': edit_tags, 'tag':tag, } return render(request, 'edit-post.html', context) HTML <div class="container my-5"> <form action="{% url 'post_update' edit_list.pk %}" method="post" enctype="multipart/form-data">{% csrf_token %} <div … -
Signifianct Reduction in Performance after Installing Whitenoise
I installed and configured whitenoise to compress my static files, after which I ran collectstatic, and it appears everything ran successfully. It says 598 files have been post-processed. However, my CSS files are still the same size, and page load times have increased in production but are the same in development. Lighthouse scores have decreased from 95 to 87 after repeated tests. I must have configured something wrong, but I'm not sure what. Settings that probably aren't relevant have been removed for brevity. Settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "True") == "True" if DEBUG is True: ALLOWED_HOSTS = [] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } # HTTPS Settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS Settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', … -
Pass argument to view with reverse url django
url = reverse("school_management:student-list", args=(student.id,)) Hi, i am using django reverse url, here i am getting output as '/school/student/.2979' I am not getting why . is included here in output? -
how to display quarter column and its sub column after each quater based on month selection using xlsxwriter and django?
I want to display Quarter column (QTD) and its sub columns(BP,RE or RE(3+9) or RE(6+6) or RE(9+3),and Actuals) after each quarter based on month selection in date picker.Currently, QTD is displayed after each month.Now, I want to display it after every quarter instead of every month. For example, If we select April, May ,June ,I want to show QTD column and its sub columns after June month and if we select months April and May ,I want to show QTD column and its sub columns after May month. Also if we select April, May ,June,July, August months, I want to show first quarter QTD column and its sub columns after June month and second quarter column after August month. code: dat = report.objects.filter(date__gte=start_date, date__lte=end_date).values('date').distinct() date_list = [] for date_value in dat: month_year = str(date_value["date"].month) + "-" + str(date_value["date"].year) date_list.append(month_year) row_num = 2 header = ['Plant Locality', 'Plant Type', 'Market', 'Product', 'UOM', 'Previous Year FTM', 'Previous Year YTM'] for col_num in range(len(header)): worksheet.write(row_num, col_num, header[col_num], header_format) month_year_cell_start = 7 for date_year in date_list: worksheet.merge_range(0, month_year_cell_start, 0, month_year_cell_start + 8, date_year, merge_format) worksheet.merge_range(1, month_year_cell_start, 1, month_year_cell_start + 2, 'FTM', header_format) worksheet.merge_range(1, month_year_cell_start + 3, 1, month_year_cell_start + 5, 'YTD', header_format) if date_year.split('-')[0] … -
Django rest framework 'NoneType' object is not callable
I am new to django and drf. I've created a viewset for getting list of elements, adding new, updating and deleting, but I have some troubles when I try to create a viewset for getting detailed info about 1 element. Here is my urls.py urlpatterns = [ path('tasks', views.TaskViewset.as_view( { 'get':'list', 'post':'add', 'put':'update', 'delete':'delete' } )), path('tasks/<int:pk>', views.TaskDetailViewset.as_view( { 'get':'detail' } )) ] and here is my TaskDetailViewset from views.py class TaskDetailViewset(viewsets.ViewSet): def detail(self, request, pk, *args, **kwargs): #data = request.query_params task = models.Task.objects.get(id=pk) serializer = serializers.TaskSerializer(task) if serializer.is_valid(): return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) When I try to send request to http://127.0.0.1:8000/api/v1/tasks/1 I get 'NoneType' object is not callable and I don't understand where is the problem here -
VSCode showing choosing debugger instead of debug configuration when I try to create a launch.json file of django
I am currently following a tutorial for django and when I try and create a launch.json file through VSCode's debug, it only shows select debugger and prompts me to use Chrome or Edge as options for the debugger. I want to select django at the debug configuration menu, and I am wondering how I would get that to open/ -
django-unicorn resets mounted data after button click
I've built several small apps over the last weeks and stumbled every time over the same problem I couldn't figure out a solution with the docs or a google search. TL;DR I can't keep the results of a queryset initialized inside __init__ or mount() after clicking a button and changing any other value unrelated to the queryset. Is there a way to save/cache the results? Simple Example Initial position components/simple_unicorn.py from django_unicorn.components import UnicornView from any.app.models import MyObject class SimpleUnicornView(UnicornView): # Initialize my sample objects empty as I don't have any filter data, yet objects: MyObject = MyObject.objects.none() # A single filter value - In reality thos are multiple buttons filter_y: str = "" # any variable unrelated to the queryset show_button_x: bool = False def mount(self): self.load_data() def load_data(self): self.objects = MyObject.objects.filter(any_value=self.filter_y) # the execution of this query takes very long def updated_filter_y(self, value): # after changing varables related to the qs it is obvious the reload the data self.load_data() # this is where the problem pops up def toggle_button_x(self): # I'm only changing a variable not connected to the loaded data self.show_button_x = not self.show_button_x # Now I must execute the query again, otherwise self.objects is empty self.load_data() … -
Python regEx won't identify whitespace
I'm trying to replace some keywords in a document using Django Template, but unfortunately i'm dealing with normal user data, so my function receives a dictionary with keys that i'm pretty sure will contain a space. To deal with this risk i'm trying to do this workaround using regEx: from typing import Dict, List from django.template import Context, Template import docx from docxcompose.composer import Composer import re import django from django.conf import settings settings.configure(TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['.'], 'APP_DIRS': False }, ]) django.setup() def combine_documents(documents: List[dict], template_data: Dict): document_paths = [] placeholder = docx.Document() composer = Composer(placeholder) for i in range(len(documents)): document_paths.append(docx.Document(documents[i]["path"])) composer.append(document_paths[i]) composer.doc.add_page_break() context = Context(template_data, autoescape=False) document = composer.doc pattern = re.compile(r"\{{[\s\S]*\}}", re.IGNORECASE) for paragraph in document.paragraphs: for word in paragraph.text.split(): matches = pattern.finditer(word) # print(word) for match in matches: print(match.group()) if " " in match.group() and match.group() == word: print(match.group()) print("it's here") paragraph.text = paragraph.text.replace(" ", "_") template = Template(paragraph.text) print(template.render(context)) return "Ok!" combine_documents(documents = [{ "title": "Titulo", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }, { "title": "Outro título", "path": "libs/plugins/signature/signature_providers/documents/Contrato de Prestação de Serviço - Exemplo.docx" }], template_data={"Empresa": "FakeCompany", "Endereço Completo": "Rua 1", "Cidade": "São Paulo", "Estado": "São Paulo", "CEP": "12345678", "CNPJ": "317637667-0001", … -
Getting forbidden error when fetching endpoint when logged into account
Using React for the frontend and Django for the backend. I have a page in my website that displays all the user settings. When they load the page it fetches the data from the backend and fills out the form, when they submit the updated form it posts it to the backend. When I go to post this data when I'm logged into an account it gives me a forbidden error but when I'm logged out and post the form it goes through. Why would it be doing this? react post const onSubmit = async (e) => { e.preventDefault() const res = await fetch('/api/account/updatesettings', { method: "POST", headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ "test": "test" }) }) const data = await res.json() } api endpoint: class UpdateSettings(APIView): serializer_class = AccountSettingsSerializer def post(self, request, format=None): print("test") serializer = self.serializer_class(data=request.data) print(serializer.data) if serializer.is_valid(): pass -
Transcribe Streams of Audio Data in Real-Time with Python
I developed a web app using Django as a backend and a Frontend library. I have used django-channels, for WebSocket and I am able to record the audio stream from the front end and send it to Django over WebSocket and then Django sends it to the group. So I'm able to do live audio calls (let's say) but I have to transcribe the audio at the backend. (the main goal of the project) Things I'm looking forward to use this package to achieve transcription. I send base64 encoded opus codecs string from the front end to Django every second. It sends recorded audio every 1 second. My doubts - If we play Audio streams independently, we are only able to play the first string. We are not able to play 2nd, 3rd .... independently (padding issues or maybe more I'm not aware of), so I have used MediaSource at front end to buffer the streams and play. The question is can we convert this 2nd 3rd audio stream into text using the above-mentioned package? or I will have to do something else. (I'm looking for ideas here on how will this work) Also, the above-mentioned package uses a wav …