Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement ADFS SSO having Django as backend and React as frontend?
I have registered a app for the django application in Azure Active directory. After the configuration of ADFS to Django app the SSO is working fine. Now I have integrated this Django app with a React app. Now I gotta implement SSO for the same. I need some guidance and direction on how to go forward with this. Please give me an idea to work on this. -
Django Template - How to check if dynamically constructed key has value in Object
I've an object that contains names like draft = { "name_ar": "test arabic", "name_en": "test english", "name_tr": "test turkish", "name_nl": "", } and I've language_code variable which will have either 'ar' or 'en' values. So before checking if key has value in the object what I did is I constructed the key first like below {% with name='name_'|add:language_code %} So now my query is I want to add class grey-color to div container if name doesn't have value in draft object. How can I achieve this? {% with name='name_'|add:language_code %} <span class="secondary-title {% if not "how can I check here" %}grey-color{% endif %}"> {% endif %} I'm very new to Django so happy to hear any suggestions or solution. -
Django template html variable inside a variable
In my views i created a variable passing in the context that looks like this {13: {112: 33.333333333333336, 120: 66.66666666666667, 125: 66.66666666666667}, 14: {110: 20.0, 111: 20.0, 113: 20.0, 121: 40.0, 126: 40.0}} In my template i am inside a loop from questions, and want to assign this values to answers inside the question: {% for question in questions %} <div class="ui basic padded segment left aligned"> <h4 class="ui header"> Question {{ forloop.counter }} / {{ questions|length }}: {{ question.prompt }} </h4> <ul> {% for option in question.answer_set.all %} <li> {{ forloop.counter }}) {{option.text}}: {{ ans.{{ question.pk }}.{{ option.pk }} }} %. {{ ans.13.120 }} </li> {% endfor %} </ul> </div> {% endfor %} If I use {{ ans.13.120 }} it works, but is not dynamic.... I want a way to use variables inside the {{ }}... something like: {{ ans.(question.pk).(option.pk) }}... Is it possible? -
Why blocks are not displayed on the page?
I ran into such a problem, the blocks do not want to be displayed on the page, which I do not really understand, since I did not work with the template engine before. this is code views.py class IndexView(generic.ListView): template_name = 'Homepage/index.html' model = Goods context_object_name = 'goods' def sale(request): return render(request, 'Homepage/sale.html') This is code of index.html <td>{% block sale %} {% endblock %}</td> This is code of sale.html {% extends "index.html" %} {% block sale %} <td class ="sale"> <img src="image"> <h1 class="description">description</h1> <a class="buy" href="#openModal" > <span >Купить</span></a> <h1 class="price">цена</h1> </td> {% endblock %} And this is the construction of the template -
Django + Celery + Redis on a K8s cluster
I have a Django application deployed on a K8s cluster. I need to send some emails (some are scheduled, others should be sent asynchronously), and the idea was to delegate those emails to Celery. So I set up a Redis server (with Sentinel) on the cluster, and deployed an instance for a Celery worker and another for Celery beat. The k8s object used to deploy the Celery worker is pretty similar to the one used for the Django application. The main difference is the command introduced on the celery worker: ['celery', '-A', 'saleor', 'worker', '-l', 'INFO'] Scheduled emails are sent with no problem (celery worker and celery beat don't have any problems connecting to the Redis server). However, the asynchronous emails - "delegated" by the Django application - are not sent because it is not possible to connect to the Redis server (ERROR celery.backends.redis Connection to Redis lost: Retry (1/20) in 1.00 second. [PID:7:uWSGIWorker1Core0]) Error 1: socket.gaierror: [Errno -5] No address associated with hostname Error 2: redis.exceptions.ConnectionError: Error -5 connecting to redis:6379. No address associated with hostname. The Redis server, Celery worker, and Celery beat are in a "redis" namespace, while the other things, including the Django app, are in … -
"Related Field got invalid lookup: contains" when attempting to search a ManyToMany field in Django
I'm using Django 3.2 and Python 3.9. I have this model with a ManyToMany field class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=True) ... crypto_currencies = models.ManyToManyField(CryptoCurrency) Then I have created this query to find an account if it contains an item from teh many-to-man field class AccountManager(models.Manager): def get_active(self, crypto_currency=None): q = Q() q &= Q(active=True) if crypto_currency != None: q &= Q(crypto_currencies__contains=crypto_currency) return Account.objects.filter(q) but this doesn't seem to be working. I get this error line 1184, in build_lookup raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: contains What's the right way to construct a Django query to search a ManyToMany field? -
non_field_errors "No data provided" error on PUT request
I am new in Django and python. Now I am trying to do web API with Django and python. My GET, POST, and DELETE requests are working, on PUT request i getting error { "non_field_errors": [ "No data provided" ] } (i used Postman) Here's my code: Serializer: from rest_framework import serializers from .models import Topic class TopicSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=50) text = serializers.CharField(max_length=500) class Meta: model = Topic fields = [ 'title', 'text' ] def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('text', instance.description) instance.save() return instance Views: from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from .models import Topic from .serializers import TopicSerializer class TopicView(APIView): def get(self, request): topics = Topic.objects.all() serializer = TopicSerializer(topics, many=True) return Response({'topic': serializer.data}) def post(self, request): topic = request.data serializer = TopicSerializer(data=topic) if serializer.is_valid(raise_exception=True): topic_saved = serializer.save() return Response({'success': 'Topic {} created successfully'.format(topic_saved.title)}) def put(self, request, pk): # saved_topic = get_object_or_404(Topic.objects.all()) saved_topic = get_object_or_404(Topic.objects.filter(id=pk)) data = request.data.get('topic') serializer = TopicSerializer(instance=saved_topic, data=data, partial=True) if serializer.is_valid(raise_exception=True): topic_saved = serializer.save() return Response({ "success": "Topic '{}' updated successfully".format(topic_saved.title) }) def delete(self, request, pk): topic = get_object_or_404(Topic.objects.all(), pk=pk) topic.delete() return Response({ "message": "Topic with id `{}` has been deleted.".format(pk) }, status=204) App … -
How do I resync my repositories with github?
I have a situation where I have a Django app hosted on a Ubuntu server, a remote github repository, and a local repository on a local machine. For all sorts of bad reasons things have gotten out of sync and the version on the Ubuntu server is the most up to date, next the version on my local machine, and lastly the version on GitHub. I'm envisioning lots of conflicts when I try to push the server version to GitHub and then pull that to my local machine. I'm wondering if it may be more straightforward to re-init the server files and link to a new repository in GitHub and pull that to my local machine. I'm not too worried at this stage about loosing version history as I'm the only one using the files (I'll clock it up to a learning experience!). -
Byte Json cannot be loaded after transforming to string json
The Json that its receiving in message is a byte json like so: b'{"_timestamp": 1636472787, "actual": 59.9, "target": 60.0}' The Code is supposed to change the byte Json to String Json and load it to access the items but when I load it I get the following error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Code: import json def handle_msg(topic, message): m = message.decode("Utf-8") print(json.loads(m)) -
Dependent dropdown filter not functioning as expected
I have a dependent dropdown filter. The issue I am facing is that after you filter the second parameter on the filter is cleared and you have to select a different option and then reselect the first option to change the second paramater Before filtering: After filtering: I believe the reason this is happening is because the jQuery is not firing again. Is it possible to get the jQuery to fire again after it has been filtered and the list already has the first parameter? New to jQuery so having a hard time with it filter: class CarFilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Post.objects.none() self.fields['manufacture'].empty_label = 'Make' self.fields['model'].empty_label = 'Model' if 'model_manufacture_id' in self.data: try: model_manufacture_id = int(self.data.get('model_manufacture_id')) self.fields['model_id'].queryset = CarModels.objects.filter(model_manufacture_id=model_manufacture_id) except (ValueError, TypeError): pass class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' form = CarFilterForm template: <form method="get" id="AllCarsForm" data-cars-url="{% url 'ajax-allcars' %}"> {% render_field myFilter.form.manufacture class="cars-filter-widget" %} {% render_field myFilter.form.model class="cars-filter-widget" %} <button class="btn btn-primary" type="submit">Search</button> </form> <script> $("#id_manufacture").change(function () { var url = $("#AllCarsForm").attr("data-cars-url"); var manufactureid = $(this).val(); $.ajax({ url: url, data: { model_manufacture: manufactureid, }, success: function (data) { $("#id_model").html(data); }, }); }); </script> -
Django - Celery Worker - Channels
thank you in advance I am trying to start a Celery Worker to accept WebConnections usng Channels - but when my worker starts it cannot seem to find channels. When I pip list channels is installed settings.py has channels INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels',' tasks.py from __future__ import absolute_import, unicode_literals import os import threading from merlin.celery import app, get_blender from django.conf import settings from celery import shared_task from channels import Channel @app.task(bind=True, track_started=True) def render(task, data, reply_channel): bpy = get_blender() setup_scene(bpy, data) context = {'rendering': True, 'filepath': os.path.join(settings.BLENDER_RENDER_TMP_DIR, task.request.id)} sync_thread = threading.Thread(target=sync_render, args=(bpy, context, reply_channel)) sync_thread.start() bpy.ops.render.render() context['rendering'] = False sync_thread.join() if os.path.exists(context['filepath']): os.remove(context['filepath']) if reply_channel is not None: Channel(reply_channel).send({ 'text': json.dumps({ 'action': 'render_finished' }) })' The error I get - from channels import Channel ImportError: cannot import name 'Channel' from 'channels' (/usr/local/lib/python3.8/dist-packages/channels/__init__.py) Again thank you in advance -
Django: from uploaded file with models.FileField create data visualization
In my projecty my user can upload a standard excel file thanks to a models.FileField. The file looks kinda like this: total partial [...] user 10 4 other 18 6 With this information I'd like to create some chart and grahic using Chart.js that compared the info from the user and the other person and then show them to my user in a html page for each file uploaded of course. So my plan would be to read the excel file using openpyxl and create the variable to loop to create the chart. Is this a good approach? This is my code right now and I'm gettin this error 'tuple' object has no attribute 'append': MODELS class Document(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) docfile = models.FileField() def __str__(self): return self.docfile 'tuple' object has no attribute 'append' VIEWS import from openpyxl import load_workbook def upload_file(request): message = 'Upload as many files as you want!' row = [] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): wb = load_workbook(filename=request.FILES['docfile'].file) sheet = wb.active newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True): for cell in row: row.append(cell) return redirect('upload_file') else: message = 'The form is not valid. Fix the following … -
How to make postgresql row fields "read only", if all fields of a row is filled up
How to make postgresql row fields "read only", if all fields of a row is filled up. I am using Django. -
Django Migration Error 'TypeError: sequence item 1: expected a bytes-like object, str found' on mysql-connector-python cursor_cent.py file
I'm using mysql-connector to handle mysql requests in a Django project. Problem is I'm setting up a simple project with "django-admin startproject project ." and when I try to do a simple manage.py migrate, this is my output. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: aqui <mysql.connector.cursor_cext._ParamSubstitutor object at 0x7f408ae1ec10> b'SELECT engine FROM information_schema.tables WHERE table_name = %s' Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 91, in migrate self.recorder.ensure_schema() File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 68, in ensure_schema editor.create_model(self.Migration) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 348, in create_model self.deferred_sql.extend(self._model_indexes_sql(model)) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 1087, in _model_indexes_sql output.extend(self._field_indexes_sql(model, field)) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 1106, in _field_indexes_sql if self._field_should_be_indexed(model, field): File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/mysql/schema.py", line 111, in _field_should_be_indexed storage = self.connection.introspection.get_storage_engine( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/mysql/connector/django/introspection.py", line 270, in get_storage_engine cursor.execute( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) … -
Aligning form labels input-group-prepend with bootstrap
I'm working on a python/django website with bootstrap, but i'm running into something i can't seem to solve on my own. Been a while since i've worked with python/django/bootstrap, so i might be missing something? <form action="" method="post" autocomplete="off"> {% csrf_token %} {{ form.non_field_errors }} <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend "> <span class="input-group-text" id="basic-addon1">Player Name</span> </div> <input type="text" class="form-control" id="player_name" name='player_name' placeholder="Player Name"> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend "> <span class="input-group-text " id="basic-addon1">Recruiter</span> </div> {{ form.recruiter }} </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Notes</span> </div> <input type="text" class="form-control" id="notes" name="notes"> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Accepted</span> </div> <select class="form-select form-select-lg" aria-label=".form-select-lg" id='accepted' name='accepted'> <option value="Not Yet" selected>Not Yet</option> <option value="No">No</option> <option value="Yes">Yes</option> </select> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Vote is up</span> </div> <select class="form-select form-select-sm" aria-label=".form-select-sm" id='vote_is_up' name='vote_is_up'> <option value="No" selected>No</option> <option value="Yes">Yes</option> </select> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="archived" hidden> <label class="form-check-label" for="flexCheckDefault" hidden> Archived </label> </div> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} <button type="submit" class="btn btn-primary">Add</button> … -
How to restrict user in Django to login through only one device, window or tab?
I am looking to develop a functionality to enable the user to login to only one place , if he tries to login from another device or tab then he will get logout from the previos tab or device, i didnt find any good solutios to implement, any help is appreciated -
find previous sunday date based on today date in Django
Let us consider today date as 09/11/2021 And previous sunday date is 31/10/2021 today = datetime.date.today() Now find previous sunday date -
Django MongoDB Model field with unique values or null
I am using Djongo v1.3.6 to connect Django to MongoDB. Now I would like to have an optional field for a unique value - in my case a phone number. I thought it is possible to have null as a placeholder for accounts that do not have a phone number. However, MongoDB seems to be treating null as a unique value as well. Thus, it is not letting me insert new objects into the database once one object has phone_number: null I tried to declare the index for phone_number as sparse but it does not seem to take any effect. I searched the Internet for some time now but could not find anything useful for my case. class UserProfile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = models.CharField(validators=[PHONE_VALIDATOR], max_length=17, unique=True, null=True, blank=True) ... meta = { 'indexes': [ {'fields': ['phone_number'], 'sparse' : True, 'unique' : True}, ], } Any help is very appreciated. -
Internal server error 500 when uploading a CSV file using AJAX
I have a very simple web app for uploading CSV files to my server. For that purpose, I'm using AJAX and JQUERY under DJANGO: function Upload_CSV(){ var csrftoken = getCookie('csrftoken'); var formData = new FormData(document.getElementById("formUploadCSV")); var add_answer = confirm("Confirm uploading and processing of csv File?" ); if (add_answer) { $.ajax({ url: "/cvs/DealsMachine/upload_csv/", type: "POST", data: formData, async: false, cache: false, contentType: false, enctype: 'multipart/form-data', processData: false, success: function (data) { $('#message').html("<p class='text-center text-success font-weight-bold'>Success</p>"); window.alert("Data populated, please check the lists table!"); }, error: function(data) { $("#message").html("<p class='text-center text-danger font-weight-bold'>Failed</p>"); } }); } } However, every time I try to use the function, I'm receiving POST 500 (Internal server error). I was able to capture the following on the browser console: Any idea about how to handle this error? I deployed the app on another server and works fine. So maybe is something about server configuration. (I'm using Linux servers) Thanks! -
Field is required even though it's been explicitely set to not required in serializer
I'm running into some trouble with a route creating/updating a model, DRF asks for a field I've set to not required, and it's been working with other serializers but not a speficic one. The request (here the costing nested object is what interests us) : { "building_block_id":"bd750fa0-d41d-492d-adc1-9aa7c50db232", "building_block_type_ids":"6fb5b907-9597-45fd-bb77-e93a2456cca3", "approbation_user":"", "approved":false, "name":"BB2", "web_doc_link":"", "author":"", "cms":"", "part_number":"", "manufacturer":"", "description":"T", "available_stock":null, "include_bench_output_connector":true, "base_repository":"", "form_factor_id":null, "direction_bench_side":null, "cost_references":[ { "cost":2, "cost_date":"2021-11-03", "cost_quantity":2, "fab_cycle_time_days":2 } ], "coupling":[ { "developped":false, "tested":false, "validated":false, "delivered":false, "valid_link":"", "implem_link":"", "software_version_id":"62f4c9f8-1156-4b41-af1a-22041b824d06" } ], "comments":[ ], "features":[ ], "provides":[ ], "requires":[ ] } Error returned by Django : { "coupling": [ { "building_block_id": [ "This field is required." ] } ] } Serializer class : class BuildingBlockSerializer(serializers.ModelSerializer): cost_references = NestedCostReferenceSerializer(many=True, required=False) coupling = NestedCouplingSerializer(many=True, required=False) comments = NestedBuildingBlockCommentsSerializer(many=True, required=False) features = NestedFeaturesBuildingBlockSerializer(many=True, required=False) provides = NestedProvidesSerializer(many=True, required=False) requires = NestedRequiresSerializer(many=True, required=False) main_picture_link = Base64ImageField(required=False) front_picture_link = Base64ImageField(required=False) back_picture_link = Base64ImageField(required=False) # Related names for reverse relationship cost_reference_rel_name = 'cost_references' coupling_rel_name = 'coupling' comment_rel_name = 'comments' feature_rel_name = 'features' provide_rel_name = 'provides' require_rel_name = 'requires' class Meta: model = building_blocks.BuildingBlock fields = ['building_block_id', 'building_block_type_ids', 'approbation_user', 'approved', 'name', 'main_picture_link', 'front_picture_link', 'back_picture_link', 'web_doc_link', 'author', 'cms', 'part_number', 'manufacturer', 'description', 'available_stock', 'include_bench_output_connector', 'base_repository', 'form_factor_id', 'direction_bench_side', 'cost_references', 'coupling', 'comments', … -
Cant use findAll() function
can any body tell me why is error html_content = get_html_content(test) from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') productDetail = [] product = soup.findAll("div",{"class":"s-result-item"}) for pd in product: product = pd.find("div",class_="s-impression-counter") product_name = product.find('span',class_="a-text-normal").text productDetail.append(product_name) print(productDetail) it appears 'NoneType' object has no attribute 'find' i know the problem is in the product variable, but if i not allow to use findAll(), what should i use ? -
save data to Django models on different types of messages I receive on Mqtt
My goal is to save data to my Django models on different types of messages I receive on Mqtt. For that I assume I need to import the model I want to save. But when I do I get "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." My mqtt connection setup: mqtt.py import paho.mqtt.client as mqtt from print.views import * def on_connect(client, userdata, rc, properties=None): client.subscribe("foo/printers/#") print("Connection returned result: " + mqtt.connack_string(rc)) def on_message(client, userdata, msg): handle_msg(msg.topic, msg.payload) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username="foo",password="bar") client.connect("mqtt.foo.de", 1883, 60) My __init__.py: from . import mqtt mqtt.client.loop_start() My Messagehandler view: from models import Machine def handle_msg(topic, message): printer = topic.split("/")[2] print(Machine.objects.get(Name=printer)) When I put the import inside the function it simply doesnt work -
Apache Django Error - Loading Module From lib64 But Expected To Load From Different Directory
I have configured apache, python virtual environment, and Django. I'm trying to host the Django in apache. I verified the Django working fine by running the command "./manage.py runserver 192.168.0.107". But this is not working in Apache, in apache, if I load the page I'm getting 500 Internal Server errors. In the Apache HTTP log, I got the below error message. [Mon Nov 08 18:21:51.248632 2021] [wsgi:error] [pid 1812] [remote 192.168.0.105:50224] django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) In Python, I verified the SQLite version and it says 3.36.0 and not 3.7.17, refer to the details below. Python 3.7.12 (default, Nov 8 2021, 09:02:58) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from sqlite3 import dbapi2 as Database>>> >>> from sqlite3 import dbapi2 as Database >>> Database.sqlite_version_info (3, 36, 0) I tried to find the version that apache actually using, I used the grep command and I found it was using SQLite 3.7.17 from lib64 [root@localhost ~]# grep -rnw /usr -e '3.7.17' /usr/lib64/pkgconfig/sqlite3.pc:10:Version: 3.7.17 /usr/include/sqlite3.h:110:#define SQLITE_VERSION "3.7.17" REQUIREMENT I need to clean or uninstall package 3.7.17 and tell Apache or WSGI to use 3.36.0 Below is the configuration … -
How to update multiple objects in django
I'd like to update more than one objects at same time, when the register date achieve more than 6 days: The Idea is update all issue_status from 'On Going' to 'Pending' for each objects Is it necessary iterate it? Below is my current code and error: models.py class MaintenanceIssue(models.Model): issue_status = models.CharField(max_length=30, choices=[('pending', 'Pending'), ('on going', 'On going'), ('done', 'Done')]) register_dt = models.DateTimeField(blank=True, null=True) @property def pending_issue(self): issue_time_diff = (datetime.now() - self.register_dt).days return issue_time_diff views.py: on_going_issues = MaintenanceIssue.objects.get(issue_status='On Going') if on_going_issues.pending_issue > 6: on_going_issues.issue_status = 'Pending' on_going_issues.save() get() returned more than one MaintenanceIssue -- it returned 61! -
twilio sms status callback - not in json
I made a django app that integrates with Twilio SMS and I am trying to set-up a way to get the status of an sms I send. I have been following twilio guide on how to track delivery status on python so when I send a text I send it with the following parameters (where sms_obj is an instance in my db to keep track of the text I am sending). def send_sms(sms_obj, to): client = Client(account_sid, auth_token) message = client.messages \ .create( body=sms_obj.body, from_= phone_number, to=to, status_callback='https://www.ateam.productions/comunications/twilio/sms/status/{sms_id}'.format(sms_id=sms_obj.id) ) return So basically I should receive a callback with delivery statuses on this url https://www.ateam.productions/comunications/twilio/sms/status/{sms_id}, (which I do) However, the data I get from Twilio aren't in a nice Json structure but rather a long string like the one below. Before I start coding some weird regex to process such string, I was wondering if anyone had advices on how to handle the process. SmsSid=SM3bceec02449e4a75a3c308e2befa6136&SmsStatus=sent&MessageStatus=sent&To=%2B19174003826&MessageSid=SM3bceec02449e4a75a3c308e2befa6136&AccountSid=////////&From=%2B19179244405&ApiVersion=2010-04-01