Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with django migration postgres deadlock?
So, I was deploying the django app to production and then the infamous postgres deadlock situation happened. This happens during the migration. Django version: 3.2 Postgres 13 Google cloud sql postgres. OperationalError deadlock detected DETAIL: Process 112506 waits for AccessExclusiveLock on relation 29425 of database 27145; blocked by process 112926. Process 112926 waits for RowShareLock on relation 29381 of database 27145; blocked by process 112506. HINT: See server log for query details. I ran this query to get the process info: SELECT 29425::regclass,29381::regclass from pg_locks; and result: regclass | regclass "custom_requestlog" "auth_user" "custom_requestlog" "auth_user" I am not sure how to proceed ahead, as the pgaudit has been enabled but it doesnt show anything and also the query insights is not that helpful. Attached is image of query insights. Any help would be helpful please! -
Error won't showing up, Form validation with Django
I just started learning Django for my new Forum project, I'm trying to find it out myself but this problem has been bothering me since 2 days. I am trying to make a registration validation for my form, I am using messages.error(request, "Text") to make an error appear on screen, but it doesn't work, and just shows nothing. Here is a part of my HTML code: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form class="login100-form validate-form" method='POST' action="{% url 'users:register' %}" > {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username" required> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter password"> <input class="input100" type="password" name="pass" placeholder="Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Confirm password"> <input class="input100" type="password" name="pass-confirm" placeholder="Confirm Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter Email"> <input class="input100" type="email" name="mail" placeholder="E-Mail" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn"> Register </button> </div> <div class="text-center p-t-90"> <a class="txt1" href="login"> Already registered? </a> </div> </form> </div> </div> </div> Here is my views.py register function: def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["pass"] password_confirm … -
Django filter can work in generate PDF using pdfkit
Am trying to generate pdfkit using these way view.py def view_PDF(request, id): sub = get_object_or_404(Student, id=id) sub_fil = Subject.objects.filter(student_name = request.user) context = { "sub": sub.id, "sub_no": sub.sub_no, "book": sub.book, 'sub_fil':sub_fil, } return render(request, 'school/pdf_template.html', context) def generate_PDF(request, id): # Use False instead of output path to save pdf to a variable pdf = pdfkit.from_url(request.build_absolute_uri(reverse('student-detail', args=[id])), False) response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'filename="student.pdf"' return response When am trying to omit this line sub_fil = Subject.objects.filter(student_name = request.user)working good without information from subject but that line is very important to display some informations. when run server with that line i got this problem OSError at /student-download/2 wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [==============================> ] 50% Error: Failed to load http://127.0.0.1:8000/student-detail/2, with network status code 299 and http status code 500 - Error downloading http://127.0.0.1:8000/student-detail/2 - server replied: Internal Server Error [============================================================] 100% Counting pages (2/6) [============================================================] Object 1 of 1 Resolving links (4/6) [============================================================] Object 1 of 1 Loading headers and footers (5/6) Printing pages (6/6) [> ] Preparing [============> ] Page 1 of 5 [========================> ] Page 2 of 5 [====================================> ] Page 3 of 5 [================================================> ] Page 4 of 5 [============================================================] … -
Out of range float values are not JSON compliant: nan, Django Rest Framework with Json Serialization Exception
I work with rest_framework to implement a django API. The table Order from my database has nan fields, and Nan generates the error Out of range float values are not JSON compliant: nan. How to ensure that serializing Nan to JSON works. #serializers.py from rest_framework import serializers from api.models import Order class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('id', 'status', 'description') The serialization here is a black box, i don't find where to fix this -
how to get item from certain database variable?
models.py: class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') i have here shop_name and adress. The thing i need is to click a button wich gets shop_name from text area and match it with adress. Is there any way to do it? as i mentioned i need to get the name of shop from text area and then show its andress -
Braintree Paypal integration through API
How can i integrate PayPal payment gateway through braintree-sandbox whose client side is on Android studio and server-side on Django framework with the help of API. -
Can someone help me to implement fecth api?
I have created a like and dislike system in Django but now I want to do it with fetch api in Javascript. I don't know how to implement it, I don't understand very well how to do it. I have created the url: urlpatterns = [ path("like/<int:id>", views.like_post, name='like_post') ] Then, in views.py: @login_required def like_post(request, id): if request.method == "POST": postId = Post.objects.get(id = id) if not postId.likes.filter(id = request.user.id).exists(): postId.likes.add(request.user) postId.save() return HttpResponseRedirect (reverse("index")) else: postId.likes.remove(request.user) postId.save() return HttpResponseRedirect (reverse("index")) return HttpResponseRedirect (reverse("index")) post.html <form method="post" action="{ url 'like_post' post.id }"> {%csrf_token%} {% if request.user in post.likes.all %} <button type="submit" style="background: none; outline: none; border: none; color: inherit; font: inherit; line-height: normal; overflow: visible; padding: 0;"> <svg xmlns="http://www.w3.org/2000/svg " width="16 " height="16 " fill="currentColor " class="bi bi-heart-fill " viewBox="0 0 16 16 "> <path fill-rule="evenodd " d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z "/> </svg> </button> {% else %} <button type="submit" style="background: none; outline: none; border: none; color: inherit; font: inherit; line-height: normal; overflow: visible; padding: 0;"> <svg xmlns="http://www.w3.org/2000/svg " width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 "> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 … -
How to set the access token in Insomnia to access DRF API
My Django settings are as follows REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("JWT",), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), } In Insomonia, I do a post a http://127.0.0.1:8000/api/v1/jwt/create/ and I get back the refresh and access token. When I go to the "POST", I choose "BEARER, and pass in the "TOKEN", but I get { "detail": "Authentication credentials were not provided." } I am not sure how to correctly pass the JWT? -
Django model location from a view
In my models.py few models related to the different entities class GuardSecurity(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='GuardSecurity', editable=False) class SecuredFaciliy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='SecuredFaciliy', editable=False) facility_name=models.CharField(max_length=64) adress=models.CharField(max_length=64) class License(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='License', editable=False) license_name=models.CharField(max_length=64) license_description=models.CharField(max_length=200) class Equipment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='Equipment', editable=False) equipment_name=models.CharField(max_length=64) class AllEntity(models.Model): id = models.UUIDField(primary_key=True) etype = models.CharField(max_length=64) class Meta: managed=False db_table="entity_full_list" They all in common have UUID as the primary key. I implement an SQL view on those models create view entity_full_list as select id, etype from entity_equipment union select id, etype from entity_guardsecurity union select id, etype from entity_license union select id, etype from entity_securedfaciliy To solve the problem of finding a relevant model from a view table I added an etype column that points to the model (string that after can be translated to a command ) Is there another way to point to the exact model from my view? -
How to perform 2 operations in parallel?
I have a problem and I can't figure it out. I have the following code that must save the data that is sent to him by an http request, first on the aws bucket and then by a request on the db. Except that 1 of the 2 operations does not work. Is there a way to do the 2 operations in parallel? @staticmethod def ingest_data(video, metadata, video_dst_path, metadata_dst_path, detected): """ Method that insert a video and a json metadata file into AWS-S3 :param video: video file forwarded by the ingestion endpoint :param video_dst_path: path to save the video on AWS-S3 :param metadata: json file forwarded by the ingestion endpoint :param metadata_dst_path: path to save the json on AWS-S3 :return: response :type {"message": ""}, code status """ try: # This part is for EAV exit plan files = {'video': video, 'metadata': metadata, 'detected': detected} # threading.Thread(target=forward, args=(files,)).start() ########################################################### # resp = requests.post('http://192.168.1.175:8000/forward', files=files) print(files, flush=True) print(metadata,flush=True) print(resp) sleep(15) print ('DENTRO IF RESPONSE 200 ') s3 = boto3.resource( service_name='s3', aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY") ) object = s3.Object(os.getenv("BUCKET_NAME"), video_dst_path) object.put(Bucket=os.getenv("BUCKET_NAME"), Key=video_dst_path, Body=video) print('Dumping and creating object {} in S3 {} bucket'.format(video_dst_path, os.getenv("BUCKET_NAME")),flush=True) object = s3.Object(os.getenv("BUCKET_NAME"), metadata_dst_path) object.put(Bucket=os.getenv("BUCKET_NAME"), Key=metadata_dst_path, Body=metadata) print('Dumping and creating object {} … -
Can't find the error in my django project
I am creating a booking website for hotels using Django, I used the booking api to get the hotels with its images and location highlights... I sent to the django template a list of dictionaries from the backend, each dict represents a hotel, now there is two apis request that I am using 1- To get all the hotels 2-To get the images and location highlights of the hotel based on its id that 1 will give me alongside other info like the name and address... (when a button is pressed) I implemented a loop in the template that will fetch all the hotels from the list on the page and I used the id of the hotel to pass it to a url namespace in the template (Template.html) where I want to call a function (book_now) and pass the arguments below: id of the hotel, name of the hotel, address of the hotel. Now what's happening is that when I choose certain destination like Berlin or Istanbul or Paris I get this error: NoReverseMatch at /homepage/ Reverse for 'book_now' with keyword arguments '{'id_hotel': **'6140138'**, 'name': 'Vital Hotel Fulya Istanbul Sisli', 'add': 'FULYA MAH. MEHMETÇİK CAD. NO: 61 İÇ KAPI … -
When saving ModelFormSet it reads the whole underlying table?
I don't know how to explain the problem in my title, so if someone knows how to better phrase the problem I'm going to describe, I hope there is a way to update the tile. I have to say I already tried to search with google, for a solution, but I'm not able to find something useful I tried to follow there video tutorial (after reading the official Django documentation of course) Video 01 Video 02 I'm using an old version of Django, because I have to connect to MS SQL Database, and this mix of python+django+mssql-backend is the only combination found functioning (I tried with the latest version of Django and Python, but I had to mess around with the mssql-backend because there were a lot of error about deprecated function, for example ugettext_lazy instead of gettext_lazy and many more...) I'm trying to create a small interface to an already existing MS SQL Database (so I can't change the structure of the database). I'm still learning Django, so I'm pretty sure the problem is mine, I have misunderstood something :( Currenty I created a page to search the interesting rows in database table and a page to edit all … -
how to edit urls.py?
i need to create url with this path graphs/<direction>. The direction should be a string because it's the name of some department. i've tried to do this kind of formating, but it didn't work. It tells me that: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graphs/PS/ urls.py from django.urls import path from . import views urlpatterns = [ path('<str:direction>', views.ViewDashboard.as_view()), ] views.py class ViewDashboard(View): def get(self, request, direction: str): string_query = request.get_full_path().split(f"{direction}/")[1] entry = Department.objects.get(department__exact=direction) data = { "title": f"Графики для направления: {direction}", "level_navigation": { "level": 2, "name_level_1": "vm", "url_level_1": "", }, "offset": eval(entry.info_grafana), "grafana_ip": grafana['ip_grafana_server'], "https": grafana['https'] if grafana.get('https') else 'http', "from": "now-30d", } if string_query: string_query = string_query[1:].split("&") for query in string_query: if query.startswith('from='): data['from'] = query.split('from=')[1] return render( request, template_name='graphs/graphs.html', context=data ) and my graphs.html {% extends "vm_mon/wrapper.html" %} {% block content %} <div class="container"> <iframe src="{{ https }}://{{ grafana_ip }}:3000/d/{{ offset.uid }}/{{ offset.slug }}?orgId=1&from=now-30d&to=now&refresh=1d" width="100%" height="1600" frameborder="0"></iframe> </div> {% endblock %} -
About shipping structure in django ecommerce
I wanted to ask what kind of structure should I use for my shipping fee. I wanted to fix my shipping fee to a certain number may be 30$, but then when I want to change the number I can do that in the admin panel, and also for a certain threshold I want to give my customers free shipping. So what do you suggest friends? Should I have a separate class for shipping? or can I finish it in my Order class by adding one field? -
Why is my download button not working when i try to download an uploaded file
I am working on a Django project. I implemented an upload and download button. The upload button functions properly but when I click the download button it tells me that the file I want to download does not exist - 'no file'. this is the code. for views def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path,'rb') as fh: response = HttpResponse(fh.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 ``` for ```url``` ``` from django.urls import path from . import views from django.conf import settings from django.views.static import serve from django.urls import re_path from django.conf.urls.static import static app_name = 'projects' urlpatterns = [ path('', views.projects, name='projects'), path('new-project/', views.newProject, name='new-project'), path('new-task/', views.newTask, name='new-task'), re_path(r'^download/(?P<path>.*)$',serve, {'document_root':settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` for ```html``` ``` {% for project in projects %} <li class="my-2"> {% if project.status == '1' %} <span class="badge badge-danger" style="width: 50px;">Stuck</span> {% elif project.status == '2' %} <span class="badge badge-info" style="width: 50px;">Working</span> {% else %} <span class="badge badge-success" style="width: 50px;">Done!</span> {% endif %} <span class="title ml-1">{{ project }}</span> <span class="value"> <span class="text-muted small">deadline: </span>{{ project.dead_line }} <span class="text-muted small">({{ project.complete_per }}%)</span> <span> <a href="{{project.pdf.url}} download="{{project.pdf.url}}""><button type="button" class="btn btn-primary" style="margin-left:47px;">Download Project</button></a> </span> </span> <div class="bars"> … -
Django attribute error while creating superuser
I've created a custom user model using AbstractBaseUser. When I try to create a super user using terminal via createsuperuser command. I get in create_superuser user.is_staff = True AttributeError: can't set attribute Below is my code for creating custom user model. import uuid from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, AbstractUser, BaseUserManager ) class AdminUserManager(BaseUserManager): def create_user(self, email_id, password=None, *args, **kwargs): if not email_id: raise ValueError('User must have an Email ID') user = self.model(email_id=email_id) user.set_password(password) user.save(using = self._db) return user def create_staffuser(self, email_id, password, *args, **kwargs): user = self.create_user( email_id, password=password ) user.is_staff = True user.save(using = self._db) return user def create_superuser(self, email_id, password, *args, **kwargs): user = self.create_user( email_id, password=password ) user.is_staff = True user.is_superuser = True user.save(using = self._db) return user USER_ROLE = ( ('pilot', 'pilot'), ('admin', 'admin') ) class AdminUser(AbstractBaseUser): user_uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile_picture = models.ImageField(upload_to='user_profile_picture/', null=True, blank=True) user_role = models.CharField(max_length=10, choices=USER_ROLE) email_id = models.EmailField(verbose_name='Email ID', unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email_id' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): full_name = f'{self.first_name} {self.last_name}' return full_name def get_short_name(self): return self.first_name … -
Same queryset evaluation code, different field names in Django Views
I have seemingly redundant code in Django Views which evaluates the same query-set (Model.objects.all()) but with different field names: def overview_view(request): bacteria = Bacteria.objects.all() bacteria_count = bacteria.count() bacteriaFilter = BacteriaFilter(request.GET, queryset=bacteria) bacteria = bacteriaFilter.qs remaining = bacteria.count() glucose = [] not_glucose = [] pure_glucose = [] for bug in bacteria: if (bug.glucose_acid_from is not None) and (bug.glucose_acid_from != 'neg'): glucose.append(bug.species) for bug in bacteria: if (bug.glucose_use is not None) and (bug.glucose_use != 'neg'): glucose.append(bug.species) any_glucose = len(set(glucose)) for bug in bacteria: if (bug.glucose_use is not None) and (bug.glucose_use == 'neg') and (bug.glucose_acid_from is not None) and (bug.glucose_acid_from == 'neg'): not_glucose.append(bug.species) no_glucose = len(set(not_glucose)) for bug in bacteria: if (bug.glucose_use is not None) and (bug.glucose_use == '+'): pure_glucose.append(bug.species) for bug in bacteria: if (bug.glucose_acid_from is not None) and (bug.glucose_acid_from == '+'): pure_glucose.append(bug.species) mix_glucose = any_glucose - len(set(pure_glucose)) nonr_glucose = bacteria_count - any_glucose fructose = [] not_fructose = [] pure_fructose = [] for bug in bacteria: if (bug.fructose_acid_from is not None) and (bug.fructose_acid_from != 'neg'): fructose.append(bug.species) for bug in bacteria: if (bug.fructose_use is not None) and (bug.fructose_use != 'neg'): fructose.append(bug.species) any_fructose = len(set(fructose)) for bug in bacteria: if (bug.fructose_use is not None) and (bug.fructose_use == 'neg') and (bug.fructose_acid_from is not None) and … -
Behavior of Python subprocess on django+nginx
I have a simply code like: subprocess.run( ["python3", "action.py", "--options"] ) In action.py i import some packages, perform small script It works properly, when i launch it on built-in django-server, but when i add nginx-server as a wrapper, i get "ModuleNotFoundError: No module named 'modulename'". Why this error might occure exactly with nginx and how i can correct it? Launch with shell=True or venv="path/to/venv" don`t work for me -
custom size of field in crispy form django not working
i want to display a form to create posts. i use crispy-form and it currently displays: with html template: {% extends 'blog_app/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Post</legend> {{ form.media }} {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock %} i want to increase size of the title box and reduce size of the content box so that i fits the content section. what i tried: in template, display each field as crispy field with specified css class: {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="form-group col-md-8"> {{ form.title|as_crispy_field }} </div> <div class="form-group col-md-8"> {{ form.content|as_crispy_field }} </div> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock %} in form class, set helper and layout: class PostCreateForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.layout = Layout( Field('title', id="form-title", css_class="col-md-8", name="title"), Field('content', id="form-content", css_class="col-md-8", name="title")) in both ways, nothing changes. can someone give me a pointer? -
Calling FileField objects in template renders incorrect path
I've implemented a FileField model in my project. I can successfully upload svg files and they save to the desired location. Within my project, I make heavy use of user uploaded images (JPGs) and they save to the correct location and I can display them in my templates with no issue. However, when I upload an svg to the FileField and then attempt to display it within the template, the link is broken. The problem is that the correct file path isn't being set within the html Template <img src="{{ account.image }}" /> It should point to the following path: localhost:8000/media/Users/jimmy/file.svg But it resolves as the following, which is incorrrect: localhost:8000/profile/settingspage1/Users/jimmy/file.svg Essentially, I've I manually append '/media' to the filepath within the template, it works, but I shouldn't have to do this. The filepath should resolve correct. <img src="/media/{{ account.image }}" /> Any thoughts on what setting could be preventing only filefields from resolving to the correct path within my media folder? Thanks! -
django removes "is_staff" permission if I try to login
I have a pretty strange situation within my django project. I have a LoginForm where a user can log into the website. I am using django 3.2.12 with some other libraries like django-crispy-forms and so on. I implemented django-crowd-auth so that users can access the page with crowd. I made the neccessary configurations in settings.py and the app is running without any issues. Afterwards I gave my existing user is_staff and is_superuser permissions to access the django administration. I did it like this: python manage.py shell >>> from django.contrib.auth.models import User >>> user = User.objects.get(username="<myuser>") >>> user.is_staff = True >>> user.is_superuser = True >>> print(user.is_staff) True >>> print(user.is_superuser) True >>> save() After that I restart my django app the following way: sudo <path_to_conda_env_python>/python manage.py runsslserver --certificate <crt-file> --key <pem-file> 0.0.0.0:88 If I try to log into the django administration panel with the user which I just gave the permissions I get the error "Please enter the correct username and password for a staff account. Note that both fields may be case-senitive" Returning to the django shell gives me this output python manage.py shell >>> from django.contrib.auth.models import User >>> user = User.objects.get(username="<myuser>") >>> print(user.is_staff) False >>> print(user.is_superuser) False It seems … -
Getting Bad Gateway and Connection reset by peer using asyncio + aiohttp
Is there some async expert with sharp eyes around? I am using asyncio (Python 3.9) with aiohttp (v3.8.1) to fetch multiple urls asynchronously through a proxy, but this implementation seems to fail pretty often throwing reset by peer and Bad Gateway errors. The same proxy works well using Scrapy spiders so there must be something wrong with my async implementation. My code: from asgiref.sync import async_to_sync import asyncio import aiohttp async def async_fetch_url(session, url: str, method: str = "get"): async with getattr(session, method)(url, proxy="https://someproxy.com/") as response: return await response.json(content_type=None) async def my_async_fetch(urls: list, method: str = "get"): async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(force_close=True)) as session: return await asyncio.gather(*[async_fetch_url(session, url, method=method) for url in urls]) def my_sync_func(): urls = [ 'https://somesite.com/1', 'https://somesite.com/2' ] result = async_to_sync(my_async_fetch)(urls) Error logs: [2022-04-28 21:47:28,576: ERROR/MainProcess] ???[???]: [Errno 104] Connection reset by peer [2022-04-28 21:47:28,576: ERROR/MainProcess] ???[???]: Traceback (most recent call last): File "/app/cubist_backend/helpers.py", line 176, in async_fetch_url async with getattr(session, method)(url, **kwargs) as response: File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 1138, in __aenter__ self._resp = await self._coro File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 535, in _request conn = await self._connector.connect( File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 542, in connect proto = await self._create_connection(req, traces, timeout) File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 905, in _create_connection _, proto = await self._create_proxy_connection(req, traces, … -
Paginate Iteratively
How to do custom pagination. I need to read csv file by rows, and return only 10 rows in response with link on the next page. -
Install Django on Gandi instance
I try to install an Django app on Gandi, and... I suck at it. If someone can help me, thx :) ! For now, what I have is un file name wsgi.py : import sys import os import os.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'cms'))) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cms.settings') from django.core.wsgi import get_wsgi_application and an other name requirements.txt : django-cms When I do pip --version : pip 22.0.4 from /home/hosting-user/.local/lib/python3.9/site-packages/pip (python 3.9) When I do python3 --version : python 3.5.3 (I don't know why because I have a 3.9 write in my Gandi dashboard, maybe it's a part of the probleme) When I do django-admin startproject django_delights : bash: django-admin: command not found When I do python -m django startproject mysite : /usr/bin/python: No module named django (same with python3 When I do env : LC_ALL=C LD_LIBRARY_PATH=/opt/mysql-8.0/lib/x86_64-linux-gnu:/opt/mysql-8.0/lib/x86_64-linux-gnu LANG=C OLDPWD=/srv/data/web DB_VERSION=8.0 CUSTOMER_DIR=/srv/data container_ttys=/dev/pts/0 /dev/pts/1 /dev/pts/2 /dev/pts/3 SHELL_START=true MAX_MEM=256 DB_USER=hosting-db PREFIX=/ container=lxc LOCAL_DIR=/srv/run WWW_ENGINE=python PWD=/srv/data/web/vhosts/default HOME=/home/hosting-user SYS_USER=hosting-admin MYSQL_HOME=/srv/data/.config/mysql-8.0 TMPDIR=/srv/data/tmp PIP_LOG=/srv/data/var/log/www/pip.log DB_ENGINE=mysql PAAS=lamp0 PIP_BUILD_DIR=/srv/data/tmp/pip-build TERM=vt100 APP_USER=hosting-app0 PIP_SRC_DIR=/srv/data/tmp/pip-src PAAS_USER=hosting-user SHLVL=4 PYTHONPATH=/srv/data/web/vhosts/default/local/lib/python2.7 WWW_VERSION=3.9 NO_MOUNT=yes LOGROTATE_CONF=/srv/data/var/admin/logrotate.conf PHP_USER=hosting-user PATH=/usr/sbin:/usr/bin:/sbin/:/bin:/opt/python-3.9/bin:/opt/python-3.9/sbin:/opt/python-3.9/usr/bin:/opt/python-3.9/usr/sbin:/opt/mysql-8.0/bin:/opt/mysql-8.0/sbin:/opt/mysql-8.0/usr/bin:/opt/mysql-8.0/usr/sbin:/opt/sqlite-3/bin:/opt/python-3.9/bin:/opt/python-3.9/sbin:/opt/python-3.9/usr/bin:/opt/python-3.9/usr/sbin:/opt/mysql-8.0/bin:/opt/mysql-8.0/sbin:/opt/mysql-8.0/usr/bin:/opt/mysql-8.0/usr/sbin:/opt/sqlite-3/bin GITWEB_USER=hosting-user LD_PRELOAD= /usr/local/lib/gandi/gandi-preload.so DISTRIB=jessie _=/usr/bin/env Tell me if you need more infos :), thx again for your time. -
How to use multiple databases in Django with an empty 'default'?
I'm trying to make a multiple database project in Django. But I'm having problems to properly migrate my models to the appropriate database. I'm using the 'Writing your first Django app' tutorial as a starting point; so ... I've written the following database routers; this one for 'polls' app: class PollsRouter: route_app_labels = {'polls'} def db_for_read(self, model, **hint): if model._meta.app_label == 'polls': return 'Polls' return None def db_for_rite(self, model, **hint): if model._meta.app_label == 'polls': return 'Polls' return None def allow_relation(self, obj1, obj2, **hint): if ( obj1._meta.app_label == 'polls' or obj2._meta.app_label == 'polls' ): return True return None def allow_migrates(self, db, app_label, model_name=None, **hints): if app_label == 'polls': return db == 'Polls' return None Also the router class for 'devices' app: class DevicesRouter: route_app_labels = {'devices'} def db_for_read(self, model, **hint): if model._meta.app_label == 'devices': return 'CTS_ER_BD' return None def db_for_rite(self, model, **hint): if model._meta.app_label == 'devices': return 'CTS_ER_BD' return None def allow_relation(self, obj1, obj2, **hint): if ( obj1._meta.app_label == 'devices' or obj2._meta.app_label == 'devices' ): return True return None def allow_migrates(self, db, app_label, model_name=None, **hints): if app_label == 'devices': return db == 'CTS_ER_BD' return None And finally, the router class for 'auth_user' database (for native Django apps) class Auth_userRouter: route_app_labels = …