Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What exactly are path converters in Django
I am new to Django and I can't seem to wrap my head around what exactly a path converter does. As I understand, for each app we require a URLConf file, which will map our URL's to our view functions. In this way, when a URL is requested by a user, the corresponding view function will be executed. According to the documentation: Path converters¶ The following path converters are available by default: str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn’t included in the expression. int - Matches zero or any positive integer. Returns an int. slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example, building-your-1st-django-site. uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID instance. path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL path rather than a segment of a URL path as with str. So, does this mean, that the path converter acts … -
Migrations reflect not only database but some business logic. Migrations blow up
Let us suppose that we had a model (example is from the documentation https://docs.djangoproject.com/en/4.1/ref/models/fields/#filefield): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) Migrations will be something like: ('upload', models.FileField(upload_to=vocabulary_phrases.models.user_directory_path)), But now you decide to change to a class: class UploadTo: def __init__(self, folder, filename_suffix=""): self.folder = folder self.filename_suffix = filename_suffix def _get_filename(self, instance, filename): _, file_extension = os.path.splitext(filename) result = str(instance.a_uuid) if self.filename_suffix: result += "-{}".format(self.filename_suffix) result += file_extension return result def save_path(self, instance, filename): tmp_filename = self._get_filename(instance, filename) result = "{}/{}".format(self.folder.value, tmp_filename) return result class MyModel(models.Model): upload = UploadTo(folder=UPLOAD_TO.VOCABULARY_FILE_FOLDER, filename_suffix="trololo").save_path When you try to makemigrations, this code will blow. It will complain like 0002_migration contains user_directory_path, it is absent. This change in the code not mechanical. I can't imagine that it can be done just by refactor / rename in IDE. Then I can't imagine what the new migration should look like. This means that I will not be able to modify migrations file easily. I will have to deploy another project next to this one and another database. Delete all migrations, makemigrations, copy created migration and substitute all occurrances of user_directory_path with what is in my clipboard. Complicated, … -
Django channels always returns AnonymousUser when using Django Authentication
i am learning about django channels. I am following the channels docs: https://channels.readthedocs.io/en/stable/topics/authentication.html When i try to access the user using self.scope["user"] in consumers.py, i am always getting AnonymousUser object I can see the logged in user in templates. I used the admin user for testing. Note: I am new here. Please let me know if i need to provide some more info. Thank you consumers.py from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer import time import asyncio from pprint import pprint from asgiref.sync import async_to_sync class MyWebsocketConsumer(WebsocketConsumer): def connect(self): print("connected") pprint(self.scope) pprint(self.scope['user'].username) self.room_name = self.scope['url_route']['kwargs']['room'] group_add = async_to_sync(self.channel_layer.group_add) group_add(self.room_name, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): pprint(self.scope['user'].is_authenticated) print('msg received', text_data) group_send = async_to_sync(self.channel_layer.group_send) message = { 'type': 'chat.message', 'msg': text_data } group_send(self.room_name, message) # self.send(text_data) def chat_message(self, event): msg = event['msg'] self.send(msg) def disconnect(self, close_code): print("disconnected", close_code) routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/wsc/<str:room>', consumers.MyWebsocketConsumer.as_asgi()), # path('ws/awsc/', consumers.MyAsyncWebsocketConsumer.as_asgi()) ] asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter import app.routing from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_consumer.settings') wsgi_app = get_asgi_application() application = ProtocolTypeRouter({ 'http': wsgi_app, 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( app.routing.websocket_urlpatterns)) ) }) settings.py from pathlib import Path # Build paths inside … -
How do i set network file path in django response?
I have MinIO and Django apps in the docker network. When I want to send a file to a client I need to use this form: response = HttpResponse() response['X-Accel-Redirect'] = file_path if download: response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name) else: response['Content-Disposition'] = 'filename="{}"'.format(file_name) Is it possible to replace file_path with network file path? -
Problem with searchbar in Django and HTML
I have created a searchbar in Django and HTML, however, this gives me problems. If I enter "Apple iPhone 13 Pro" in the searchbar it will not find any results, because the URL is not encode. The URL is: Apple+iPhone+13+Pro, but it should be: Apple+iPhone%C2%A0%. How can I solve? -
Deploy Zappa Django on AWS Lambda with Custom GoDaddy Domain
I created a Django Rest APIS using the Django Rest framework. I used Zappa to deploy my DJANGO API and got a working URL https://autocreatedname.execute-api.region.amazonaws.com/dev Zappa created an s3 bucket and a lambda function After that, I created a Cloudfront distribution with my custom domain name and got d3b779m4oksdfs.cloudfront.net --> this works in isolation on the browser. I created AWS certification and added CNAME and Value to my Godaddy DNS and it's active and validated. Now, I am not sure if I need Amazon route 53/API Gateway to connect these. -
Triggering a trackor without change in value in django?
I have a use case, where I am tracking the changes of a field. My issue is I want to trigger it even if there is no change in that field. E.g., status field changes from Null -> IM -> OK -> OK I have put my logging code based on the change of status field and due to some constraint I had to do the status change from IM to OK. I now want to trigger the tracker for the OK - > OK (the very first occurrence only) This is my post_save signal: @receiver(post_save, sender="iot_app.VehicleNumber") def vehiclenumber_post_save(sender, instance, created, *args, **kwargs): if changed == 'status': if created: continue try: log_ota_events.delay( vehicle_id=instance.id, event=getattr(instance, '_event_type'), source=getattr(instance, '_event_source', None), source_id=getattr(instance, '_event_source_id', None), metadata={ 'immobilize_status': instance.status, 'immobilizer_action': instance.immobilizer_action, 'immobilisation_valid_upto': str(instance.immobilisation_valid_upto), }, comment=getattr(instance, '_event_comment', None), ) except Exception as e: logger.warning(f"Couldn't log the event {e}", exc_info=True)``` -
Django Rest Framework, request POST, update if exists, create if not exists from mass data of POST request
I am building an API for users info data I want to make that when the POST request, execute function "create", "update" if from POST request user exists: update (full_name, function, department, logon, system, lic_type ) if from POST request user doesn't exist: create (user, full_name, function, department, logon, system, lic_type ) models.py from django.db import models class Users(models.Model): user = models.CharField(max_length=50,blank=True, null=True) full_name = models.CharField(max_length=200, blank=True, null=True) function = models.CharField(max_length=300,blank=True, null=True) department = models.CharField(max_length=300,blank=True, null=True) logon = models.DateTimeField(blank=True, null=True) system = models.CharField(max_length=300,blank=True, null=True) lic_type = models.CharField(max_length=300,blank=True, null=True) serizlizers.py from rest_framework import serializers from .models import Users class UsersSerializer(serializers.ModelSerializer): logon = serializers.DateTimeField(input_formats=settings.DATE_INPUT_FORMATS) class Meta: model = Users # fields = '__all__' fields = ['user', 'full_name', 'function', 'department', 'logon', 'system', 'lic_type'] views.py from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from .models import Users from .serializers import UsersSerializer from rest_framework.decorators import api_view, authentication_classes from rest_framework.response import Response from django.views.decorators.csrf import csrf_exempt from rest_framework.authentication import BasicAuthentication @csrf_exempt @api_view(['GET', 'POST']) @authentication_classes([BasicAuthentication]) def users_list(request): if request.method == 'GET': users = Users.objects.all() user = request.GET.get('user', None) if user is not None: users = users.filter(user__icontains=user) users_serializer = UsersSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) elif request.method == 'POST': users_data = JSONParser().parse(request) users_serializer = UsersSerializer(data=users_data, … -
Django creation of model with foreign keys
I have a model with two foreign keys. When I use ModelForm to create instances those two foreign keys appear as drop down menus. But I want them to be automatically created from string values. How could i do this? -
Django-tenants "Unable to create the django_migrations table"
An issue occurred where our production database was not getting migrated due to an error during migration. This error involved the usage of the package django-tenants, which is a fork of the django-tenant-schemas package. The error: Traceback (most recent call last): File "/backend/manage.py", line 21, in <module> main() File "/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 89, in handle executor.run_migrations(tenants=tenants) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations Starting new HTTPS connection (1): o1380729.ingest.sentry.io:443 run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants)) File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations migration_recorder.ensure_schema() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 70, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (relation "django_migrations" already exists ) What could cause this error? -
jquery each function for auto generated html elements with same class
I have an ajax script that should act on some automatically generated html elements from django, to do this I was told to use the each() function in jquery to act on each element with the same class name. The script sort of works without the each() function, but it only changes the first element rather than each individual element. With the each function in place, no values are changed so I'm not sure what to do. javascript $(document).ready(function() { $('.fix-button').each(function() { $(this).on('submit', function(e){ e.preventDefault(); issue_id = $(this) $.ajax({ type: 'POST', url: '{% url "fix_issue" %}', data: { issueid: issue_id.val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("fixed_bool").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }); }); }); my views.py if its necessary def FixView(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('issueid')) issue = get_object_or_404(Issue, id=id) if issue.fixed == False: print(issue) issue.fixed = True result = str(issue.fixed) issue.save() else: issue.fixed = False result = str(issue.fixed) issue.save() return JsonResponse({'result': result, }) -
No module named... in Django proyect
I have a pretty standart Django project and i can't find a way to import /middleware/utils/compare.py from /middleware/utils/request.py This is the proyect tree: |--middleware/ | |--utils/ | | |--compare.py | | |--request.py | |--__init__.py | |--asgi.py | |--settings.py | |--urls.py | |--views.py | |--wsgi.py |--manage.py Where __init__.py, asgi.py, settings.py, urls.py, wsgi.py have no major modifications. (__init__.py is empty) # middleware/views.py from .utils.request import requests # This line works fine # middleware/utils/request.py from compare import compare # ModuleNotFoundError: No module named 'compare' from .compare import compare # Attempted relative import beyond top-level package pylint(relative-beyond-top-level) # ^^^ This line absolutly breaks my code, but it runs from utils.compare import compare # ModuleNotFoundError: No module named 'utils' from .utils.compare import compare # ModuleNotFoundError: No module named 'middleware.utils.utils' Note: compare.py has a function named compare, i also tried renaming it but had the same problems. This might be obvious, but i run the proyect with python manage.py runserver -
Create Array from Model Data in Django Template in <script>
I am trying to use JQuery date picker and I want to make use of the beforeShowDay method in order to block out dates in the date picker. I have been able to get the widget to work and if I define an array, the beforeShowDay method works flawlessly. But my issue is passing the data from my Django model to create an array. Is there a way to create an array within the element in the template in order to achieve this? template <script> # works as intended when the array is defined manually var array = [ "2022-10-01" ] # this is where I am having trouble creating an array from the model data var array = [ {% for x in listing_reservations %} {{x.dates}} {% endfor %} ] $(function() { $( "#id_start_date" ).datepicker( { beforeShowDay: function(date){ var string = jQuery.datepicker.formatDate('yy-mm-dd', date); return [ array.indexOf(string) == -1 ]; } } ); }); </script> -
'EntryPoints' object has no attribute 'get' - Digital ocean
I have made a deplyoment to Digital ocean, on staging (Heroku server) the app is working well, but Digital ocean it's failing with the error below, what could be the issue : AttributeError at /admin/ 'EntryPoints' object has no attribute 'get' Request Method: GET Request URL: https://xxxx/admin/ Django Version: 3.1 Exception Type: AttributeError Exception Value: 'EntryPoints' object has no attribute 'get' Exception Location: /usr/local/lib/python3.7/site-packages/markdown/util.py, line 85, in <module> Python Executable: /usr/local/bin/python Python Version: 3.7.5 Python Path: ['/opt/app', '/usr/local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf'] Server time: Sun, 02 Oct 2022 21:41:00 +0000 -
Staging syntax error while creating Django model instance
from customer.models import Customer; cust = Customer.objects.create_user(first_name=\"'$first_name'\", last_name='\"'$last_name'\", uuid='\"'$uuid'\"); Getting these errors for the last name: Staging: -c: unexpected EOF while looking for matching `"' Staging: -c: syntax error: unexpected end of file I have tried last_name=$'$last_name' but that does not work and I need it to still be a string if given an empty string. This is in a bash script. -
How to sort a queryset based on a foreign key field?
This is a contest system project. I have these models and I know the contest_id and problem_id. I'm trying to return a queryset that contains users who have solved a problem. A user who solves a problem is the one whose submission's score is equal to score of the problem he tried to solve. At the end I need to sort these users based on the time they have submitted their successful submission. class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants')so class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey("accounts.User", on_delete=models.CASCADE) score = models.PositiveIntegerField(default=100) class Submission(models.Model): submitted_time = models.DateTimeField() participant = models.ForeignKey(User, related_name="submissions", on_delete=models.CASCADE) problem = models.ForeignKey(Problem, related_name="submissions", on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) I tried following code but I don't get wrong answer. How can I sort my QuerySet? def list_users_solved_problem(contest_id, problem_id): problem_score = Problem.objects.get(id=problem_id).score successful_submissions_ids = Submission.objects.filter(Q(score=problem_score) & Q(problem_id=problem_id)) \ .values_list('participant__id', flat=True) return Contest.objects.get(id=contest_id).participants.order_by('submissions__submitted_time') -
Setting environment variables using activate.bat
I am using PyCharm on Windows and want to set the environment variables for Django website. I am setting the values in the project's venv: activate.bat @echo off set "VIRTUAL_ENV=D:\Git\QV-PublicWebsite\venv" set DJANGO_SECRET_KEY='random' ... activate.ps1 ... $VIRTUAL_ENV = $BASE_DIR $env:VIRTUAL_ENV = $VIRTUAL_ENV $env:DJANGO_SECRET_KEY='random' ... When I load the project in PyCharm, I can see that the venv is active. But when I start debugging the project, I am not able to read the values: This is the settings that I have for debugging the project: -
How to solve Django ValueError: Field 'id' expected a number
I am making filters in Django to select data from a database. Now it looks like: view.py: def get_current_user(request): current_user = request.user return current_user def is_valid_query_param(param): return param != '' and param is not None def bootstrapFilterView(request): user = get_current_user(request) qs = CompletedWork.objects.filter(checked_by_head=True) struct_divisions = StructuralDivisions.objects.filter( Q(head=user) | Q(management_unit__head=user) | Q(curator=user) | Q(management_unit__curator=user) ) workers = CustomUser.objects.filter( Q(struct_division__head=user) | Q(struct_division__management_unit__head=user) | Q(struct_division__curator=user) | Q(struct_division__management_unit__curator=user) ) workstype = WorksType.objects.filter( Q(available_to__head=user) | Q(available_to__curator=user) ).distinct() work_notes_contains_query = request.GET.get('work_notes_contains') work_scope_min = request.GET.get('work_scope_min') work_scope_max = request.GET.get('work_scope_max') period_min = request.GET.get('period_min') period_max = request.GET.get('period_max') struct_division = request.GET.get('struct_division') worker = request.GET.get('worker') work_done = request.GET.get('work_done') if is_valid_query_param(work_notes_contains_query): qs = qs.filter(work_notes__icontains=work_notes_contains_query) if is_valid_query_param(work_scope_min): qs = qs.filter(work_scope__gte=work_scope_min) if is_valid_query_param(work_scope_max): qs = qs.filter(work_scope__lte=work_scope_max) if is_valid_query_param(period_min): qs = qs.filter(period__date__gte=period_min) if is_valid_query_param(period_max): qs = qs.filter(period__date__lte=period_max) if is_valid_query_param(struct_division) and struct_division != 'Choose...': qs = qs.filter(worker__struct_division__name=struct_division) if is_valid_query_param(worker) and worker != 'Choose...': qs = qs.filter(worker=worker) if is_valid_query_param(work_done) and work_done != 'Choose...': qs = qs.filter(work_done__name=work_done) context = { 'queryset': qs, 'struct_divisions': struct_divisions, 'workers': workers, 'workstype': workstype, } return render(request, 'bootstrap_form.html', context) All works well, except: if is_valid_query_param(worker) and worker != 'Choose...': qs = qs.filter(worker=worker) It's return ValueError at /boot/ Field 'id' expected a number but got 'Chambers Jessica '. I tried different syntax, but nothing helped How … -
Handling JSON response from a Django QuerySet via AJAX
I am getting a JSON response from a Django view. def loadSelectedTemplate(request): # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the template matching the ID templateID = request.GET.get("templateID", None) # check for the template matching ID in the database. template = list(operationTemplates.objects.filter(templateID = templateID)) if operationTemplates.objects.filter(templateID = templateID).exists(): # if template found return record ser_template = serializers.serialize('json', template ) return JsonResponse({"valid": True, "template": ser_template}, status=200) else: # if nick_name not found, then user can create a new friend. return JsonResponse({"valid": False}, status = 200) the response is received can be logged to the console. // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'loadSelectedTemplate' %}", data: {"templateID": templateID}, success: function (response) { // if valid template, add to textarea if (response["valid"]){ var template = response["template"]; console.log(response); } Json object looks like this; { "valid": true, "template": "[{\"model\": \"opnoteannotator.operationtemplates\", \"pk\": 14, \"fields\": {\"templateCategory\": \"Lower Limb\", \"templateName\": \"Femoral to below knee Bypass using autologous vein\", \"templatePreopBundle\": \"WHO check list completed.\\r\\n Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\", \"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\", I want to add the objects in "fields" to a textarea … -
How to pass a dynamically changing variable from python to HTML and get the browser to re-render the new data without reloading the whole web-page?
I would like to achieve the following: pass a variable from my python script to a HTML page get the browser to display the updated information DO NOT re-render, or reload the WHOLE HTML page as this would take too long (new data will be transmitted from the python script to the HTML page every 250ms or so.) data is generated live by the python script and so the solution have to take this into account After researching the whole day and watching numerous tutorials, I understood that Flask or Django could be used to achieve this via a concept called "templating". Unfortunately I am complete beginner and I got lost in the details without seeing the "big picture" of what is need to be done... So I ended up here, hoping someone can clear up my understanding about the topic without assuming any previous knowledge... So I have a super simple HTML file as below: <!DOCTYPE html> <html> <head> <title>Simple Test</title> </head> <body> <h1>Changing Number:</h1> <h1 id="number">0</h1> and I also have a python script: import random import time for i in range(10): myvar = random.randint(1, 10) time.sleep(1) The goal is to pass myvar to the html element with the … -
how to access an element from a list of dictionaries
I'm trying to build a cart view following a tutorial and I need to print out the quantity of an item. I have two functions in utils.py from where I wanna access the quantity element and print it out in a view, currently getting an error unhashable type: 'list' def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart:', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]["quantity"] product = Product.objects.get(id=i) total = (product.final_price * cart[i]["quantity"]) order['get_cart_total'] += total order['get_cart_items'] += cart[i]["quantity"] item = { 'product':{ 'id':product.id, 'name':product.name, 'final_price':product.final_price, 'image_URL':product.image_URL, }, **#print the quantity on view** 'quantity':cart[i]["quantity"], 'get_total':total, } items.append(item) except: pass return {"items": items, "order": order, "cartItems": cartItems} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems':cartItems ,'order':order, 'items':items} def my_view(request): data = cartData(request) qty = data['item',['quantity']] print(qty) -
nginx not serving statick files django 4.1
i am new in deploy projects my static files not serving with nginx thats look my site-available/myprject file server{ listen 80; server_name mydomain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/user/project/static; } location /media/ { autoindex on; alias /home/user/project/media; } location / { proxy_pass myIp:myPort; } } my static files and media have this path /home/user/project/staict files and media files that's how it looks my settings.py configurations STATIC_URL = '/static/' STATIC_ROOT =os.path.join(BASE_DIR,'static') my debug variable is false i run collectstatic thanks for any answers. -
why I'm getting "Not Found: /api/v1.0/productos/${this.id_product}/"
I got a problem with vue.js. I made a CRUD, and got an issue trying to use PUT to update. when I applied this method to send update information to Django, an error appeared: METHOD IN VUE.JS methods: { onSubmit(evt){ evt.preventDefault() const path = 'http://127.0.0.1:8000/api/v1.0/productos/${this.id_product}/' axios.put(path, this.form).then((response) => { this.form.nombreProd = response.data.nombreProd this.form.precioProd = response.data.precioProd this.form.contenido = response.data.contenido this.form.descripcionProd = response.data.descripcionProd alert("Actualización exitosa") }) .catch((error) => { console.log(error) }) } ANSWER IN DJANGO Not Found: /api/v1.0/productos/${this.id_product}/ [02/Oct/2022 12:57:46] "PUT /api/v1.0/productos/$%7Bthis.id_product%7D/ HTTP/1.1" 404 2609 Trying to understand, I realized that it could be an issue with the curly braces, but I don´t know how to solve it -
Django: Nested Loop In Template
category = ['cat1','cat2','cat3'] inventory = CurrentInventory.objects.all() for cats in categories inventorybycat = inventory.filter(category =cats) setofinventories.append(inventorybycat) dictofstuff = [zip(setofinventories,categories)] context = { 'setofinventories':setofinventories 'category':category 'dictofstuff':dictofstuff } In views.py above this loop creates a list of objects per each category. In the template below this loop prints a filtered object list per every item in the category list. {% for inventory in setofinventories%} {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement. I would either like to use zip(category,setofinventories) to pass these two items together, or create a category model, filter by that model and then I can reference that model by item? If I zip these items dictofstuff = [zip(setofinventories,categories)] How do I reference the category in the template? {% for inventory in setofinventories%} {{categories{{[forloop.counter]}}}}#This line does not work {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} -
Poblem when updating a table using celery task: OperationalError
I use Celery task and got an error I do not understand. I loop over a table (that contain query definitions) to edit missing/inconsistent data in a database (using API) and registered discrepencies in another table. If I run query one at a time, it works but when I try to loop over queries, I got an error OperationalError('server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n') def DCF_edition(self): DCF_BEFORE_UPDATE = pd.DataFrame.from_records(DataCorrectionForm.objects.all().values()) DCF_BEFORE_UPDATE = DCF_BEFORE_UPDATE.astype({'record_date': str,'created_date': str}) if not DCF_BEFORE_UPDATE.empty else DCF_BEFORE_UPDATE data = [] # load queries definition queries = queries_definitions() if not queries.empty: for index, row in queries.iterrows(): try: missing_or_inconsistent = missing_or_inconsistent_data(row['ide'],row['query_type'],row['crf_name'].lower(),row['crf identification data.append(missing_or_inconsistent[['dcf_ide','category','crf','crf_ide','pat','record_date','field_name','field_label','message','field_value','dcf_status','DEF','deactivated']]) DCF_AFTER_UPDATE = pd.concat(data) DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop_duplicates(keep='last') DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop(['DEF'], axis=1) DCF_AFTER_UPDATE.rename(columns = {'pat':'patient',}, inplace = True) except Exception as e: Log.objects.create(dcf_edition_status=0,dcf_edition_exception=str(e)[:200]) continue # Cast date into string format to be able to dumps data DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.astype({'record_date': str}) if not DCF_AFTER_UPDATE.empty else DCF_AFTER_UPDATE records = json.loads(json.dumps(list(DCF_AFTER_UPDATE.T.to_dict().values()))) for record in records: if not DCF_BEFORE_UPDATE.empty and record['dcf_ide'] in DCF_BEFORE_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=2) else: DataCorrectionForm.objects.get_or_create(**record) # resolved dcf => status=0 if not DCF_BEFORE_UPDATE.empty: records = json.loads(json.dumps(list(DCF_BEFORE_UPDATE.T.to_dict().values()))) for record in records: if record['dcf_ide'] not in DCF_AFTER_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=0) Log.objects.create(dcf_edition_status=1) return True