Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I construct a Django Template Tag condition statement to check the request method for POST?
First, what I'd like to work: {% if method == POST %} {% include "app/template_x.html"%} {% else %} {% include "app/template_y.html"%} {% endif %} I'm using class based views, inheriting from django.views.generic.edit.UpdateView I tried a few things, among them passing an HttpRespons.method object via extra context in the urls.py asview() function. Anyone have an idea how I should approach this problem? -
heartbeat between python desktop app installed at client and django server app
There is a python desktop app that is deployed at client end and a Django web based server app. What way can we possibly set up a heartbeat for each client's desktop location so that we get an alert in case desktop application is not working/off. -
OSError: [Errno 99] Address not available - sending e-mail from django docker app with gmail smtp
I'm trying to send an e-mail from my django application in docker and I'm getting following error: OSError at /accounts/mail/ [Errno 99] Address not available Request Method: GET Request URL: https://localhost:8000/accounts/mail/ Django Version: 2.2.5 Exception Type: OSError Exception Value: [Errno 99] Address not available Web server log: web_1 | OSError: [Errno 99] Address not available web_1 | [17/Sep/2019 19:21:35] "GET /accounts/mail/ HTTP/1.1" 500 108369 My environment: Ubuntu 18.04 Docker Django + Gunicorn Postfix I have no problem to send an e-mail outside docker, locally. I suppose that there might be a problem with smtp port inside docker, but I don't know how to fix that. I tried with postfix - same error. View code from django: from django.core.mail import EmailMessage # didn't work also with send_mail def email(request): mail_subject = 'Activate your account' message = 'test' to_email = 'mail@mail' email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('index') Part of my docker-compose file. version: '3.3' services: web: build: ./app command: python manage.py runsslserver 0.0.0.0:8000 ... ports: - 8000:8000 - 587:587 - 25:25 env_file: .envdev ... postfix: image: juanluisbaptiste/postfix:latest expose: - "25" env_file: - .envpostfix restart: always volumes: - "/etc/localtime:/etc/localtime:ro" ... Django settings: EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend EMAIL_USE_TLS=True EMAIL_HOST=smtp.gmail.com EMAIL_HOST_USER=*** EMAIL_HOST_PASSWORD=*** EMAIL_PORT=587 My … -
Items getting disappeared when I put them for scrollreveal
I'm using scroll reveal in my site. When I put them for scroll reveal they are getting disappeared. But first 4 items(images, div) are responding to the scroll reveal(2 or 3 items working fine) rest of the items are not. I'm using https://unpkg.com/scrollreveal/dist/scrollreveal.min.js. they are provided with exact id and classes for reveal method. <section style="margin-top: 60px; text-align: justify;"> <div class="container"> <div class="row"> <div class="col-md-4 col-sm-4"> <div class="cardss" style=" border-radius: 10px 10px 10px 10px;-moz-border-radius: 10px 10px 10px 10px;-webkit-border-radius: 10px 10px 10px 10px;padding: 10px"> <img id="im1" class="card-img-top" src="static/learninganddev.png" style="height: 250px; width: 200px; margin-left: 70px" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" style="font-weight: 2px solid #000000; font-size: 20px">Learning&Development</h5> <p class="card-text">Google Home voice-activated speaker.consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p> </div> <div class="card-body" style="margin-top: 50px"> <a href="#" class="card-link">Read more</a> </div> </div> </div> <script> window.sr = ScrollReveal({ reset: true }); sr.reveal('.navbar', { duration: 2000, origin:'bottom' }); sr.reveal('.who', { duration: 2000, origin:'top', distance:'300px', easing: 'cubic-bezier(0.5, 0, 0, 1)' , }); sr.reveal('.whowearetext', { //till here everything is fine. duration: 2000, origin:'right', }); sr.reveal('.cardss', { // this one onwards not working, getting disappeared. … -
How do I assign a Python variable from js code to send to the database without reloading the page?
There is a page for creating posts "aframe". There is field name office 'title', button choice background, terrain. Data from the 'title' field is saved to the database. But how to connect the background, relief buttons to the database via django without reloading the page? Is it possible to pass a value from javascript to python to save to a database var sceneEl = document.querySelector('a-scene'); AFRAME.registerComponent('foo', { init: function () { var skyEl = sceneEl.querySelector('a-sky'); //Changing color using JQuery here $(document).ready(function(){ let color, src,mtl, terrain, text1; $("#text1").click(function(e){ var x = document.getElementById("fname").value; //document.write(x); document.getElementById("output").innerText = x; return false; }); $("#color button").click(function(e){ color = e.currentTarget.className; skyEl.setAttribute('src', '#blank'); skyEl.setAttribute('color', color); {{ background }} = color; }); $("#picture button").click(function(e){ src = e.currentTarget.className; skyEl.removeAttribute('color'); skyEl.setAttribute('src', '#'+src); }); $("#terrain button").click(function(e){ var skob = sceneEl.querySelectorAll('.obj_model'); terrain = e.currentTarget.className; mtl = e.currentTarget.name; for (let index = 0; index <= skob.length; ++index) { //alert(mtl); //skyEl.setAttribute('color', '#1fa9e3'); skob[index].setAttribute('src', '#'+terrain+'-obj'); skob[index].setAttribute('mtl', '#'+mtl); if(terrain=='city'){ skob[index].setAttribute('scale', '30 120 35'); } else { skob[index].setAttribute('scale', '5 10 5') ; } } }); }); } }); sourceURL=pen.js <form method="post"> <div id="left" > <div id="select"> <div id="cssmenu"> {% csrf_token %} <input type="text" placeholder="title" name="title"> <input type="text" placeholder="body" name="body"> <input type="text" placeholder="background" name="background"> <ul> <li class='has-sub'><a href='index.html'><span>Terrain</span></a> <ul> … -
Django background task not running
I am trying to run a background task in django to run an sql query when the user clicks on a certain button. I created the function in tasks.pyand when I try and run it using the @background decorator, it does not run (Runs fine without @background). I am not getting any error, however the task is not running. Here is my tasks.py from background_task import background from django.db import connection @background(schedule=1) def delete_process_background(process_id): print("Start of background task") with connection.cursor() as cursor: cursor.callproc("delete_process",[process_id]) And my function in views.py that is triggered when user clicks the button: def db_revert_process(request): process_id = int(request.POST['text']) delete_process_background(process_id) print("Called background process") return HttpResponse() The print statement in the views.py function is executed but not the statement in the background task. -
django models: change the way value of a field gets rendered in admin panel
My model in django has uuid as its primary key: class User(models.Model): token = models.UUIDField(primary_key=True, default=uuid.uuid4) def __str__(self): return str(self.token).replace('-', '') and since uuid gets saved in the database without dashes(-), therefor I could able to render it without dashes using __str__ in the code above. The result looks like this: But how can I do the same thing for the way the value gets rendered in the admin panel (how to remove dashes): -
django form can not find the author in the post
Wanted to have every user already post with their post authorship but, the code I have with, they need to choose the author I have tried deleting author then error pop up: author_id is unknown class Post(models.Model): STATUS_CHOICES = { ("draft", "Draft"), ("published", "Published"), } author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1 ) title = models.CharField(max_length= 100, null=True, blank=True, default="Başlık") class PostForm(forms.ModelForm): class Meta: model = Post fields = ["author", "title", "content", "image"] widgets = { "author": forms.Select(attrs={"class": "form-control"}), "title": forms.TextInput(attrs={"class": "form-control"}), I use django 2.2.5 and still have errors -
How to search by choice value
How to search by choice value and not the key as in the following: This model: CITY_CHOICES = ( ('Omran', 'عمران'), ('AlBayda ', 'البيضاء'), ('Hodeidah', 'الحديدة'), ) class Place(models.Model): city = models.CharField(choices=CITY_CHOICES, max_length=20) # Manager objects = PlaceManager() This search by city but looking for the key and I want it looking for value class PlaceQuerySet(models.QuerySet): def search(self, query): lookup = ( Q(city__icontains=query) ) return self.filter(lookup) class PlaceManager(models.Manager): def get_queryset(self): return PlaceQuerySet(self.model, using=self._db) def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().search(query) -
How to retreive manyToMany field in django model serializer, with viewset?
Help, I am trying to understand since last hours, how to send a manytomany extra data with my Item modelSerializer. here is the definition of the fiel in the Item model, extra = models.ManyToManyField(SimpleExtraField, through='ExtraField') class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) here is my model serializer : class basic_itemSerial(serializers.ModelSerializer): medias = mediaSerial(many=True) extra = ExtraSerial(many=True, required=False) children = minItemSerial(many=True) class Meta: model = Item fields = '__all__' as a queryset, I am just trying to get a list, list this queryset = Item.objects.all() I tried adding extra data to get_serializer_context, like this, def get_serializer_context(self, *args, **kwargs): context = super(self.__class__, self).get_serializer_context(*args, **kwargs) qex= [] for q in self.queryset: qq = ExtraField.objects.all().filter(item=q.reference) for qqs in qq: qex.append(qqs) context['extra'] = qex return context I also tried to change the name in the serializer to extra_fields = ExtraSerial(many=True, required=False) But None of them worked for me, I think I am connecting bad the serializer to the queryset. also here are the extraModel and SimpleExtraField: class ExtraField(models.Model): item = models.ForeignKey(Item, related_name="extra_fields") key = models.ForeignKey(SimpleExtraField) # add limit to not yet selected value = models.CharField(max_length=glLargeCharLen) serializer.py class SimpleExtraField(models.Model): name = models.CharField(max_length=glMiddleCharLen, unique=True, primary_key=True) -
How to get values for a queryset for an model when the foreign key is not in the current model?
I have the following models: class Work_Music(models.Model): key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) class Catalogue(models.Model): work_music = models.ForeignKey(Work_Music, verbose_name=_('work_music'), on_delete=models.PROTECT) name = models.CharField(max_length=100, null=True, blank=True) name_short = models.CharField(max_length=100, null=True, blank=True) no = models.CharField(max_length=100, null=True, blank=True) related_field() only works with the Foreign key is in Work_Music. Many catalogue/catalogue numbers can map to a piece of music (Work_Music). How can I construct a query set on Work_Music to pull all of the catalogues related to the piece of work? -
Multiple File Upload inside a inlineformset
Hi I would like to know if it's possible to have a multiple file upload field within a formset. The structure is as following: I have a parent model who get a one to one relationship with one of his possible child. The child have several inline formset with other specific models. And one of those formset need to contain a multiple file upload. They are all edited in the same view. The parent and the related child get created before going to that edit view. This is a capture of my database structure (there is a missing table on the right): Just to give you a vague idea I have: a Task model which have a 1to1 to a GeneralApplicationTask which have a many to one relationship with GeneralApplicationProperty(this is what is used in the inlineformset) So for each GeneralApplicationTask Form I have some fields and then several formset containing property information and each need to contain a multiplefile upload. The problem I am facing is, if I create a modelForm to manage the files and create a Mt1 from the GeneralApplicationProperty model, then I cant properly save the files because I need to know which form (and the … -
old javascript script code in chrome inspect than editor
I am making my personal portfolio using Django and I was writing a javascript for contact form and it is getting some old javascript code I don't know from where. The code I wrote in my script in the editor is new but when I am inspecting in chrome it's showing some old code for the same script file -
How to send data in POST fetch request from one domain and process request on server listening on different domain?
I will admit I don't understand this part of the web technologies. I have a python django app running on localhost:8000 and react client SPA running on localhost:3000. I have implemented REST APIs on the server using django rest framework and I am calling a couple of APIs from the client in browser. There is a issue of CORS which I have patched using django cors headers app. I am able to use GET APIs like this and that is working fine till now. fetch("http://localhost:8000/api/comments", { method: "get" }).then((response)=> { console.log("got response"); return response.json(); }).then((comments) => { console.log("got json", comments); this.setState({ comments: comments }) }).catch((error)=> { console.log("error", error); }); Second I have POST API where add commenter's name, I have tried different variations to call this API, but not with much success. All the variations have one issue and that is, the request body is empty, browser network tab and logs in views.py method agree on that. var headers = new Headers(); // Add a few headers headers.append('Content-Type', 'application/json'); headers.append('X-Requested-With', 'XMLHttpRequest') let payload = { "first_name": first_name.value, "last_name": last_name.value }; var data = new FormData(); data.append( "json", JSON.stringify( payload ) ); const request = new Request("http://localhost:8000/api/user", { method: 'POST', mode: … -
Where to learn advanced/beyond-basic Django web
Hi guys I’m new to web dev and Django but I’ve learnt all the basics and now want to develop my skills. I’ve created some web apps that aren’t too complex since I’m struggling to find follow-along content for advanced web Django dev. Where can I find some? -
clamav timing out when scanning stream for large file
Have a React/Django app that a small group of clients use to submit files to us. Using react-dropzone for the file upload, without any maxSize specified, so it should be react-dropzone causing the issue. The file I'm working with is an Excel file of about 160MB. When the files are uploaded, clamav (called from Django) scans the files in stream before writing to disk. I have run into issues in the past with clamav and default maximum file sizes being removed, so I have those either removed or set very high. Initially it was timing out after 30 seconds. I looked at the scan.conf for anything related to time and 30, which brought me to IdleTimeout which defaults to 30. I changed it to 360 and now it times out after about 90 seconds. Nothing in the scan.conf has a 90 associated with it, so I'm puzzled as to what else I could change to get this to work. These are settings I've changed and the value I have them at: LogFile /home/log/clamd.log LogTime yes LogSyslog yes LogVerbose yes LocalSocket /var/run/clamd.scan/clamd.sock StreamMaxLength 2048M ReadTimeout 360 IdleTimeout 360 MaxScanSize 0 MaxFileSize 0 OnAccessMaxFileSize 0 # 0 disables any limit Any suggestions … -
Invalid block tag on line 21: 'transaction'. Did you forget to register or load this tag?
I am getting the error on the transaction models, not sure what i am missing. See the error below i am on the view from django.db import models class Status(models.Model): description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "status" def __str__(self): return self.description class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) password = models.CharField(max_length=128) created_at = models.DateTimeField() updated_at = models.DateTimeField() signed_agreement = models.BooleanField() class Meta: db_table = "users" def __str__(self): return self.first_name + ' ' + self.last_name class Inventory(models.Model): status = models.ForeignKey(Status, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "inventory" def __str__(self): return self.description class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE,related_name='inventory') checkout_time = models.DateTimeField() scheduled_checkin_time = models.DateTimeField() actual_checkin_time = models.DateTimeField() created_at = models.DateTimeField() updated_at = models.DateTimeField() class Meta: db_table = "transactions" def __str__(self): return self.user.first_name + ' ' + self.inventory.description -
psycopg2 copy_from csv with null foreign key field
I'm downloading a CSV file from a URL then trying to load it into a PostgreSQL table using copy_from. On the Product model there's a foreign key field, nutrition, with null=True. class Product(models.Model): ... nutrition = models.ForeignKey( NutritionFact, blank=True, null=True, on_delete=models.SET_NULL, ) In the file a null nutrition field is represented by an empty string ("") which is causing an error: psycopg2.DataError: invalid input syntax for integer: "" CONTEXT: COPY product_product, line 1, column nutrition_id: "" def copy_from_csv(model, reader): opts = model._meta table = f'{opts.app_label}_{opts.model_name}' columns = next(reader) # first row of csv is columns buffer = io.StringIO() writer = csv.writer(buffer, delimiter='\t') for row in reader: writer.writerow(row) model.objects.all().delete() buffer.seek(0) with closing(connection.cursor()) as cursor: cursor.copy_from( buffer, table=table, sep='\t', columns=columns, ) I've tried csv.writer(buffer, delimiter='\t', escapechar='\\', quoting=csv.QUOTE_NONE) but the error persists. -
Can't convert Request to PhoneNumber. django rest custom token auth
I am trying to create custom token authentication end point which accepts phone number and token and status in request POST then response shoud ba as follows Successful response should create a status object linked to the user object Failing request can be either unauthorized request or bad request based on auth-token/phone number combination. to do that I wrote following snippets: serializers.py class TokenSerializer(serializers.Serializer): phone_number = serializers.CharField(required=True, allow_blank=False) def validate(self, attrs): phone_number = attrs.get('phone_number') user = authenticate(request=self.context.get('request'),phone_number=phone_number) if user is None: msg = ('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = ('Must include "phone_number.') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs views.py class TokenView(APIView): serializer_class=TokenSerializer authentication_classes = (CustomTokenAuthentication, ) def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data login(request,user) token, created = Token.objects.get_or_create(user=user) return Response({ 'user':new_data, 'token':token.key }) authbackend.py: class CustomTokenAuthentication(TokenAuthentication): def authenticate_credentials(self, key,phone_number): try: user = UserProfile.objects.get(phone_number=username) return user except ObjectDoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). raise exceptions.AuthenticationFailed('Invalid phone ') try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') return (token.user, token) when try to login I got this … -
Access Django ManyToMany field values within Model.clean()
It seems (though I'm having trouble finding it in the Django documentation) that ManyToMany fields are deferred when they are selected in the Django admin, and so effectively not set, during the call to a Django Model's .clean() method. Here's an example to illustrate. models.py: import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ class Country(models.Model): code = models.SlugField(max_length=2, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class Region(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) name = models.CharField(max_length=64, db_index=True, unique=True) class SampleModel(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) regions = models.ManyToManyField(Region, blank=True) countries = models.ManyToManyField(Country, blank=True) field1 = models.PositiveIntegerField() field2 = models.CharField( max_length=3, choices=[("foo", "FOO"), ("bar", "BAR")] ) def clean(self, *args, **kwargs): print( "Got id=%s, regions=%s, countries=%s, field1=%s, field2=%s" % (self.id, self.regions.all(), self.countries.all(), self.field1, self.field2) ) if self.regions.exists() and self.countries.exists(): raise ValidationError(_("'Regions' and 'Countries' are mutually exclusive")) super().clean(*args, **kwargs) admin.py: from django.contrib import admin from my_app.models import SampleModel @admin.register(SampleModel) class SampleModleAdmin(admin.ModelAdmin): fields = ("regions", "countries", "field1", "field2") In Django shell after ./manage makemigrations && ./manage migrate: from my_app.models import Country, Region Country.objects.bulk_create([ Country(code="US", name="United States"), Country(code="UK", name="United Kingdom"), ]) Region.objects.bulk_create([ Region(name="North America"), Region(name="EMEA"), ]) Above, SampleModel overrides .clean() to enforce that regions and countries are mutually exclusive. (Specify one … -
【Django×Google App Engine】No module named 'MySQLdb' when deploying
I'm setting GitHub source ↓ https://github.com/priyankavergadia/Django-Dialogflow-GoogleVisionAPI But I have trouble in [Deploy the app to the App Engine standard environment] phase. At a glance Deploying have been done well.But I'm trying to access webservice, so [502 Bad Gateway] appears. At local environment(running python manage.py runserver), this program works well. Please give me some advices. My environment: ・Windows10 ・Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 ・django 2.2.4 ・MySQL second generation 5.7 mysql django I serched and tried. 1. install mysqlclient and uninstall PyMySQL 2. rewrite [import ~]part in various pattern... description in Django setting.py below # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter # See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers # for more information import MySQLdb as sql# noqa: 402 # [START db_setup] if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/michatbot-250809:us-central1:polls-instance2', 'USER': 'test', 'PASSWORD': '', 'NAME': 'polls', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: … -
django soft deleted objects appear in filters
I implemented soft deletion by adding a BooleanFeild "deleted" to my models, overriding the delete method for CASCADING deletion and updating deleted field and changing objects with a custom manager which filters deleted objs. the problem is when I'm filtering other models on relations, the deleted rows affect the result. here's an example of my implementation: models: class Model_B(models.Model): # somefields... class Model_A(models.Model): label = models.CharField(max_length=30) deleted = models.BooleanField(default=False) model_bs = models.ManyToManyField(Model_B, through='RelationModel') # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() def delete(self, *args, **kwargs): # first we set deleted flag of Zone to True self.deleted = True self.relationmodel_set.update(deleted=True) # save zone self.save() class RelationModel(models.Model): model_a = models.ForeignKey(Model_A, models.CASCADE) model_b = models.ForeignKey(Model_B, models.CASCADE) deleted = models.BooleanField(default=False) # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() manager: class BaseManager(models.Manager): """ this manager will filter deleted """ use_for_related_fields = True def get_queryset(self): return super().get_queryset().filter(deleted=False) class AllManager(models.Manager): """ all """ def get_queryset(self): return super().get_queryset() query: Model_B.objects.filter(model_a__isnull=False) this returns Model_B objects which has a relations to deleted Model_A objects too. I tried: Model_b.objects.filter(model_a__isnull=False, model_a__deleted=False) this one returns … -
How to dump an object that is a child of a class (knowing that class casting is impossible in Python)?
I have a 3 models: Entity, Person which is a child of Entity, and Agenda: class Entity(models.Model): is_physical = models.BooleanField(default=True) class Person(Entity): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) agendas = models.ManyToManyField('Agenda') def simple_desc(self): return str(self.user) if self.user is not None else '? no user ?' class Agenda(models.Model): owner = models.ForeignKey(Entity, blank=True, null=True, on_delete=models.CASCADE, related_name='owner') You (almost) can't do simpler! Now I would like to list all the owners of all the agendas starting with agendas like: for agenda in Agenda.objects.all(): print(agenda.owner.simple_desc()) Because owner is an Entity, it doesn't know about simple_desc() (which is in its child Person). It's impossible to cast the owner into a Person. How would you do? Note aside: Right now, all owner are Person, but in a near futur, I'll create Company(Entity) which could also be owner of an Agenda, so I need to keep my models like this, don't suggest to change this organization this is not a valid solution. It's important, I have a more complex query, to make my loop with Agenda (and not Person) -
Django annotate sum subquery
How to sum a field of a subquery ( with OuterRef ) and annotate it on outer model? note that I have a common my_special_queryset_annotator that alter queryset by adding some annotations, ... so i dont want to use direct Sum('books__sections__page') let assume following models class Library(models.Model): votes=models.IntegerField() class Book(models.Model): library=models.ForiegnKey(Library) class Section(models.Model): book=models.ForiegnKey(Book) pages=models.IntegerField() # this works, but when want to use `my_special_queryset_annotator` # we could not do this simple annotation Library.annotate( all_pages=Sum('books__sections__pages'), ) # when want to sum on a Subquery, its must constructed like below but it dont work Library.objects.annotate( all_pages=SUM( # <-- problem Subquery( my_special_queryset_annotator( Section.objects.filter(book__libraray_id=OuterRef('id')) ).values('altered_pages') ) ) ) -
ModuleNotFoundError: No module named view, models
Tenho o seguinte problema tenho duas app Quero que um model de uma dessas apps passe informação para outra app exemplo Projeto: APP1.models APP2.view View da APP2 from projeto.app1.models import ObjetoX objeto_x = ObjetoX(parm=1) Ao fazer isso surge o seguinte erro: ModuleNotFoundError: No module named 'projeto.app1'