Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do i keep getting an TemplateSyntaxError on line 4
i keep getting error on line 4 onle when i add the last h1 block with its block content and endblock here is the error TemplateSyntaxError at /mySecondPage Invalid block tag on line 4: 'endblock'. Did you forget to register or load this tag? {% extends "index.html" %} {% block title %}My Second Page{% endblock %} {% block content %} <h1>Hello, world! Django First Page</h1> {% endblock %} i dont know how to ifx it can someone please help -
Prometheus- total time of function
I am using Prometheus and Grafana on my Django project. I decorated with Prometheus a few functions that eventually did API calls. PROMETHEUS_TIME = Histogram( name="method_latency_seconds", documentation='total time', labelnames=('component', 'container', 'tenant', 'app', 'metric_name')) I want to get the maximum; I tried to do a graph on Grafana but had no success: method_latency_seconds{app='my_app', metric='my_metric'} this promQL show me NO DATA while method_latency_seconds_sum{app='my_app', metric='my_metric'} or method_latency_seconds_count{app='my_app', metric='my_metric'} showing data but not what I'm searching for. Is someone can help me to get the maximum? Is there another way to get data that is not Grafana? -
How to set date_hierarchy to an annotation field
I have a Model and its Manager. I created an annotated field date (which returns not null date from start or set date). class TimerManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .annotate( date=models.ExpressionWrapper( functions.Coalesce( models.F("start__date"), models.F("actual_date"), ), output_field=models.DateField( _("date"), ), ), ) ) class Timer(models.Model): start = models.DateTimeField(_("start"), auto_now_add=True) end = models.DateTimeField(_("end"), null=True, blank=True) set_date = models.DateField(_("set date"), null=True, blank=True) objects = TimerManager() I want to use this annotated field in date_hierarchy of Timer's ModelAdmin but this error occurres: <class 'timers.admin.TimerAdmin'>: (admin.E127) The value of 'date_hierarchy' refers to 'date', which does not refer to a Field. list_display can show annotated fields by reffering ModelAdmin's methods which explicitly return these properties: @admin.register(Timer) class TimerAdmin(admin.ModelAdmin): list_display = ["pk", "start", "end", "date"] exclude = [] def date(self, obj): return obj.date We use this method in date_hierarchy: date_hierarchy = "date". But the issue still happens. -
how should i fix bunch of no reverse math errors in django
i read everything about no reverse match error but nothings changed i did everything and my task is "In the view related to the list of posts that are filtered, how to filter the posts based on the time that is considered for publication. This filter should be such that it takes the time considered for the published_date section and compares it with the current time, if it is past the current time, it should be displayed and otherwise not." and "In the view related to displaying a single post, insert a function that every time the view related to each post is called, one unit will be added to the counted_view attribute of that post. urls.py from django.urls import path, include from blog.views import * app_name = 'blog' urlpatterns = [ path('', blog_view, name='index'), path('single/<int:pid>', blog_single, name='single') ] views.py from django.shortcuts import render, get_object_or_404 from blog.models import blog_Post from django.utils import timezone # Create your views here. def blog_view(request, pid): posts = blog_Post.objects.filter(published_date__lte=timezone.now(), status=1, pk=pid) context = {'posts': posts} return render(request, "blog/blog-home.html",context) def blog_single(request, pid): blog_object = get_object_or_404(blog_Post, pk=pid) blog_object.counted_views += 1 blog_object.save() return render(request, "blog/blog-single.html", {'posts':blog_object})] base.html <li><a href="{% url 'blog:index' %}">Blog Home</a></li <li><a href="{% url 'blog:single' pid=post.id … -
Sort Django QuerySet by the combination of string fields from a M2M relationship
Suppose I have two models connected with a many-to-many relationship. class Bar(models.Model): name = models.CharField() class Foo(models.Model): name = models.CharField() bars = models.ManyToManyField(Bars, through='FooBars') class FooBars(models.Model): date = models.DateTimeField(auto_now_add=true) foo = models.ForeignKey(Foo, on_delete=models.CASCADE) bar = models.ForeignKey(Bar, on_delete=models.CASCADE) In a QuerySet of Foo, I want the related Bars ordered by date so that I can then sort Foo models on the combined string of the date-ordered names in bars. For example: FooBars: foo bar date a alpha 01-01-2020 a beta 01-03-2020 a gamma 01-02-2020 b alpha 01-01-2020 b beta 01-02-2020 b gamma 01-03-2020 QuerySet sorted on the combined string of Foo.bars: Foo bars b alpha, beta, gamma a alpha, gamma, beta I've tried annotations with some combinations of Subquery, F() yet can't get the annotation to evaluate and appear on the Queryset. -
How to change Hx-Get value dynamically?
I have a button which opens a dialog located in some_template.html: <button @click="open = !open" id="btn_id" hx-get="/some_url/" hx-trigger="click" hx-swap="outerHTML"> </button> Then I have another_template which includes some_template In another_template I am handling a button click: <script> document.addEventListener('alpine:init', () => { Alpine.data('dialog', () => ({ handleButtonClick(id) { console.log(id); // prints the expected id correctly const button = document.getElementById('btn_id'); const url = `/some_url/${id}`; button.setAttribute('hx-get', url); console.log(button.attributes); // prints the updated `hx-get` with the id included button.click(); } })); }); </script> The dialog is opening correctly which means the button.click() is working properly. The main problem is that the hx-get is not being updated, i.e., there is no id associated with it, and it still processes the request without it, using what was initially defined in the button: hx-get="/some_url/". -
Pycharm/npm always gets stuck when i try to install Tailwind dependencies
When I run python manage.py tailwind install to install the Django-Tailwind dependencies the IDE seems to get stuck. This is what the console shows: (venv) jonas@Air-von-Jonas prizewize % python manage.py tailwind install (⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂) ⠙ idealTree:static_src: sill idealTree buildDeps and nothing ever happens. When I try to run the tailwind dev server I get (venv) jonas@Air-von-Jonas prizewize % python manage.py tailwind start > theme@3.6.0 start > npm run dev > theme@3.6.0 dev > cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w node:events:505 throw er; // Unhandled 'error' event ^ Error: spawn tailwindcss ENOENT at ChildProcess._handle.onexit (node:internal/child_process:283:19) at onErrorNT (node:internal/child_process:476:16) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) Emitted 'error' event on ChildProcess instance at: at ChildProcess._handle.onexit (node:internal/child_process:289:12) at onErrorNT (node:internal/child_process:476:16) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { errno: -2, code: 'ENOENT', syscall: 'spawn tailwindcss', path: 'tailwindcss', spawnargs: [ '--postcss', '-i', './src/styles.css', '-o', '../static/css/dist/styles.css', '-w' ] } Node.js v18.0.0 (venv) jonas@Air-von-Jonas prizewize % so it seems it didnt install the dependencies first of all. I also tried it via npm i tailwindcss which gets stuck as well or at least doesn't execute any --- so maybe it's a npm issue? -
override all-auth user model
Im using django all-auth for my website, and I have created a custom subscription system. I want to create a method has_active_subscription in the User model : def has_active_subscription(self) -> bool: subscriptions = self.subscriptions.filter(status__in=["active", "trial"]) return subscriptions.exists() My idea was to create a custom user model like this : class CustomUser(AllAuthUser): But the issue is that I can't find the default all-auth user model AllAuthUser (https://github.com/pennersr/django-allauth/blob/main/allauth/account/models.py). Also I would like the table's name in the database to be the same as the default one : auth_user. Can someone please help me? :) -
404 Error from XML calling Django function
My django code takes a set of questions with 4 answers, 1 is correct, from a model. If the user clicks on the correct one, it should use javascript and XML to call a Django function which verifies whether it was the correct button, and give back a new colour and message and so on. <button class="button questionbutton" id="3" style="vertical-align:middle; margin:35px 70px;" onclick="window.location.reload(true)"><span>{{ question.question3 }}</span></button> <button class="button questionbutton" id="4" style="vertical-align:middle; margin:35px 70px;" onclick="window.location.reload(true)"><span>{{ question.question4 }}</span></button> </div> </div> <script> const buttons = document.querySelectorAll('.questionbutton'); buttons.forEach(button => { button.addEventListener('click', function (event) { const clicked = event.target; const selected = clicked.getAttribute('data'); const check = clicked.getAttribute('correct') === 'true'; const questionId = clicked.getAttribute('question'); var xhr = new XMLHttpRequest(); xhr.open('POST', '/processLB/', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.onload = function () { if (xhr.status === 200) { var response = JSON.parse(xhr.responseText); if (response.result === 'correct') { if (check) {5 clicked.style.backgroundColor = 'green'; } else { clicked.style.backgroundColor = 'red'; } } else { clicked.style.backgroundColor = 'gray'; } } else { } }; xhr.send('selected=' + encodeURIComponent(selected) + '&question_id=' + encodeURIComponent(questionId)); }); }); </script> Is my HTML and javascript function. The problem is I am getting a 404 error stating that processLB() can't be found when clicking the button. I've run some … -
No such file or directory Django AWS S3 Boto3 Upload
I tried everything, its not working, and i think i know why but i dont know how to fix it, im using this tutorial to upload in chunks to bypass the Cloudflare upload limitation of 100mb file def create_post(request): # s3_client=boto3.client('s3') s3 = boto3.client('s3', region_name=settings.AWS_S3_REGION_NAME, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) categories_1 = Category.objects.all() if request.method == 'POST': file = request.FILES['file'].read() file_name_s3 = request.POST['filename'] fileName= request.POST['filename'].replace(' ', '') fileName_STR = re.sub("[^A-Z]", "", fileName,0,re.IGNORECASE) + '.mp4' existingPath = request.POST['existingPath'] end = request.POST['end'] image = request.FILES.get('image', False) imageName = request.FILES.get('imagename', False) if image != False: image = request.FILES['image'].read() imageName= request.POST['imagename'].replace(' ', '') else: pass title = request.POST['title'] tags = request.POST['tags'] categories = parse_ids(request.POST['categories']) description = request.POST['description'] nextSlice = request.POST['nextSlice'] if file=="" or fileName_STR=="" or existingPath=="" or end=="" or nextSlice=="": res = JsonResponse({'data':'Invalid Request'}) return res else: if existingPath == 'null': path = 'media/uploads/video_files/' + fileName if image != False: with open(path, 'wb+') as destination: destination.write(file) imagePath = 'media/thumbnail/' + imageName else: pass if image: with open(imagePath, 'wb+') as destination: destination.write(image) else: pass object_name = Path.joinpath(BASE_DIR, file_name_s3) handles the upload................... path = 'media/uploads/video_files/' + fileName_STR with open(object_name, 'rb') as destination: s3_client.upload_file(object_name ,bucket,fileName_STR) ............................................ FileFolder = Post() FileFolder.video = 'uploads/video_files/'+fileName_STR FileFolder.existingPath = fileName_STR FileFolder.eof = end FileFolder.title = … -
Authenticate user login to form and makes only 10 forms in django
The problem is that, I want that the authenticated users login into the form. And They can make only 10 forms after the 10 forms message is displayed. I have tried but the message is not displayed. VIEWS.PY def create_form(request): # Creator must be authenticated if not request. user.is_authenticated: return HttpResponseRedirect(reverse("login")) def create_form(request): # Assuming the user is already authenticated logged_in_user = request.user # Set the maximum allowed forms per creator (in this case, 10) max_forms_per_creator = 10 # Get the count of forms created by the logged-in user form_count = Form.objects.filter(creator=logged_in_user).count() # Check if the user has reached the form creation limit if form_count >= max_forms_per_creator: return render(request, "error/error.html" ) This program works but it does not show the error message nor show the error HTML page -
missing an object auth when overided the function get_app_list() from- django.contrib.admin.AdminSite
I was trying to rearrange the order of models and apps displayed in django admin panel, for that i over rided the function get__app__list() function which is defined in django package mentioned below. from django.contrib.admin import AdminSite class CustomAdminSite(AdminSite): def get_app_list(self, request, app_label=None): """ Return a sorted list of all the installed apps that have been registered in this site. """ app_dict = self._build_app_dict(request, app_label) ordering_dict = {'AUTH':1,USERS': 1,'COURSE': 2,} # Sort the apps based on ordering_dict app_list =sorted(app_dict.values(),key=lambdax:ordering_dict.get(x["name"].upper(),float('inf'))) return app_list admin.site = CustomAdminSite() i tries this in admin.py of all my apps. when i used the same code in inside django library ( by rewriting inside the package ) , i worked perfectily. but if i inherited the AsminSite and overrided the function get__app__list() : the object of auth app is not in request, so the GROUP table is missing in admin panel, how the object is not there when i inherit and override it ?? i need an solution for this i want to know how the object is not there when i inherit and override it what can i do inted ? -
Pycharm (Django project) debugger gives an error when starting
I am working on a django project and tried to run the debugger but it gives the error below which seems to be something with pydevd-pycharm. I have not seen it somewhere online or have been able to just reinstall this helper. /Users/newadmin/PycharmProjects/ThreadIt/venv/bin/python /Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 64748 --file /Users/newadmin/PycharmProjects/ThreadIt/manage.py runserver 8000 Connected to pydev debugger (build 232.8660.197) Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 2199, in <module> main() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 2181, in main globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1451, in run self.prepare_to_run() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1339, in prepare_to_run self.patch_threads() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1355, in patch_threads patch_thread_modules() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 886, in patch_thread_modules patch_thread_module(t) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 849, in patch_thread_module _original_start_new_thread = thread_module._original_start_new_thread = thread_module.start_new_thread AttributeError: module 'thread' has no attribute 'start_new_thread' Process finished with exit code 1 In the console it looks like it is out of date and is using python2's thread in stead of threading. But I don't really want to touch the source code and have not found the problem with other people when searching online. -
Invalid HTTP_HOST header: '<calculated when request is sent>'. The domain name provided is not valid according to RFC 1034/1035
I'm trying to make a function that will return a file and change the StatusType to the one I need. There is an error that I don't understand, please, who has encountered such an error, help me please! error: Invalid HTTP_HOST header: '<calculated when request is sent>'. The domain name provided is not valid according to RFC 1034/1035 class CheckUpdate(generics.UpdateAPIView): """ Update the check instance, returns a file and marks the check as printed. """ serializer_class = CheckUpdateSerializer queryset = Check.objects.all() def get_object(self): """ Get the check object based on the provided 'pk'. """ pk = self.kwargs.get("pk") validate_check_by_id(pk) return get_object_or_404(Check, pk=pk) def perform_update(self, serializer): """ Update the status of the check instance to 'StatusType.PRINTED'. """ instance = serializer.save(status=StatusType.PRINTED) def get_pdf_file_response(self, instance): """ Get the PDF file response of the check instance. """ instance = self.get_object() file_path = instance.pdf_file.path with open(file_path, "rb") as f: response = FileResponse(f.read(), content_type="text/pdf") response["Content-Disposition"] = f"attachment; filename={slugify(instance.name)}" return response def update(self, request, *args, **kwargs): """ Update the check instance and return the PDF file. """ instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return self.get_pdf_file_response(instance) Im try to allow all hosts and cors. But nothink helps. -
django.db.utils.IntegrityError: Stuck with this error for days
I'm trying to make migrations in my model but stuck with this error: django.db.utils.IntegrityError: The row in table 'posts_article' with primary key '1' has an invalid foreign key: posts_article.author_id contains a value '1' that does not have a corresponding value in posts_author.id. Here's my models: from django.db import models from django.contrib.auth import get_user_model from django.utils.timezone import now User = get_user_model() # Create your models here. class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) profile_picture = models.ImageField() def __str__(self): return self.user.username class Topic(models.Model): title = models.CharField(max_length=20, blank=True, null=True) subtitle = models.CharField(max_length=20, blank=True, null=True) slug = models.SlugField(blank=True, null=True) thumbnail = models.ImageField(blank=True, null=True) def __str__(self): return self.title class Article(models.Model): title = models.CharField(max_length=100, blank=True, null=True) overview = models.TextField(null=True) content = models.TextField(null=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, blank=True, null=True) thumbnail = models.ImageField(blank=True, null=True) categories = models.ManyToManyField(Topic, blank=True, null=True) #featured = models.BooleanField(None, default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: ordering = ['-updated', '-created'] I've searched the internet and tried a few solutions but it's the same. I am totally out of solutions. I am new to Django so please don't be too hard on me :) -
Aggregating Two Django Models with No Direct Relationship - Translating Pandas to Django ORM
I am currently aggregating two QuerySets by merging them based off of a key "pl_id" and grouping by two additional attributes, "zip_code" and "num_itms" with Pandas, but in production this is far too slow due to the large size of the datasets. I have tried multiple approaches with SubQueries but nothing is working, as the subqueries return multiple values. Zip codes is an ArrayField and is being unnested with the Postgres function, this seems to be complicating my goal. Is there a way to achieve this Pandas aggregation with Django ORM? result = ( pd.DataFrame.from_records( self.offer_query.annotate( partner_id=F("l__p_id"), zip_code=Func( F("l__ra__zip_codes_array"), function="unnest", ), ).values("zip_code", "p_id", "pl_id") ) .merge( pd.DataFrame.from_records( self.prices_query.values( "pl_id", "num_items", "price", ) ), on="pl_id", ) .groupby(["zip_code", "num_items"]) .agg( count=("p_id", "count"), min=("price", "min"), max=("price", "max"), ) .reset_index() ) I have already tried a subquery for each aggregation. -
OperationalError at / [Errno 111] Connection refused with Django and Celery
As the title suggest, I'm having OperationalError at / [Errno 111] Connection refused I'm using Django with Celery and Redis as Broker. The issue happens only when I'm using gunicorn with the command gunicorn --bind 0.0.0.0:8080 Lab.wsgi. Everything work with the Django internal server I've already tried this solution but it didn't work for me From the stack error it seems it's trying to use amqp when I'm using Redis with Celery. In Django on my settings.py I have REDIS_HOST = "172.20.1.2" REDIS_PORT = "6379" CELERY_BROKER_URL = "redis://" + REDIS_HOST + ":" + REDIS_PORT + "/0" CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRASPORT_PROTOCOL = {"visibility_timeout":3600} CELERY_ACCEPT_CONTET = ["application/json"] CELERY_TASK_SERIALIZER = "json" So I can't udnerstand Error stack Internal Server Error: /celery-progress/01f2ab7b-5b25-4bda-901f-50cedb4d4a69/ Traceback (most recent call last): File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery_progress/views.py", line 10, in get_progress return HttpResponse(json.dumps(progress.get_info()), content_type='application/json') File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery_progress/backend.py", line 64, in get_info task_meta = self.result._get_task_meta() File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery/result.py", line 438, in _get_task_meta return self._maybe_set_cache(self.backend.get_task_meta(self.id)) File "/home/lab/dashboardlab/.venv/lib/python3.10/site-packages/celery/backends/base.py", line 608, in get_task_meta meta = self._get_task_meta_for(task_id) AttributeError: 'DisabledBackend' object … -
I can't display the image in django admin UI
enter image description here my UI interface keep showing this url img source, meanwhile what i want is the image preview. maybe i need some additional format? what is the html tag needed to show as image in browser view? this is my source code now for **admin.py** from django.contrib import admin from .models import Categorie, Product from django.utils.html import format_html @admin.register(Categorie) class CategoryAdmin(admin.ModelAdmin): list_display = ('category_name',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_filter = ('category',) list_display = ('product_name', 'category','thumbnail_preview','description') def save_model(self, request, obj, form, change): obj.category_id = obj.category.id obj.save() def thumbnail_preview(self, obj): preview_html = '' for i in range(1, 6): product_photo_field = f'Photo_{i}' if hasattr(obj, product_photo_field): product_photo = getattr(obj, product_photo_field) if product_photo: preview_html += format_html('<img src="{}" style="max-height:100px; max-width:100px;" />', product_photo.url) print(preview_html) if not preview_html: return '(No Images)' return preview_html thumbnail_preview.allow_tags = True thumbnail_preview.short_description = 'Product Photos' and this is the models.py file from django.db import models **# Model for Category** class Categorie(models.Model): category_name = models.CharField(max_length=100, unique=True,default='') def __str__(self): return self.category_name **# Model for Product** class Product(models.Model): category = models.ForeignKey(Categorie, on_delete=models.CASCADE) product_name = models.CharField(max_length=200) Photo_1 = models.ImageField(upload_to='product_photos/') Photo_2 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_3 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_4 = models.ImageField(upload_to='product_photos/', blank=True, null=True) Photo_5 = models.ImageField(upload_to='product_photos/', blank=True, null=True) description = models.TextField() def __str__(self): return … -
When passing list into payload in Python requests module it is giving recursive error
I am trying to run tests like following: @patch("requests.post") # Mock the database connection def test_high_level_summary_success(self, mock_post): data = { "geo_level": "\"Global\"", "combinations": [{"product":"AAA","geo_value":"PL"}] } # Make a POST request to the endpoint url = reverse("myurl:deepdive-high-level-summary") response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) However when I pass this list as combinations value ([{"product":"AAA","geo_value":"PL"}]) it is somehow giving me the following error: E RecursionError: maximum recursion depth exceeded while calling a Python object !!! Recursion detected (same locals & position) Why this might be the issue? Here is the function I want to test: @action(detail=False, methods=["post"]) def high_level_summary(self, request): try: # athenalogger.test_func1() json_payload = { "geo_level": ast.literal_eval(request.data.get("geo_level")), "combinations": ast.literal_eval(request.data.get("combinations")), } if request.data.get("months"): json_payload.update({"months": ast.literal_eval(request.data.get("months"))}) url = "{}{}".format(settings.MYURL, "api/deep_dive/high_level_summary") response = requests.post(url.replace("'", ""), json=json_payload) if response.status_code in [200, 201]: return Response({"result": response.json(), "status": "success"}, status=status.HTTP_200_OK) elif response.status_code in [400]: return Response({"result": {}, "status": "success"}, status=status.HTTP_200_OK) else: self.logger.error("error occured : {}".format(response.text)) return Response( {"error_message": "error response from sbd", "status": response.status_code}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) except Exception as e: self.logger.error("\n Deepdive got an error: {}\n".format(traceback.format_exc())) return Response( {"error_message": "something went wrong", "status": "error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, ) -
Uploading audio file using react and DRF - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 14
I have an application in which user either records an audio, or selects one from memory. Then, sends the file via this axios: const submit = () => { let params = new FormData(); params.append("exercise_id", exercise_id); params.append("answer", answer, "file.mp3"); setLoading(true); axios .post("submit_answer/", params, { headers: { "content-type": "multipart/form-data", }, }) .then((res) => { console.log(res.data); if (res.data.status === 1) { toaster(res.data.msg); } else { toaster(res.data.msg); } setLoading(false); }) .catch((err) => { setLoading(false); handleError(err); }); }; In the back-end I am using DRF, this is my serializer: class SubmitAnswerSerializer(serializers.Serializer): exercise_id = serializers.IntegerField() As you see, I am not using a serializer for the answer field, as it could be an audio, a video, an image, or even an integer number. Instead, I get it in my api: @api_view(["POST"]) def submit_answer(request): serializer = serializers.SubmitAnswerSerializer(data=request.data) if not serializer.is_valid(): return Response( {"status": 0, "msg": "submit_answer serializer invalid"}, status=status.HTTP_200_OK, ) exercise_id = serializer.validated_data.get("exercise_id") answer = request.data.get("answer") print(answer) ##########rest of the code but when i try to upload the media file using this api, I get this error: Internal Server Error: /api/submit_answer/ Traceback (most recent call last): File "~lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "~lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "~lib/python3.10/site-packages/django/template/response.py", … -
Redacting files of Django project after deplo
I have deployed my Django project on my local server. Ubuntu 22.04.2 LTS Django 4.2.4 nginx 1.18.0 gunicorn 20.1.0 I use mysql-connector-python to connect with MySQL database. mysql-connector-python 8.0.33 I need to redact file with my DB queries and setting.py. I try to redact with nano and restart nginx but it doesn't work. How can I redact this files on prod? -
SystemCheckError when running makemigrations for Wagtail models
I'm trying to create migrations for my Wagtail models, but I encountered a SystemCheckError with some fields.E304 and fields.E305 errors. I'm using Django with Wagtail to build my web application, and the specific error message is as follows: SystemCheckError: System check identified some issues: ERRORS: app.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'app.HomePage.page_ptr' clashes with reverse accessor for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. app.HomePage.page_ptr: (fields.E305) Reverse query name for 'app.HomePage.page_ptr' clashes with reverse query name for 'home.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'app.HomePage.page_ptr' or 'home.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E304) Reverse accessor 'Page.homepage' for 'home.HomePage.page_ptr' clashes with reverse accessor for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. home.HomePage.page_ptr: (fields.E305) Reverse query name for 'home.HomePage.page_ptr' clashes with reverse query name for 'app.HomePage.page_ptr'. HINT: Add or change a related_name argument to the definition for 'home.HomePage.page_ptr' or 'app.HomePage.page_ptr'. I have a Django project with two Wagtail models: HomePage in the app app and HomePage in the home app. Both models inherit from the Wagtail Page model. I added some custom fields to each model, and the HomePage model has an additional field called … -
Build a backend in django from scratch without using ORM [closed]
I'm required to build a simple api but I'm not to use any ORM while using relational db. I have to do authentication as well. I am stuck even after some research and don't know how to aproach this. I have been doin django with ORM, and maybe DB first aproach is the go to here but still is there a way to create tables directly from django without getting models, involved? -
How to run a query with group by over a 'select_related' field in django ORM
I'm developing a reservations system and on my database I have Products, different Items of the products and orders related to specific items. The intention is to get the list of available items of an specific product that are not already reserved between two dates. These are my models: class Product(models.Model): # Aqui se almacenaran los modelos name = models.CharField(max_length=50, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) stock = models.IntegerField() def __str__(self): return self.name class Item(models.Model): # Aqui se almacenaran las matriculas especificas disponibles name = models.CharField(max_length=50, unique=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return f"{self.product.name} - {self.name}" class Order(models.Model): status = models.CharField(max_length=50) item = models.ForeignKey(Item, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() notes = models.TextField(max_length=2000, null=True, blank=True) assigned_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.item.name} - {self.start_date} - {self.end_date}" After some tests in SQL in the database, I've reached the following query that gives me the expected result: SELECT calendarapp_item.id, calendarapp_item.product_id as product, count(orders.id) AS active_orders FROM calendarapp_item LEFT JOIN (SELECT * FROM calendarapp_order WHERE start_date<='{}' AND end_date>='{}' AND status='completed') AS orders ON orders.item_id=calendarapp_item.id GROUP BY calendarapp_item.id HAVING active_orders=0 and product={} I would like to translate this query to Django ORM in order … -
Return field value when referencing model instance
If I have the following Model: class VATPercentage(models.Model): percentage = models.IntegerField(default=21) Is there anyway I can make it so that when you reference an instance of it, you actually get the value stored in the percentage field? For example, I want to be able to do: Service.vat_percentage instead of Service.vat_percentage.percentage Similar to how _ str _ would work if you called str() on the model, but I need an integer.. I tried to look for something similar like defining an _ int _ function but i dont think thats a thing..