Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Paginatation based on multiple filters and rules on multiple fields
I'm working with a specific algorithm (not entirely math based) with djangorestframework (DRF) pagination. I want to use CursorPagination but the ordering is based on some set of rules spanning across different attributes. Here are some examples: Filter based on a DurationField of 30 minutes or less Filter based on a DurationField of 1 hour or less AND some table attribute that is some arbitrary integer of 10 or more Filter based on a DurationField of 2 hours or less AND the id (AutoField) must be greater than 30. Those were completely made up example of course, but the general gist is to paginate. If rule one only returns 20 out of the max 50 results, then apply rule 2 (then rule 3 if it still doesn't fill up to 50 items). I'd like to use CursorPagination since there are records that are continuously created. -
Django Cart not given me the right total price
I'm building a shopping cart to sell prints. At this point there are two sizes of prints with two different prices. On the form I implemented a field print_size. When I buy the first print is fine, but if I buy the same print with a different size the total price is just multiply from the first one. Any help is appreciated. from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 26)] PRODUCT_PRINT_CHOICES =( ("1", "8x12 inches"), ("2", "12x18 inches"), ) class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) print_size = forms.TypedChoiceField(choices=PRODUCT_PRINT_CHOICES, coerce=int) views.py @require_POST def cart_add(request, product_id): cart = Cart(request) # create a new cart object passing it the request object product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data pt = form.cleaned_data.get('print_size', None) if pt == 2: product.price = 45.00 if pt == 1: product.price = 25.00 cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not … -
Django saves empty formset values
I have a simple formset with some logic and I got a problem trying to save it. It doesn't matter how many forms I got in formset. After clicking "save" button in my template, Django saves a single empty form in database instead of saving all forms in formset with values. So here is my form (with some logic in init method): def catch_prefix(field_name, fields): """Returns current field_name prefix from form.data""" for field in fields.keys(): if field_name[-len(field):] == field: prefix = field_name[:-len(field)] return prefix class SignCreateForm(ModelForm): data_url = '/sign-form-data/' class Meta: model = SignModel fields = ['country', 'region', 'area', 'quality_mark', 'sign'] dependencies = {'quality_mark': ('country', 'region', 'area'), 'area': ('country', 'region'), 'region': ('country',)} class Media: js = ('js/formset.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) attrs_dict = {'onchange': 'addForm(this)', 'class': 'form-control', 'data-url': self.data_url} for field_name, field in self.fields.items(): self.fields[field_name].widget.attrs.update(attrs_dict) if self.is_bound: prefix = catch_prefix(self.data['field_name'], self.fields) self.prefix = prefix[:-1] for key, value in self.dependencies.items(): for item in value: if self.data[prefix+item]: self.fields[key].limit_choices_to = {item: self.data[self.prefix+'-'+item]} apply_limit_choices_to_to_formfield(self.fields[key]) views: class ViewJS(FormView): """Class for AJAX form transmitting. form.errors.clear() is needed because form sends to server every time the user changes any field and empty fields may not be allowed by form model. So form.errors.clear() helps JS to … -
(again) How to translate only custom error messages in DRF?
Please! Help me! I asked it few times on several services, and I got absolutely no answers. In DRF all default error messages are already translated. But I need to translate my own error messages. What I did: Put all my error messages into _(), where _ is gettext In settings set LOCALE_PATHS to locale folder Ran python manage.py makemessages -l ru That created .po file and here goes the first trouble. In the .po file are my messages and besides that there are a lot of default Django messages which I don't want to translate. (I do not want to override the translation, I want to extend it) I translated my messages in the .po file, then I ran python manage.py compilemessages which created .mo file. And here is the second trouble. All my messages are now translated, but default DRF messages (they were not in the .po file, there were Django messages, not DRF) are not already translated, they are only in English (e.g. Authentication credentials were not provided, This field is required, etc.) -
Query a table using ORM without models.py
There are about a dozen tables that are automatically created every quarter based on the data that we aggregate, so making a models.py doesn't make a lot of sense. (Normalizing the tables does, as does reworking the process to insert into an existing normalized table, instead of creating a new table every time, but I digress...) At any rate, I think I know the answer to this, but is there a way to use the ORM and refer to these tables without declaring them in the models.py? I have a feeling there isn't, but want to confirm really the only option in this case is to write queries in raw SQL. -
Django Google Login with React Frontend
This question may be super simple but I've been googling for a while now and haven't found an exact solution. I'm trying to implement a Google Login using React for the frontend and Django for the backend. How exactly would I do this? I have seen solutions where a token is sent over to the backend which then retrieves the necessary information from the Google API and either creates or retrieves a user from the database based on the token. However, this seemed to be based on JWT and I was wondering if it is possible to implement the same with the simple Django Auth Token? Maybe I'm just really blind but I really wasn't able to find a suitable solution. Thanks for your help! -
Codecov only runs tests listed last in .travis.yml
I am using Travis CI and Codecov with my Django project, and using the coverage package to generate coverage reports. The project has two apps, app1 and app2, each with their own tests.py. My .travis.yml currently looks like this: language: python python: - "3.6" install: - pip install -r requirements.txt script: - coverage run manage.py test app1 - coverage run manage.py test app2 after_success: - bash <(curl -s https://codecov.io/bash) When executing either coverage run manage.py test account or coverage run manage.py test main from the console, all tests pass. However, when I push to github and codecov runs the tests, it only runs the last command For example, when the script block looks like this: script: - coverage run manage.py test app1 - coverage run manage.py test app2 both the app1 and the app2 tests are run (as shown in Travis CI), but none of the the app1 tests are included in the coverage report, and when is looks like this: script: - coverage run manage.py test app2 - coverage run manage.py test app1 the opposite is true. Like I said, both tests are shown to be executed in Travis CI, so why is only one of them getting included … -
How can i append two classes in JQuery
I have implemented a chat box message (live chat) using django and now i want to add css, but i have problem on how to append multiple classes on messege sent. For example, i want to show other user messages float left and current user messages float right. But when i submit messages is displays only on float right, because i am only appending one class to messege sent. I think this is because i am only appending class="message-list me", when i change class="message-list" this display all message to the left. How do i float each message to left and right? This is what i got: haha should float to right (flex-start), while pepe should float to left (flex-end). I want something like this: Template: <div class="message-wrap" id='chat-items'> {% for chat in object.chatmessage_set.all %} <div class="message-list"> {% if request.user != chat.user %} <div class="msg"> <p> {{ chat.message }} </p> </div> <div class="time">{{ chat.timestamp }}</div> {% endif %} </div> <div class="message-list me"> {% if request.user == chat.user %} <div class="msg"> <p> {{ chat.message }} </p> </div> <div class="time">{{ chat.timestamp }}</div> {% endif %} </div> {% endfor %} </div> CSS: .message-wrap .message-list { align-self: flex-start; #float start max-width: 70%; } .message-wrap .message-list.me … -
How do I connect a React registration form with Django for backend without the REST API?
I know this sounds dumb, but is it possible to not separate React and Django but instead have them blended together with having to use the REST API? -
Launching a Django/Angular project for production
I have created a web app that uses Django(Backend) and Angular(Frontend). I want to launch this web app in a production environment. I am not looking to use (AWS or any other services), I want to create my own server and run it from my second computer. I don't have much knowledge of creating and managing a server so any advice (tutorials)would help! -
How to receive json field in Django Rest Framework which I don't want to store?
I'm building an api with Django Rest Framework for the following json: { "x_id": 123, "message_type": "count", "aggregate": [{"id": 1, "count": 3}], } The json objects in the aggregate can be of two different types, which is dependent on the message_type. So if message_type equals count the objects in the aggregate array look like above, and if the message_type equals person then the object in the aggregate array are completely different. I've got two separate models for the two different types of aggregates and I want to store them in those tables depending on the message_type. But since message_type is not part of any model it isn't validated and I can't use it in the serializers create() method: class ObservationSerializer(serializers.ModelSerializer): class Meta: model = Observation fields = ['x_id'] def create(self, validated_data): print("message_type" in validated_data) # => prints "False" return Observation.objects.create(**validated_data) Does anybody know how I can make the field message_type required, just so that I can use it to decide in which table I want to store the aggregate? -
Uploading excel document to React and storing in database
I am working on a project where I would like users to be able to upload an excel file through my react frontend. I need the uploaded document's data to be stored in a database so I can access it for different graphs and for an algorithm to change the data amounts. I am using PostgreSQL, React, Django, restful apis, and PostgreSQL. Any info on how to do this would be great. Thanks. -
Create validation error with two possible conditions
I can create a if not statement with one condition. This works - if not "ABC124" in voucher: raise forms.ValidationError("Invalid Voucher") return voucher And this works - if not "ABC124" in voucher: raise forms.ValidationError("Invalid Voucher") return voucher But this doesn't work - if not "ABC124" in voucher or if not "ABC123" in voucher: raise forms.ValidationError("Invalid Voucher") return voucher And this doesn't work - if not "ABC124" in voucher or not "ABC123" in voucher : raise forms.ValidationError("Invalid Voucher") return voucher How do I make an if statement with two conditions? -
Getting data from multiple containers into a single container in Django docker
I want to work on a django project in which specific data from different containers gets uploaded and updated to a single container. Is this possible? If so, can i get any leads? -
Django Improperly Configured for View (Login)
I'm working on setting up an auth for a Django project, I created an app called users to handle all auth related operations, profiles, etc I created a templates folder inside users app folder, inside there is two HTML files called : standard_signup.html and login.html . Here are urls.py files for the full site and the users app: urls.py - Full django site (the django project): from django.conf.urls import include from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path("accounts/",include("users.urls")), ] urls.py - users app: from django.urls import path from . import views urlpatterns = [ path("signup/user/",views.StandardSignUp.as_view(),name="signup"), path("join/",views.LoginPage.as_view(),name="login-page") ] All the view classes for users are obviously defined in views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.urls import reverse_lazy from django.views.generic import CreateView # Create your views here. class StandardSignUp(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'standard_signup.html' class LoginPage(CreateView): template_name = "login.html" Signup works well, when I go to /accounts/signup/users/ I get the signup html template. But when I go to accounts/join/ I get this error : ImproperlyConfigured at /accounts/join/ LoginPage is missing a QuerySet. Define LoginPage.model, LoginPage.queryset, or override LoginPage.get_queryset(). I can't find a workaround online for this error … -
NOT NULL constraint failed:
i'm creating a User registration form with the AbstractBaseUser, i have got to the point where when i press "Create" on my page it should save the fields to the Database however, i keep getting the following error message: Traceback (most recent call last): File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dylan\myblogsite\account\views.py", line 11, in registration_view form.save() File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\forms.py", line 137, in save user.save() File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\base_user.py", line 66, in save super().save(*args, **kwargs) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 782, in save_base updated = self._save_table( File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 924, in _do_insert return manager._insert( File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1392, in execute_sql cursor.execute(sql, params) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) … -
In Django update-view instance is not pre-filled in the form
Update-form is not filled in with the instance of the object (when I press the URL provided below, I get to the needed page, but the fields are empty, if enter the same url again - it works). What could be the least obvious reason for it? It happened in all browsers both locally and on a server. Check the code: Model: class ExpenseName(Time): name = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE) budget_default = models.IntegerField(null=True, blank=True) Backend: @login_required def update_expense(request, id): item = ExpenseName.objects.get(id=id) if item.user == request.user: if request.method == 'POST': form = NewFieldForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('home') else: form = NewFieldForm(instance=item) else: raise Http404('You are not allowed to see this') context = { 'form': form } return render(request, 'expenses/update.html', context) URL: path('<int:id>/update/', update_expense, name='update-field'), Frontend: {% extends 'expenses/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row h-100 align-items-center justify-content-center"> <div class="col-6 text-center" style="height:250px; width: 100px; padding-top: 30px; background-color: #4db8ff; border-radius: 10px;"> <form method="POST"> {% csrf_token %} Name of the expense:<div>{{ form.name }}</div> Budget: <div>{{ form.budget_default }}</div> <div><button class="btn btn-sm btn-dark mt-2 text-center" type="submit">Update</button></div> <a class="text-dark" style="font-size: 13px;" href="{% url 'home' %}">Cancel</a> </form> </div> </div> {% endblock content %} I really do hope someone can … -
How can I exclude the user who has once used the coupon for a previous order?
Hello guys I need to exclude a user who has once used the coupon, that is to restrict the use of coupon to 1 per person. here are my codes, it isn't working. I tried this way, but it doesn't work it seems. views. coupon = Coupon.objects.filter(code__exact=code, valid_from__lte=now, valid_to__gte=now,).exclude(order__user=self.request.user, max_value__lte=F('used')).first() models class Coupon(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) code = models.CharField(max_length=20) valid_from = models.DateTimeField() valid_to = models.DateTimeField() max_value = models.IntegerField(validators=[MaxValueValidator(100)], verbose_name='Coupon Quantity', null=True) used = models.IntegerField(default=0) Thanks -
How to model django apps
i'm building a web app customer ticketing system using Django. i'm stuck and drawing blanks. accounts would create client, send email to sign up, and update tickets that clients create. clients would login and be able to create a ticket and view already created tickets. wondering if i should create my models all in app or so i create separate apps like accounts app, ticket app and client app. I've tried searching on google but unable to find a specific answer to my question. any help would be appreciated as i'm new to database modeling. -
element of object_list in script section of django template
my view returns the object_list to the template. I apply a for loop to this list and everything works fine. But when I write some Javascript inside script tags just below a button and try to get {{ post.pk }} inside script tags, it returns the pk of the last element in object_list. For example: if it is the first iteration and when above script tags I try to get {{ post.pk }}, it returns the pk of the current element of object_list. But when I try to do the same thing between script tags, it returns the pk of the last element of object_list. What is the reason and is there any solution? Thanks in advance -
How to render javascript in django
This javascript file refuses to run I already create a class with update-class as name in the main.html folder but when I run the site and click on the button the javascript action does not display at the console.... var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action); console.log('USER:', user) if (user == 'AnonymousUser'){ console.log('User is not authenticated') }else{ updateUserOrder(productId, action); } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data', data); }) } Can any one suggest what is done wrong here? -
form resends data after refresh
Should be very simple but not working. I have a view with a form. When I submit the form I what to stay on this view but I want to prevent the form from resending data. Every answer here in stackoverflow says a redirect is enough to change from post to get method. But I want to stay on the view and a redirect to the same view is not working. Here is what I did: @never_cache @csrf_protect def journeys(request): if request.method == "POST": form = AddJourneyForm(request.POST) if form.is_valid(): journey = form.save(commit=False) journey.user = request.user journey.save() redirect('JourneyMap_journeys') else: form = AddJourneyForm() qs = Journey.objects.filter(user_id=request.user.id) context = { 'form': form, 'journeys': qs } return render(request, 'JourneyMap/journeys.html', context) Also, I tried to reset the form when loading the page and when submitting the form: <script type="text/javascript"> $( document ).ready(function() { document.getElementById('add-journey').reset(); }); function submitJourneyForm() { var form = document.getElementById('add-journey'); form.submit(); form.reset(); return true; } </script> none of it works. -
Avoiding Race Conditions with Django's get_or_create() with using Multiprocessing
I'm really struggling to avoid race conditions with Django when using the multiprocessing library to parallelize the creation/updating of database objects. I've got the following models, custom Manager, and code: class CustomPersonManager(models.Manager): from django.db import transaction # not really imported here, just for reference def get_or_create(self, defaults=None, **kwargs): with transaction.atomic(): # Added transaction.atomic() self._for_write = True try: return self.select_for_update().get(**kwargs), False # Added <select_for_update> except self.model.DoesNotExist: params = self._extract_model_params(defaults, **kwargs) return self._create_object_from_params(kwargs, params) class Person(models.Model): name = models.TextField(unique=True) objects = CustomPersonManager() # adds the custom manager def main(): from multiprocessing import Pool names = ['john', 'john', 'sue', 'mary', 'bob', 'alice'] with Pool() as pool: pool.map(Person.objects.get_or_create, names) With the above, and also w/o the above, I get the following error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "appname_person_id_key" DETAIL: Key (person_id)=(1) already exists. I'm pretty sure I have a handle on why the issue is happening, I just can't figure out how to go about addressing it. I've read through several dozen discussions here on SO, as well as other sites, all of which sound promising but don't seem to work (or, rather, I can't get them to work.) Would appreciate any thoughts/ideas on how to proceed. Notes: I'm using a Postgres … -
Auth.Token must be a "User" instance Django
This error occurs when I try to login using the endpoint this endpoint api/auth/user. ValueError: Cannot assign "OrderedDict([('username', 'Kdot'), ('password', '123456')])": "AuthToken.user" must be a "User" instance. Below is the urls from django.urls import path, include from .api import RegisterAPI, LoginAPI, UserAPI from knox import views as knox_views urlpatterns = [ path('api/auth', include('knox.urls')), path('api/auth/register', RegisterAPI.as_view()), path('api/auth/login', LoginAPI.as_view()), path('api/auth/user', UserAPI.as_view()), path('api/auth/logout', knox_views.LogoutView.as_view(), name='knox_logout') ] Here is the api.py file from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, LoginSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "User": UserSerializer(user, context=self.get_serializer_context()).data, "Token": AuthToken.objects.create(user)[1] }) # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data _, token = AuthToken.objects.create(user) return Response({ "User": UserSerializer(user, context=self.get_serializer_context()).data, "Token": token }) # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated ] serializer_class = UserSerializer def get_object(self): return self.request.user Below is the serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class … -
Change the value of a field in a class depending on the result of a function
how can I modify the value of a boolean field of a class depending on the result of a function? What I am trying to do is a function that ping (icmp) an ip that is in the 'Cliente' class and depending on the result, change the value 'ping_status' in the class. I'm new to python, so I don't have a lot of knowledge, and I've been trying to do this for 1 week, but I can't. models.py class Cliente(models.Model): razon_social = models.CharField('Razon Social', max_length=50) numero_cuenta = models.CharField('Numero de cuenta',max_length=6) nombre_contacto = models.CharField('Nombre del contacto', max_length=50) numero_del_contacto = models.CharField('Numero del contacto', max_length=10) email = models.EmailField('Correo Electronico', blank=True, null=True) tiene_as_propio = models.BooleanField('Tiene ASN priopio', default=False) ipv4 = models.GenericIPAddressField('IP', default='192.168.0.0') segmento = models.CharField('Segmento', max_length=15) asn= models.CharField(max_length=6, blank=True, null=True) created = models.DateTimeField('Creado el', auto_now_add=True ,blank=True, null=True) updated = models.DateTimeField('Actualizado el', auto_now_add=True, blank=True, null=True) topologia = models.FileField('Topologia', blank=True, null=True) ping_status = models.BooleanField('Ping', blank=True, null=True) def Meta(self): verbose_name = 'cliente' verbose_name_plural = 'clientes' def __str__(self): return self.razon_social My function looks like this: def do_ping(): """Realice un nuevo ping y guárdelo en la base de datos.""" ip_clientes = Cliente.objects.values_list('ipv4') for ip in ip_clientes: ip = (list(ip)) for ping in ip: ping = subprocess.call(['ping', '-n', '1', '-w', …