Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Framework forms
My problem is that user is registered in database but it is not logged in. only those users are able to logged in which are created from admin panel of django This is model view -
How to test a function which returns something and has side effect?
I have a function which returns something but has a side effect at the same time. Should I test only value which this function returns or I need to test result of a side effect too? @slack_interactions.on('admin_add') def handle_admin_add(payload): team_id = payload['team']['id'] user_id = payload['user']['id'] action_value = payload['actions'][0]['selected_options'][0]['value'] user = SlackUser.objects.find_by_ids(team_id, action_value) if user and not user.is_bot: user.make_admin() return build_admins_message(team_id, user_id) -
Django templating. get titel of category
i'm currently trying to figure out how i can display the categories title in my template. Im trying to implement a filter view and this is the last step needed. currently i get the following output Latest Post's in <QuerySet [<Category: testcategory>]> template.html <h1 class="center">Latest Post's in {{ categories }}</h1> < right here!!! {% for post in posts %} <div class="post"> <h3><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h3> <p>{{ post.content|safe|slice:":1000"|linebreaksbr}} {% if post.content|length > 500 %} <a href="{% url 'post_detail' pk=post.pk %}">... more</a> {% endif %}</p> <div class="date"> <a>Published by: <a href="{% url 'profile' pk=post.author.pk %}">{{ post.author }}</a></a><br> <a>Published at: {{ post.published_date }}</a><br> <a>Category: <a href="{% url 'category_by' pk=post.category.pk %}">{{ post.category }}</a></a><br> <a>Tag(s): {{ post.tag }}</a><br> <a>Comment(s): {{ post.comment_set.count }}</a> </div> </div> {% endfor %} views.py def category_show(request, pk): list_posts = Post.objects.get_queryset().filter(category_id=pk).order_by('-pk') paginator = Paginator(list_posts, 10) # Show 10 Posts per page page = request.GET.get('page') posts = paginator.get_page(page) categories = Category.objects.all() return render(request, 'myproject/post_list_by_category.html', {'posts': posts, 'categories': categories}) -
Display Dropdown Search Django
i am display list of users. Now i want a search dropdown list which will display the companies and according to those companies list of users will be displayed. Please provide me a way to do search and list users and the same time. i am sharing a image with you people. Thanks in advance. class UserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'users/users.html' def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) context['users'] = User.objects.exclude(userprofile__user_role__role_title='Super Admin') # Pass Form to display inside search box return context -
Is it bad practice to store a timer object in a database and also have the program continuously query in Django?
I am a beginner in Django and Python in general and have been practicing by making a browser-based multiplayer game. In the game, registered players can "attack" other players. Once a player has "attacked" a player he must wait 30 minutes before his ability to 'attack' again is reset. I have an idea of implementing this but am not sure if my approach is bad practice: I thought about adding a "TimeToReset" field in the database to each registered user and fill that field with a timer object. Once a player 'attacks' his 'TimeToReset' field starts counting down from 30 minutes to 0. and then have the application continuously query all the users in the database with a while True loop, looking for users that their "TimeToReset" reached 0. And then run code to reset their ability to 'attack' again. I am not sure how efficient my approach or if it is even possible is and would love some input. So to summarize: 1)Is it ok to store a timer/stopwatch object(which continuously changes) in a database? 2)Is it efficient to continuously run a while true loop to query the database? Or if is there a better approach to implement this … -
unable to run django project under apache server
I have created one virtual environment in /var/www/python3 using pipenv and then created django project and installed all dependencies my Pipfile is: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==2.1.4" django-rest-swagger = "*" mysqlclient = "*" django-cors-headers = "*" pillow = "*" djangorestframework = "*" django-extra-fields = "*" djangorestframework-xml = "*" django-filter = "*" [requires] python_version = "3.6" my wsgi.py file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "image_management.settings") application = get_wsgi_application() my urls.py is: from django.contrib import admin from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from image_app import views as image_view from django.urls import path, include from rest_framework import routers from django.conf.urls.static import static from django.conf import settings from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') router = routers.DefaultRouter() router.register(r'images', image_view.ImageViewSet) router.register(r'albums', image_view.AlbumViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^swagger/$', schema_view) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I have ran my apache using : sudo service apache2 restart when i try to access the admin page in django using http://10.75.12.254/admin/ I am getting the followinf error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them … -
Pytest Django with override_settings ignored
The override of Django settings in my Pytest test method does not seem to work. My test method is as follows: @pytest.mark.django_db def test_ip_range(rf, custom_fixture): with override_settings(IP_RANGE = [IPNetwork('1.0.0.0/8')]): request = rf.get('/') request.user = UserFactory() response = custom_fixture.process_request(request) assert isinstance(response, HttpResponseForbidden) However, while debugging the process_request method I noticed that IP_RANGE in settings is just the default, nothing is overridden. I also tried the settings fixture as a parameter, with the same results. What am I missing? -
Django POST request always empty but it is not
I'm a noob with Django. I try to display the content of a POST request but I don't succeed. I'm using POSTMAN to produce POST request. This is my view in Django : @csrf_exempt def prem(request): if request.method == 'GET': print("GET") context = {'contenu': request.GET.get("name") } # do_something() elif request.method == 'POST': for i in request.POST: print(i) datar = request.POST.get('mykey','rien') context = { 'contenu' : datar } return render(request, 'polls/seco.html', context) When I click on POST in POSTMAN, this is what my shell display : So, my web app receive the POST request, but I cannot get its content. This my template : {% if contenu %} {% csrf_token %} <p>{{ contenu }}</p> <p>Contenu detecté.</p> {% endif %} This is what POSTMAN display : If someone could help me it would be really great ! :) -
How to access post from username only?
I am writing models and i want to access post from username directly in django views. Is it possible? the models.py file is as follows:- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone #this is how profile of a sample user, say MAX looks like class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username -
Django on Debian 9 - ImportError: No module named 'PROJECT.settings.py'
I'm trying to deploy my Django app on Google compute engine Debian VM instance, I have installed the Python(3.6) and setup virtual environment then clone my Django application which is working perfectly well on the local system. When I try to run python manage.py migrate command it returns an error as: ImportError: No module named 'Fetchors.settings.py'; 'Fetchors.settings' is not a package Here's my Fetchors/wsgi.py: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(path) if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Fetchors.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) What can be wrong here? Thanks in advance! -
How to chain annotation in Django ORM?
I have a table like this a | b | c | sample_type | value 1 2 3 xx 0 1 34 45 yy 1 1 2 3 xx 1 Now I want to find the unique row count(unique based on the values combined by column a, b, c), sum('values) group by sample_type in Django ORM. So far I have tried this values('sample_type', 'a', 'b', 'c'). \ annotate(positive_temp=Sum('values'), total_temp=Count('a')). \ values(name=F('sample_type'), pos=F('values'), tot=F('total_temp')). \ annotate(positive=Sum('pos'), total=Sum('tot')) but on the last annotate it throws error can not do sum on aggregated values -
Handle ajax request with Django LoginRequiredMixin after session timeout
This situation was covered in other posts, but in most cases solutions are outdated and apply only to function-based views. My problem is simple: Right now my app enforces session timeouts on Django site with this parameters: SESSION_SAVE_EVERY_REQUEST = True SESSION_COOKIE_AGE = 600 And most of views utilize LoginrequiredMixin. It works fine, but with the AJAX it obviously won't work. The common solution found over internet is changing the behaviour of authentication controll to return 403. Is it possible to super the LoginRequiredMixin to do so for ajax requests? Or maybe just giveup and do this fully with javascript, on client side? -
I want to fetch the html content loaded from url in iframe and want to display it in another iframe in Django?
<div class="box"> <iframe src="https://api.cloudconvert.com/convert/" enctype="multipart/form-data" frameborder="2" name="frame1" scrolling="yes" width="600" height="712" align="right" > </iframe> <form method="POST" action="https://api.cloudconvert.com/convert/" enctype="multipart/form-data" target="frame1"> <input type="file" name="file"> <input type="hidden" name="apikey" value="EwzmwYg9LNggAcJdCfg0i5kPQqVSZPMnsYZw1KczeWJTuBlsT0uceQmKBllQppoA"> <input type="hidden" name="inputformat" value="pdf"> <input type="hidden" name="outputformat" value="html"> <input type="hidden" name="input" value="upload"> <input type="hidden" name="timeout" value="10"> <input type="hidden" name="wait" value="true"> <input type="hidden" name="download" value="inline"> <input type="hidden" name="save" value="true"> <input type="submit" value="Convert!"> </form> </div> The above is my html code to load the content of my iframe. def pdf_html(request): tag = [] try: html = open("/home/sevenbits/pro/project/myproject/templates/pdf_html/iframe.html") except HTTPError as e: print(e) except URLError: print("Server down or incorrect domain") else: res = BeautifulSoup(html.read(), "html5lib") tag = res.find('iframe') src = tag['src','enctype'] #URl of iframe ready for scraping return render(request,'pdf_html/iframe.html') This is my view to display the content of the html page. I want to simply take code of html page loaded in the iframe and display it to my another iframe and I'm using the beautifulsoup library. -
Django google maps error 'This page can't load Google Maps correctly.'
Im using django_google_maps app in my django project . I added GOOGLE_MAPS_API_KEY in my settings.py. here is my user model: class UserData(AbstractBaseUser): first_name = models.TextField(null=False) last_name = models.TextField(null=False) email = models.EmailField(null=False, unique=True) id_code = models.CharField(null=False, max_length=11) profile_picture = models.ImageField(null=True, blank=True) rank = models.IntegerField(default=0) # here is google map fields address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100) And already added this code in my ModelAdmin class formfield_overrides = { map_fields.AddressField: { 'widget': map_widgets.GoogleMapsAddressWidget(attrs={'data-map-type': 'roadmap'})}, } But when i want to add user in admin panel this error occurs in map section From google : This page can't load Google Maps correctly. Do you own this website? Anyone can help ? -
How to Display Topic by User Subscription to Topic Category
I'm new to Django Python framework. i have the Topic model, SubChannel model, SubChannelSubscription model. i want to display the Topics according to what the user subscribed to. For example, If a User subscribed to Physics category only, the User should only see Physics Topics Python 3 and Django 2 class SubChannelSubscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriptions', verbose_name='Subscriber', default=True) category = models.ForeignKey(SubChannel, related_name='Topic+', on_delete=models.CASCADE, verbose_name='SubChannel', default=True) def __str__(self): return '%(user)s\'s subscription to "%(category)s"' % {'user': self.user, 'category': self.category} class Meta(object): verbose_name = 'Subscription to SubChannel' verbose_name_plural = 'Subscriptions to SubChannel' class Topic(models.Model): by = models.ForeignKey(User, on_delete=models.CASCADE, default=True) subject = models.CharField(max_length=150, unique=True, null=True) date_created = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(SubChannel, on_delete=models.CASCADE, null=True, default=True, related_name='topics') file = RichTextUploadingField(blank=True, null=True) def __str__(self): return self.subject def get_absolute_url(self): return reverse('Topic_detail', kwargs={'pk': self.pk}) I have my Views.py code for User Subscription shown below class SubChannelSubscriptionView(ListView): template_name = 'subscription.html' model = Topic def get_queryset(self): self.user = get_object_or_404(User, pk=self.kwargs['pk']) return SubChannelSubscription.objects.filter(user=self.user) def get_context_data(self, **kwargs): context = super(SubChannelSubscriptionView, self).get_context_data(**kwargs) context['topics'] = self.user context['top'] = Topic.objects.filter(category=1) return context my urls.py path('subscription/<int:pk>', SubChannelSubscriptionView.as_view(), name='subscription'), -
Unable to Redirect to homepage after login in Django
hay i'm new to django framework, i got issue that i can not solved. It is when i tried to redirect the admin to admin custom homepage using LOGIN_REDIRECT_URL, i set it to /profile, but instead go to homepage it raised "Page not found (404)" here's my root url file urlpatterns = [ path('admin/', admin.site.urls), path('', include('front_page.urls')), path('accounts/login',views.LoginView.as_view(),name='login'), path('accounts/logout/', views.logout, name='logout', kwargs={'next_page': '/'}), path('profile/', include('admin_page.urls')), ] admin apps url app_name = "admin" urlpatterns = [ path('home/', views.index, name='admin_index'), path('berita/', views.BeritaList.as_view(), name='all_berita'), ] setting.py LOGIN_REDIRECT_URL = '/profile' homepage file <div class="jumbotron"> <div class="container"> <h1>Hello, admin</h1> <p>Selamat di halaman utama administrator,silahkan menekan tombol dibawah untuk menginput Peta atau berita</p> <p><a class="btn btn-primary btn-lg" href="{% url 'admin:all_berita' %}" role="button">Berita</a> <a class="btn btn-primary btn-lg" href="" role="button">Peta</a></p> </div> </div> i got confused because it happen only when i try to redirect admin after login, can someone help me solve it, thank you -
Django templates. I get in my mail parameters, how can I send them to another html with include?
This is my welcome container: <tr> <td align="center"> <!-- Start internal container --> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td height="30" style="line-height:30px; font-size:30px;">&nbsp;</td> </tr> <tr> <td align="left" style="font-family: 'Lato', sans-serif; font-size:20px; line-height:26px;"> <p style="font-family: 'Lato', sans-serif; margin: 0; padding: 15px 60px 15px 60px; font-weight: bold; color: #333333;"> {{ title }} </p> <p style="font-family: 'Lato', sans-serif; font-size:16px; margin: 0; padding: 0px 60px 0px 60px; color: #333333;"> {{ subtitle }} </p> </td> </tr> </table> <!-- End internal container --> </td> I tried this: {% "Hi {{first_name}}" as titleStr%} {% with title=titleStr subtitle="Please confirm your email address by clicking this button." %} {% include "emails/_parts/welcome_container.html" %} {% endwith %} But I get this issue: Invalid block tag on line 29: '"Hi', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong? Line 29 is the one with title=titleStr -
Dealing with Many models and relations in Django Rest Framework
I am working on building an API backend full of many models and relations among them. I am confused between three options: - Using Django Rest Framework: It will be useful as a specialized framework to build an API, but it becomes very complex while: dealing with many models and relations. customizing the queries itself (for example: if I want to use select_related attribute to query on a one to many field instead of leaving it to DRF). Serializing many models together and in different situations like ListView, DetailsView, ..etc. However, I see that this package could be useful: https://github.com/MattBroach/DjangoRestMultipleModels I think it will be overhead on the application itself and it will be slower (I am not sure). the hierarchy that it use, more and more complexity. So, finally I see that it is restricted when it comes to deep customization. However, it provides many features to be used directly instead of inventing the wheel. - Using pure Django: This will make it more flexible to build my application and I can use the django.core.serializers.serialize to serialize my data like: Django or Django Rest Framework, I can also use the pyjwt and others. I know that the disadvantage of … -
Django 2.0: Url path to homepage/index
I'm trying to set my django homepage, linked to the root of my website: i.e. http://127.0.0.1:8000/index/ but instead, I keep getting errors where Django is searching for myapp as the homepage: http://127.0.0.1:8000/myapp/. I would just like to land on a homepage with "index" in the url instead of "myapp/" The error is as follows: Using the URLconf defined in Main.urls, Django tried these URL patterns, in this order: admin/ [name='index'] [name='myapp_index'] publications/ [name='publications'] ^static\/(?P<path>.*)$ The current path, myapp/, didn't match any of these. Views.py def index(request): return render(request, 'index.html') Main/urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) myapp/urls from django.urls import path from logbook import views urlpatterns = [ path('', views.index, name='index'), path('', views.myapp_index, name='myapp_index'), path('publications/', views.publications, name='publications'), ] Now, if I change the path in Main/urls.py to path('myapp/', include('myapp.urls')), I land on the appropriate homepage, except, I would prefer that there is "index/" listed in the URL instead of "myapp/". I may be missing something very simple here. This is what I think is my MWE, happy to add more. -
Strategy to measure memory usage for Django queryset
I want to measure how much memory Django queryset use. For example, I try the simple way. import psutil process = psutil.Process(os.getpid()) s = process.memory_info().rss # in bytes for i in queryset: pass e = process.memory_info().rss # in bytes print('queryset memory: %s' % (e-s)) Since iterating queryset, Django will hit a database and the result will be cached and by getting memory usage for the Python process, I try to measure queryset memory usage. I wonder if the access would be right or there is any way to measure my goal, you guys know. This measure is to predict if there would be any issue when trying to get a massive query result and if there is, from how many rows result in an issue. I know If I want to avoid caching queryset result, I can use iterator(). However, iterator() also should determine chunk_size parameter to reduce the number of hitting database and memory usage will be different depending on chunk_size. import psutil process = psutil.Process(os.getpid()) s = process.memory_info().rss # in bytes for i in queryset.iterator(chunk_size=10000): pass e = process.memory_info().rss # in bytes print('queryset memory: %s' % (e-s)) -
Django - unable to open database file
It gives 500 error (more precisely “unable to open database file”) when I go to the admin panel. + In the logs, nginx writes that it cannot find .css files, although they are in place. You can see the debugging at https://testeuppi98.ddns.net - root:root -
Pass Variable from View to Form Django
Basically i am sending email to user with password and username. I can get the username using self.cleaned_data.get('email'). But the problem is that i dont know how to get password from view which i am setting random password in views. So please help me to get that random password from views.py to forms.py in def send_email Forms.py class UserRegisterForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['first_name','last_name', 'email'] def send_email(self): name = self.cleaned_data.get('first_name') username = self.cleaned_data.get('email') to_email = self.cleaned_data.get('email') password1 = # Get Password from view Views.py def register(request): if request.method == 'POST': ur_form = UserRegisterForm(request.POST) pr_form = UserProfileForm(request.POST, request.FILES) user_role = 0 if ur_form.is_valid() and pr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email password = User.objects.make_random_password() # Pass This to Form send_email new_user.set_password(password) new_user.save() -
Django DateTimeField is not editable
I have a blog and I post many articles. Each article has a date of publication, and sometimes I have to edit this date. Everything running on the Django admin panel and I never encountered any 500 error since I decided to add the DateTimeField in my admin.py. The issue is, Django cannot edit the DateTimeField and it returns : Internal Server Error: /admin/wall/articles/62/change/ FieldError at /admin/wall/articles/62/change/ 'date' cannot be specified for Articles model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class ArticlesAdmin. I don't understand why it doesn't work. Models : class Articles(models.Model): title = models.CharField(max_length=100, null=False, verbose_name="Titre") description = models.TextField(max_length=500, null=False, verbose_name="Description pour les partages sur les réseaux sociaux") subtitle = models.TextField(max_length=300, null=True, verbose_name="Sous-titre") text = RichTextUploadingField() tag = models.ManyToManyField(Tag, verbose_name="Tag") subcategory = models.ForeignKey(SubCategory, verbose_name="Sous-catégorie", blank=True, null=True) image = models.FileField(upload_to='media/articles/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Image de présentation") image_description = models.CharField(max_length=100, null=True, verbose_name="Description pour cette image") image_legende = models.CharField(max_length=100, null=True, verbose_name="Légende pour cette images") author = models.ForeignKey(User, verbose_name="Auteur") published = models.BooleanField(default=True, verbose_name="Publié") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") def get_absolute_url(self): return reverse('read', kwargs={'post':self.id, 'slug':slugify(self.title)}) def __str__(self): return self.title admin.py class ArticlesAdmin(admin.ModelAdmin): list_display = ('date', 'title', 'author', 'published', 'update') fieldsets = … -
How to handle async task with Django atomic transactions creating db entries
My system receives payload from another source. This payload contains items information, including brand and such. I save this payload inside a buffer. Buffers are processed async with Celery tasks. Based on the payload we create the entries or update them if necessary. This is done by using an atomic transaction, in which we create the Item, the Brand and Category. The issue I am running into is that it can be possible that two buffers both have an Brand which is not yet created in the db. Using update_or_create inside the atomic block I check whether it already exists. Since both buffers are ran async at almost exactly the same time both think the Brand does not yet exists. This means both of them try to create the Brand yielding me the following database error: postgres_1 | ERROR: duplicate key value violates unique constraint "catalogue_brand_name_key" postgres_1 | DETAIL: Key (name)=(Bic) already exists. postgres_1 | STATEMENT: INSERT INTO "catalogue_brand" ("id", "created_date", "modified_date", "name") VALUES ('c8e9f328-cee7-4b9b-ba45-268180c723d8'::uuid, '2018-12-28T08:08:51.519672+00:00'::timestamptz, '2018-12-28T08:08:51.519691+00:00'::timestamptz, 'Bic') Since this is a db-level exception I am unable to catch it inside my code and the buffer will be marked as completed (since no exception inside the code was given). The … -
As you see, when I try to pull the api of a web page, I catch a bug
Because of some demand functions, I try to call the interface once a minute, but different devices will trigger the same bug at different times. I try to solve it, but I can't do anything about it.thanks! code: class ActorCloudAlertsNumberView(ListAPIView): """ get: """ def get(self, request, *args, **kwargs): try: last_time = request.GET['time'] except Exception: raise Error(errors.INVALID, 'xxxx', 'xxxx') page = '1' page_size = '100' ac_client = acc.ActorCloudClient.get_instance() # headers = {"Connection": "close", } # ac_result = ac_client.get(acc.AC_ALERTS_GET_URL.format(page=page, page_size=page_size), headers=headers) ac_result = ac_client.get(acc.AC_ALERTS_GET_URL.format(page=page, page_size=page_size)) if str(last_time) == 'null': full_number = ac_result.get('meta')['count'] return Response({'number': full_number}, status=status.HTTP_200_OK) try: last_time = datetime.strptime(last_time, '%Y-%m-%d|%H:%M:%S') except ValueError: raise Error(errors.PARSE_ERROR, 'xxxx', 'xxxx') ac_alerts_num = 0 for ac_alert in ac_result.get('items'): alert_time = ac_alert.get('startTime') alert_time = datetime.strptime(alert_time, '%Y-%m-%d %H:%M:%S') if last_time <= alert_time: ac_alerts_num += 1 else: break return Response({'number': ac_alerts_num}, status=status.HTTP_200_OK) error stack: ConnectionError at /api/v1/alerts/number HTTPConnectionPool(host='emqx.in.chinaopen.ai', port=80): Max retries exceeded with url: /api/v1/current_alerts?_page=1&_limit=100 (Caused by NewConnectionError(': Failed to establish a new connection: [Errno -3] Try again',)) Request Method: GET Request URL: http://xxxxx.ai/api/v1/alerts/number?time=null Django Version: 2.1.2 Python Executable: /usr/local/bin/python Python Version: 3.6.6 Python Path: ['/code/src/apps', '/code/src', '/usr/local/bin', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/code/src']