Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unabe to load Dynamic images using loop counter in django
I am unable to load th image using loop counter. Its loading the page http://localhost:8000/static/images/png%7B%7Bforloop.counter%7D%7D.png instead of http://localhost:8000/static/images/png1.png http://localhost:8000/static/images/png2.png def html(request): # template = loader.get_template('index.html') # return HttpResponse(template.render()) params = {'movie':['Dr Strange','Shamsheera']} return render(request, 'index.html',params) <table style="width:100%"> {% for m in movie %} <tr> <td width="30%"><img src="{% static 'images/png{{forloop.counter}}.png' %}" alt="{{forloop.counter}}"></td> <td width="20%">{{m}}</td> <td width="50%">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam explicabo asperiores est nostrum mollitia dignissimos unde sapiente quos deserunt eveniet placeat beatae neque incidunt quia nulla itaque voluptatum earum, repudiandae enim cum fugiat nisi magnam dolorem? Deserunt odit, repellat eius qui asperiores adipisci soluta blanditiis inventore dignissimos est et nesciunt porro, iusto, ex at consectetur obcaecati unde! Dolorem rerum veniam mollitia, provident, sunt officiis maxime maiores atque cumque consequatur quidem molestias amet ullam? Iure pariatur, tempora voluptatem sint, quidem eius vel nemo eveniet eaque unde doloremque. Adipisci, maiores corrupti, ut debitis, error odio omnis odit id ratione enim minima a!</td> </tr> {% endfor %} </table> -
Django csv upload to db works but throws error
I have created an app named customer within a project named Website using django. I have created a csv upload in the admin area which is connected to the Postgres db. An error occurs when I upload the CSV returning: Exception Type: IndexError Exception Value: list index out of range However the CSV file is still added to the db but the error screen is displayed. Even more strangely if I a notepad doc as csv containing the data and upload that I get no error until I try to upload a second data set. If I save an excel doc as csv I get the error. Where am I going wrong ? Models.py class customer(models.Model): name = models.CharField(max_length=50, blank=True) balance = models.CharField(max_length=120, blank=True) def __str__(self): return self.name Admin.py from django.contrib import admin from django.urls import path from django.shortcuts import render, redirect from .models import customer from django import forms from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from import_export import resources class data(resources.ModelResource): class Meta: model = customer class CsvImportForm(forms.Form): csv_upload = forms.FileField() class CustomerAdmin(admin.ModelAdmin): list_display = ('name', 'balance',) def get_urls(self): urls = super().get_urls() new_urls = [path('upload-csv/', self.upload_csv), ] return new_urls + urls def upload_csv(self, … -
How to load sql dump in a containerized django docker which depends on postgres
I am running a Django container on docker which depends on Postgres. Now the issue is, when I try to load the postgresql docker-compose up cat /tmp/dump.sql | sudo docker exec -i <container_id> psql -U <user> -d <database_name> This imports the first few tables and gives me a lot of errors on the terminal An example constraint "table_id" for relation "table_name" already exists Another example null value in column "column_name" violates not-null constraint Another one insert or update on table "table_1" violates foreign key constraint "table_id" I wanted to know is this even the right way to import this data. Plus I cant seem to drop the database as it is already being used by django. Note: I tried with volumes where I imported the db with postgresql. But everytime I run django, the database gets reset. I am guessing it has something to do with the migrations, but I can't touch that part. -
Tests with DRF ApiClient and DummyCache backend fail with UpdateError when try to save session
I test my view, which returns data about the previous session. Test with request factory works well. def test_session_view(self, rf): """Retrieve user token. path: /auth/session/ request: None respond: {token: str} """ url = reverse('get_session') view = SessionView.as_view() user_id = '589d1bac-d935-4160-92ce-b18170f35188' token: str = 'cl5aml1wh0000bh022o5em2re' request = rf.get(url) session_key = None engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore(session_key) request.session.update({ 'token': token, 'user_id': user_id, 'tenant_id': None }) request.session.save() response = view(request).render() assert response.status_code == 200 assert UserSessionFetchResponse(**response.data) But if I use DRF ApiClient test fails with UpdateError: ...django/contrib/sessions/backends/cache.py:62: in save raise UpdateError E django.contrib.sessions.backends.base.UpdateError This is the failing test: def test_retrieve_saved_session(self, api_client): """Fetches token from db.""" endpoint = reverse('get_session') # настройка условий user_id = '589d1bac-d935-4160-92ce-b18170f35188' token: str = 'cl5aml1wh0000bh022o5em2re' tenant_id: str = 'a1bd988a-9c52-4f97-bfac-9478d58cb0c3' client = api_client() client = set_api_client_defaults( client=client, ) session = client.session session.update({ 'token': token, 'user_id': user_id, 'tenant_id': tenant_id }) session.save() response: 'Response' = client.get( path=endpoint, ) assert response.status_code == 200 assert response.data['token'] == token assert UserSessionFetchResponse(**response.data) "api_client" is a fixture: @pytest.fixture() def api_client() -> Type[APIClient]: return APIClient Relevant settings: SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } Manual tests and tests with request factory work vell. I do something wrong with ApiClient. Django … -
Double authentication in rest api
I am trying to get the rest API data in python using the request module. I am using double authentication in my API. When I run the code, I got error 401 but this is working perfectly on postman import requests response = requests.get('http://localhost:8285/x/1/mindie?C=dfghdh&SDate=01-05-2022&EDate=02-05-2022', headers={'Authorization': 'Basic dweeytdvgccsbj','Authorization': 'Basic fhgvecdjfvnhi'}) s = response.json() print(response) -
How to add SVG object in HTML?
I am following some examples of d3.js to plot graphs. For reference here is the link. Following is the code where I've used the LineChart function to build the plot. With Django as backend. {% load static %} <html> <script src="https://d3js.org/d3.v6.js"></script> <body> <h1> Hello! </h1> <div id="chart"></div> </body> <script> // set the dimensions and margins of the graph const margin = {top: 10, right: 30, bottom: 30, left: 60}, width = 460 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; // append the svg object to the body of the page const svg = d3.select("#chart") .append("chart") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // Copyright 2021 Observable, Inc. // Released under the ISC license. // https://observablehq.com/@d3/line-chart function LineChart(data, { x = ([x]) => x, // given d in data, returns the (temporal) x-value y = ([, y]) => y, // given d in data, returns the (quantitative) y-value defined, // for gaps in data curve = d3.curveLinear, // method of interpolation between points marginTop = 20, // top margin, in pixels marginRight = 30, // right margin, in pixels marginBottom = 30, // bottom margin, in pixels marginLeft = … -
Long running tasks is cancelled - Celery5.2.6
I have a project hosted in Digital Ocean in a Basic Droplet with 2 GB Ram. In my local machine, the long-running task runs between 8-10 minutes and is still successful.However in Digital Ocean droplets, often times the celery will not succeed in the long-running task. Current celery - celery 5.2.6 I have two configurations in supervisor Running the celery worker celery -A myproject worker -l info Running the celery beat celery -A myproject beat -l info This is the message from celeryd.log CPendingDeprecationWarning: In Celery 5.1 we introduced an optional breaking change which on connection, loss cancels all currently executed tasks with late acknowledgment enabled. These tasks cannot be acknowledged as the connection is gone, and the tasks are automatically redelivered back to the queue. You can enable this behavior using the worker_cancel_long_running_tasks_on_connection_loss setting. In Celery 5.1 it is set to False by default. The setting will be set to True by default in Celery 6.0. warnings.warn(CANCEL_TASKS_BY_DEFAULT, CPendingDeprecationWarning) [2022-07-07 04:25:36,998: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) [2022-07-07 04:25:39,066: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused.. Trying again in 4.00 seconds... … -
Celery redis result backend type conversion
We have been using redis as a celery backend for a lot of time. Recently, we decided to store some json data in it . So here comes the problem: after retrieving result from celery data through AsyncResult(task_id) data such as {True:10,False:1} becomes {1:10,0:1}. Probably because redis has no boolean type in it's core. Keeping results with boolean keys is crucial for our system. I've tried to add CELERY_RESULT_SERIALIZER = 'json' into config with no effect. Is there any solution for this? -
How do i get the ID of the current form in Django Admin
i'm using admin.py in django and i want to know how can i get my current id from the form just for customize the page. Anyone can help me please? -
Django 403 Error while using POST method through Front end ( Angular Js )
views.py class ExtendUserSession(MiddlewareMixin): """ Extend authenticated user's sessions so they don't have to log back in next 15 minutes (set by Django's default `SESSION_COOKIE_AGE` setting). """ def process_request(self, request): # Only extend the session for auth'd users if request.user.is_authenticated: reason = CsrfViewMiddleware('get_response').process_view(request, None, (), {}) if reason: # process_view returns HTTPException pass else: # process_view returns None - No error on HTTP request from CSRF middleware verification request.session.set_expiry(86400) settings.py CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', #I have changed the localhost as in my local ip. so 8000 is backend and 8080 is frontend port 'http://localhost:8080', ] # A list of origins that are allowed to make cross-site HTTP requests to your Django application. CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000', 'http://localhost:8080', ] CSRF_WHITELIST_ORIGINS = ['localhost:8000','localhost:8080'] # SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # SESSION_COOKIE_NAME='sessionid' SESSION_COOKIE_PATH='/' #default / # SESSION_COOKIE_SECURE=True#default False SESSION_COOKIE_SECURE=False # SESSION_COOKIE_DOMAIN='localhost:8080' #default None SESSION_COOKIE_DOMAIN= None SESSION_COOKIE_HTTPONLY=False # default is True SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 86400 CSRF_COOKIE_NAME='X-CSRFToken' CSRF_COOKIE_AGE=86400 CSRF_COOKIE_DOMAIN=None CSRF_COOKIE_HTTPONLY=False CSRF_COOKIE_PATH='/' CSRF_COOKIE_SECURE=False I'm able to get post method from POSTMAN for eg: But while trying through Front-end this is the error I'll be getting Is there any settings I have to change for making it accepting request through FrontEnd -
Having trouble updating data in CRUD using Serializers
I am having trouble updating my data in CRUD operation while using Serializers in the sub category model.Category and sub category are connected using foreign keys.I have been trying see where I am going wrong in terms of my code but I am unable to figure it out Update function def edit_sub_categories(request,id): if request.method == 'GET': print('GET',id) editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"SUBCategories":s.data,"context": category.data} # print(category.data) return render(request,'polls/edit_sub_categories.html',hm) else: print('POST',id) editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') # print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() print('form error',form.errors) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: return redirect("sub_categories:show_sub_categories") below is the html code <form method="POST" > {% csrf_token %} <table> <thead> <tr> <td>Categories Name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.category_name}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" value="{{SUBCategories.sub_categories_name}}"></td> </tr> <tr> <td>Sub Categories Description</td> <td><input type="text" name="sub_categories_description" value="{{SUBCategories.sub_categories_description}}"></td> </tr> <tr> <td> <a href="{% url 'sub_categories:show_sub_categories' %}"> <button type="submit" class="btn btn-success" value="update record"> <i class="fa-solid fa-database"> Update Value</i> </button> </a> </td> <td> {% if messages %} {% for mess in messages %} <b style="color:green;"> {{mess}} </b> {% endfor %} {% endif … -
How would I disable a button with the context value
How would I use the context value to check if the currently logged in user has the same team and it's not null and the is_edit field is true. {% if request.user.is_edit and team==request.user.team%} produces Could not parse the remainder: '==request.user.team' from 'team==request.user.team' edit.html {% extends 'base.html' %} {% block title %}Add{% endblock %} {% block content %} <h1 class="cardHeader">Edit Page</h1> <div class="card"> <div class="container"> <h1>Edit team member</h1> <p>Edit contact info,location and role</p> </div> <form method = "POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ editProfileForm.as_p }} <input type="submit" name="editProfileForm" value="Save"> <!-- Check if the user who can delete the team member is the same team and had admin role? --> {% if request.user.is_edit and team==request.user.team%} <input type="submit" name="deleteProfileForm" value="Delete"> {% endif %} </form> </div> {% endblock %} views.py def edit(request,user_id): context={} try: user = Profile.objects.get(id=user_id) print(user,user_id) except Exception as e: print(str(e)) return redirect('home') context['team']=user.team #Currently logged in user has to have is_edit? and be the same team #if request.user.team != user.team and request.user.is_edit: #return redirect('home') if request.method=="POST": if "editProfileForm" in request.POST: print('Editing') edit_profile_form = UserProfileForm(request.POST or None,instance=user) if edit_profile_form.is_valid(): edit_profile_form.save() print(edit_profile_form) return redirect('home') else: context['editProfileForm'] = edit_profile_form return render(request,'edit.html',context) if "deleteProfileForm" in request.POST: print('Deleting') try: user.delete() #messages.success(request, "The user is … -
Django- Retrieving and normalising data from mongodb
In django project, I have connected with mongodb without creating models. I just writing data directly into collection using python code. All the collections are working independently. For example, I have employee and employment collection(one employee has multiple employment). There is no foreignkey relationship between employee and employment. # employee response {{"emp_id": "S101", "emp_name": "Kim", "dob": "1995-12-30"} {"emp_id": "S102", "emp_name": "Sasi", "dob": "2000-12-01"} {"emp_id": "S103", "emp_name": "Shakthi", "dob": "2001-01-01"}} # employment response {{"emp_id": "S101", "employment_type": "contract", "status": "terminated", "date": "2017-04-05"}, {"emp_id": "S101", "employment_type": "contract", "status": "pending", "date": "2018-07-09"}, {"emp_id": "S102", "employment_type": "Permanent", "status": "active","date": "2017-04-05"}, {"emp_id": "S103", "employment_type": "Permanent", "status": "active", "date": "2017-04-05"}} when I retrieve employee details I would like to get response like below, { {{"emp_id": "S101", "emp_name": "Kim", "dob": "1995-12-30", "employment_status": {{"emp_id": "S101", "employment_type": "contract", "status": "terminated", "date": "2017-04-05"}, {"emp_id": "S101", "employment_type": "contract", "status": "pending", "date": "2018-07-09"}} {{"emp_id": "S102", "emp_name": "Sasi", "dob": "2000-12-01", "employment_status":{"emp_id": "S102", "employment_type": "Permanent", "status": "active","date": "2017-04-05"}}} } How can i achieve this? Thanks in advance. -
Unknow field by switching default login to email
Unknown field(s) (username) specified for Profile. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. I have the above error I think it's due to how I switched email to the default login so username isn't viable anymore. I used readonly_fields=('username',) in admin.py it worked but I am not sure why it works. admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import UserProfileForm from .models import Profile class CustomUserAdmin(UserAdmin): add_form = UserProfileForm model = Profile list_display=('id','email','password','first_name','last_name','phone_number','is_edit','team') ordering = ('email',) pass admin.site.register(Profile, CustomUserAdmin) ##Maybe rework this later for better inclusion of all models. from django.apps import apps from django.contrib import admin class ListAdminMixin(object): def __init__(self, model, admin_site): self.list_display = [field.name for field in model._meta.fields] super(ListAdminMixin, self).__init__(model, admin_site) models = apps.get_models() for model in models: admin_class = type('AdminClass', (ListAdminMixin, admin.ModelAdmin), {}) try: admin.site.register(model, admin_class) except admin.sites.AlreadyRegistered: pass model.py from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField import uuid from .managers import CustomUserManager class Team(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Profile(AbstractUser): username = None email = models.EmailField('email address', unique=True) # Here first_name = models.TextField(max_length=100, blank=True,null=True) last_name = models.TextField(max_length=100, blank=True,null=True) phone_number = PhoneNumberField(max_length=25, region='US') is_edit = models.BooleanField(default=False) team = models.ForeignKey(Team,on_delete=models.CASCADE,null=True, blank=True, default = None) USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
Data not getting updated in shopping CRUD operations
I am currently writing a shopping CRUD operation where Categories and SUB categories are connected via foreignkey and I am using serializers. I have written update function to edit the data ,however,the data in not getting updated despite writing the update function below is the edit and insert function of the sub_categories def edit_sub_categories(request,id): if request.method == 'GET': editsubcategories = SUBCategories.objects.filter(id=id).first() s= SUBCategoriesSerializer(editsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"SUBCategories":s.data,"context": category.data} # print(category.data) return render(request,'polls/edit_sub_categories.html',hm) else: editsubcategories = {} d = SUBCategories.objects.filter(id=id).first() if d: editsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') editsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') # print(editsubcategories) form = SUBCategoriesSerializer(d,data=editsubcategories) if form.is_valid(): form.save() # print("hkjk",form.data) print('form error',form.errors) messages.success(request,'Record Updated Successfully...!:)') return redirect('sub_categories:show_sub_categories') else: return redirect("sub_categories:show_sub_categories") def insert_sub_categories(request): if request.method == "POST": form = SUBCategoriesSerializer(data=request.POST) if form.is_valid(): form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("sub_categories:show_sub_categories") category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) hm = {"context": category.data} return render(request, "polls/insert_sub_categories.html", hm) html code of edit page <form method="POST" > {% csrf_token %} <table> <!--content-table--> <thead> <tr> <td>Sub Categories ID</td> <td><input type="text" name="id" value="{{SUBCategories.id}}" readonly></td> </tr> <tr> <td>Categories Name</td> <td> <!-- <input type="text" name="category_name" value="{{SUBCategories.category_name}}"> --> <select name="category_name" id=""> {% for c in context %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>Sub Categories Name</td> <td><input type="text" name="sub_categories_name" … -
How to convert raw sql to Django ORM?
I have two models wp_8_posts and wp_8_postmeta and I have sql query to run on this model. sql_query = "SELECT a.ID, a.post_title, a.post_name, a.post_date, b.meta_value, c.meta_value, f.guid FROM wp_8_posts a, wp_8_postmeta b, wp_8_postmeta c, wp_8_postmeta d, wp_8_postmeta e, wp_8_posts f WHERE a.post_type = 'book' AND a.ID = b.post_id AND b.meta_key='book_pub' AND a.ID = c.post_id AND c.meta_key='book_url' AND a.ID = d.post_id AND d.meta_key='ex_category' AND d.meta_value LIKE '%"var1"%' AND a.ID = e.post_id AND e.meta_key='book_img' AND e.meta_value = f.ID ORDER BY a.post_date DESC LIMIT var2;" There is no relation(foreign key etc.) defined in both the models. I want to use Django ORM, How can I convert this? -
My k8s liveness probe isn't setting the Host
I'm trying to deploy a Django app with startup and liveness probes configured. As it's a Django app, I need the Host header on the probes to match something permitted in my ALLOWED_HOSTS. As my probes are both httpGet checks, the simplest solution seems like it would be to use the httpHeaders field as suggested in the kubernetes docs. This seems to work for the startupProbe, however it's not working for the livenessProbe. Sanitized version of my probes: livenessProbe: httpGet: httpHeaders: - name: Host value: k8s-probes path: /health/liveness port: http scheme: HTTP startupProbe: httpGet: httpHeaders: - name: Host value: k8s-probes path: /health/ port: http scheme: HTTP When the pod startups up, I see 200 responses to the initial startup probes, then once the liveness probe starts, I get 400 responses with the error that the pod IP address isn't in ALLOWED_HOSTS, indicating k8s isn't setting the Host header I've defined for the liveness probe. -
Django destroy and keep newly created testing database
I know we could use --keepdb when running manage.py test to keep the test databases, but when i have a new migration, the old DB need to be destroyed to create new one. Is there any way to destroy the old DB AND keep it after test completed ? -
Cannot assign "'": "" must be a "" instance. ModelChoiceField
I have a form where a user can select the title of an object and then save it but when I do hit save, I get an error. I am very certain that this problem is because I am using ModelChoiceField which returns ids of objects instead of the instances of that object. So, I have two models: InvoiceModel class Invoice(models.Model): line_one = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 1", blank=True, null=True, default='') line_one_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_one_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_one_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) Invoice.line_one is referenced to Inventory.product_number. InventoryModel: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, null=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title InvoiceForm: class InvoiceForm(forms.ModelForm): line_one = forms.ModelChoiceField(queryset=Inventory.objects.values_list('title', flat=True), label="Line 1") line_one_unit_price = forms.CharField(widget=forms.Select, label="Unit Price(₹)") class Meta: model = Invoice fields = ['line_one',#...] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['line_one_unit_price'].widget.choices = [(i.amount, i.amount) for i in Inventory.objects.all()] I actually have 10 lines, [i.e., line_two, etc..] but I am just pasting the code for line_one here for simplicity. I also want only the amount of the object selected in line_one to be displayed in line_one_unit_price. … -
Connection refused on ipv6 server
I'm making a little side project with Django and i want to acces this local server from outside my lan. So I decided to try ipv6 I set ALLOWED_HOSTS = ["*"] and run the server as python manage.py runserver --ipv6 "[::1]:8000", but i can't access it from another pc (even from the ones i could with ipv4, connected to my wifi). I get the Connection Refused error in the browser. And yes, my port is open in the firewall (sudo ufw allow 8000) One last thing, checking with wireshark, i found the TCP packages get to the server. A RST flag is sent. -
How to parallelize requests in django script run from the command line?
I have a local Django project and some scripts that execute requests in parallel, but the requests are always executed synchronously. Here is a sample script that demonstrates the issue: import asyncio import json import requests from asgiref.sync import async_to_sync async def do_task(task): print(f"starting task {task}") response = requests.get("https://swapi.dev/api/people/1") response_json = json.loads(response.text) print(response_json) print(f"finished task {task}") async def run(): tasks = set() for i in range(5): task = asyncio.create_task(do_task(i)) tasks.add(task) task.add_done_callback(tasks.discard) await asyncio.gather(*tasks) # python manage.py shell < path/to/scripts/test.py if __name__ in ("__main__", "django.core.management.commands.shell"): print("==start==") async_to_sync(run)() print("==done==") The output for this script is: ==start== starting task 0 {...} # response finished task 0 starting task 1 {...} # response finished task 1 starting task 2 {...} # response finished task 2 starting task 3 {...} # response finished task 3 starting task 4 {...} # response finished task 4 ==done== I would expect to see something closer to this (all tasks started at the same time): ==start== starting task 0 starting task 1 starting task 2 starting task 3 starting task 4 {...} # response {...} # response {...} # response {...} # response {...} # response finished task 0 finished task 1 finished task 2 finished task 3 finished … -
When trying to access excel file getting error
CODE import openpyxl class FileView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = [IsAdminUser] def post(self, request, *args, **kwargs): ''' API user to import hospital's adimission data in bulk, using xls file ''' # getting the excel file # try: # excel_file = request.FILES["excel_file"] # except: # return Response({'err_msg': 'bad request'}, status=status.HTTP_400_BAD_REQUEST) excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets worksheet = wb['Sheet1'] # excel_data = [] print(worksheet) Error Internal Server Error: /file/upload/ Traceback (most recent call last): File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\utils\datastructures.py", line 76, in getitem list_ = super().getitem(key) KeyError: 'excel_file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "G:\office\medicover\medicover_bloodbank_django\file_app\views.py", line 27, in post excel_file = request.FILES["excel_file"] File "G:\office\medicover\medicover_bloodbank_django\venv\lib\site-packages\django\utils\datastructures.py", line 78, in getitem raise … -
show database to template django
hello I've been trying for a long time to make the database appear in the template but since then I can't show the database to the index.html I use version 4 of django with bootstrap thank you for showing me the solution because on my side I really tried everything but zero always empty in the final rendering on my visual MY MODEL from django.db import models class Appartement(models.Model): nom = models.CharField(max_length=200) Ville_et_adresse = models.CharField(max_length=200) NB_de_chambre = models.DecimalField(max_digits=20, decimal_places=0) NB_de_douche = models.DecimalField(max_digits=20, decimal_places=0) NB_de_garage = models.DecimalField(max_digits=20, decimal_places=0) NB_de_piscine = models.DecimalField(max_digits=20, decimal_places=0) NB_de_cuisine = models.DecimalField(max_digits=20, decimal_places=0) Superficie = models.DecimalField(max_digits=20, decimal_places=0) Prix = models.DecimalField(max_digits=20, decimal_places=0) Description = models.TextField(max_length=1000, default=True) image = models.ImageField(upload_to="static/upload/", blank=True, null=True) actif = models.BooleanField(default=True) def __str__(self): return f'{self.name}' class Meta: ordering = ['-id'] verbose_name_plural =("Appartements") <div class="col-md-12"> <div class="tab-content mt-30"> <div class="tab-pane fade show active" id="all_property"> <div class="row"> <div class="col-xl-4 col-md-6 col-sm-12"> <div class="single-property-box"> <div class="property-item"> <a class="property-img" href="avendre"><img src="{% static 'images/property/property_1.jpg'%}" alt="#"> </a> <ul class="feature_text"> <li class="feature_or"><span>À VENDRE</span></li> </ul> <div class="property-author-wrap"> </div> </div> {% for appartement in Appartement %} <div class="property-title-box"> <h4><a href="avendre">{{ appartement.nom }}</a></h4> <div class="property-location"> <i class="fa fa-map-marker-alt"></i> <p>{{ Appartement.Ville_et_adresse}}</p> </div> <ul class="property-feature"> <li> <i class="fas fa-bed"></i> <span>{{ Appartement.NB_de_chambre }}</span> </li> <li> <i class="fas fa-bath"></i> <span>{{ … -
How can I use Speech Recognition in Django on the client side?
I am writing an application in Django. There should be a field to fill in, which the user should be able to fill in by voice. He should see what he dictated and, if an error occurs, be able to fix it quickly. I wrote an html file with a small script in js inside. Here are its contents: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input id="the_button" type="button" value="Click to Speak"> <input id="the_form" type="text" name="q" size=80 > <script type="text/javascript"> var SpeechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)(); const the_button = document.getElementById("the_button"); the_button.addEventListener('click', function(event) { SpeechRecognition.start(); }) SpeechRecognition.onresult = function(event){ var the_text = event.results[0][0].transcript; document.getElementById('the_form').value = the_text; }; SpeechRecognition.onend = function(){ SpeechRecognition.stop(); }; </script> </body> </html> This html file works fine when I open it in the browser. But when I integrate this file into my Django project in the developer console I get an error in the line: var SpeechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition || window.msSpeechRecognition)(); I installed SpeechRecognition modules in my Django project, it doesn't seem to have anything to do with my problem. I would be grateful for any advice on … -
Django change external user-facing field name
I have a model that will have two similar "id"-like fields. One will be the primary key, one will be the a human-readable id. On the backed/in the model, I have differentiated them as such pk_id = models.AutoField(primary_key=True) # internal only, incrementing int ext_id = models.CharField(max_length=128) # external facing, words+int When the user does a query to get a list of the models, I want to EXCLUDE pk_id entirely, and have ext_id appear simply under the name id. Like this: { 'id' : 'name_title_001' # same as ext_id 'other_fields' : 'bla bla bla' } How do I accomplish this?