Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"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 -
Template Does Not Exist at / cms_wizard /create/ INHERIT
The issue > https://i.stack.imgur.com/0mbDr.png Here is one solution I tried: "os.path.join(SETTINGS_PATH, 'templates'), "(I substituted SETTINGS_PATH with BASE_DIR, and the setting.py terminated without any errors but still the problem isn't solved. how am I supposed to inherit the template, it has to be in a folder which I should make? also, the directory of cms_wizard/create isn't making sense as shown in the image above how do I fix it. Here is my setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cms.context_processors.cms_settings', 'django.template.context_processors.i18n', ], }, }, ] -
Django makemigrations models conflict apps extensions
I'm trying to extend 2 apps in django. While I'm trying to apply manage.py makemigrations I'm recieving the following error: File "Desktop\ipam\ipam_extension\openwisp_ipam_extension\models.py", line 3, in <module> from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet File "Desktop\ipam\venv\lib\site-packages\openwisp_ipam\base\models .py", line 10, in <module> from openwisp_users.models import Organization File "Desktop\ipam\venv\lib\site-packages\openwisp_users\models.py" , line 18, in <module> class User(AbstractUser): File "Desktop\ipam\venv\lib\site-packages\django\db\models\base.py" , line 113, in __new__ raise RuntimeError( RuntimeError: Model class openwisp_users.models.User doesn't declare an explicit app_label and isn't in an application in INSTA LLED_APPS. My 2 apps are: openwisp_users_extension extends openwisp_users openwisp_ipam_extension extends openwisp_ipam The problem is probebly that in openwisp_ipam_extension.models I have this line: from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet Which internally using openwisp_users extended app. I assume this conflict shouldn't happend because I saw it is possible to extend both apps together -
django oauth2 Session value state missing error
there is my social auth setting and it works correctly in local-host but on server it returns session value state missing error. i have tested similar questions in stack overflow but the answers didn't solved my problem. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/' SOCIAL_AUTH_LOGIN_URL = '/' SOCIAL_AUTH_REDIRECT_IS_HTTPS = True LOGIN_URL = '/auth/login/google-oauth2/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = ['state'] SESSION_COOKIE_SECURE = False AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) white_list = ['http://localhost:8000/accounts/profile'] DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': white_list, 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SERIALIZERS': {}, } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Order by nested objects date
I am building a chat application and have the following models representing the chat room, chat message and the counter of unread messages class ChatRoom(BaseModel): name = models.CharField(max_length=255, default='', blank=True) participants = models.ManyToManyField('accounts.User', related_name='chat_rooms') class ChatMessage(BaseModel): text = models.TextField(default='', blank=True) owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='messages') class ChatRoomUnreadMessagesCounter(BaseModel): room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='unread_counters') owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) messages_count = models.IntegerField(default=0) class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) class Meta: abstract = True I would like to make an API view that would return a list of ChatRoom objects that are ordered in the following manner: ChatRoom objects that have unread messages ordered by messages count -> ChatRoom objects that have messages in them by the latest message created_at last in first out -> ChatRoom objects that are sorted alphabetically. How would I construct my queryset properly? Here's an expected result output | Room Name | Unread Messages | Last Message | | Rean | 2 | 09.11.2021T12:00:00 | | Ash | 1 | 09.11.2021T12:00:24 | | Altina | 0 | 09.11.2021T12:15:00 | | Juna | 0 | 09.11.2021T12:14:00 | | Kurt | 0 | 09.11.2021T12:13:00 | | Musse | 0 | 09.11.2021T12:12:00 | … -
Django send multiple responses
Disclaimer: New to Django, don't know all the advanced stuff here so may be quoting my question in a misleading way. I have set up a Django web server that does some numerical calculation with some network data on the server-side and returns the data to the client. Now, the tasks requested by users have multiple results and they are generated sequentially. For now what I'm doing (1) User send a task request from frontend---> (2) calculation is done in the backend sequentially and all the result is generated ---> (3) django sends all the result in a single response to the frontend to update the result. Now the 2nd step that is the calculation part takes a lot of time about 1-2 seconds which spoils the user experience on the client-side. As multiple results are generated sequentially, I can show the result one by one to the client as they are generated. But I can't understand how can I send multiple responses against a single client request. I guess this is not possible with HTTP? Can anyone help me how do I tackle this problem? Is it possible to that?