Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django settings TypeError: 'module' object is not callable
File "D:\Python Development\Django_Broad\blog\blog\settings.py", line 19, in ALLOWED_HOSTS =config('ALLOWED_HOSTS', cast=csv()) TypeError: 'module' object is not callable Why am I getting this error? someone help me.. -
fetch function in javascript looping twice
function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; fetch('/emails/sent') .then(response => response.json()) .then(emails => { // Print emails console.log("Hello, world!"); // ... do something else with emails ... }); } ** corresponding api where fetch request is being made ** @login_required def mailbox(request, mailbox): # Filter emails returned based on mailbox if mailbox == "inbox": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=False ) elif mailbox == "sent": emails = Email.objects.filter( user=request.user, sender=request.user ) elif mailbox == "archive": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=True ) else: return JsonResponse({"error": "Invalid mailbox."}, status=400) # Return emails in reverse chronologial order emails = emails.order_by("-timestamp").all() print(request.user) for email in emails: print(email) return JsonResponse([email.serialize() for email in emails], safe=False) Actually, fetch function loops twice and "Hello, world!" is printed twice in console, so emails when fetched also get displayed twice. Please tell me why fetch request is called twice on backend. Please feel free to ask for more information. -
ModelForm can't see my attributes-fields, form ProfileForm needs update, WHYYYY?
First of all i am new at programming and I was doing django eshop from the tutorials and everything was going well until everything crashed when I tried to make Cabinet in Users: here is My views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm from django.contrib.auth import authenticate , login as django_login , logout as django_logout from .models import Profile from .forms import ProfileForm def cabinet(request): django_user = request.user profile = Profile.objects.get(user=django_user) context = { 'form': ProfileForm(instance=profile) } return render(request, 'users/cabinet/main.html', context) My main.html {% extends 'base.html' %} {% block content %} <h1>Welcome {{ request.user.username }}!</h1> <form action="" method="post"> {% csrf_token %} <div> <label for="">First name</label> <input type="text" name="first_name" value="{{ request.user.first_name }}"> </div> <div> <label for="">Last name</label> <input type="text" name="last_name" value="{{ request.user.last_name }}"> </div> <div> <label for="">Email</label> <input type="email" name="email" value="{{ request.user.email }}"> </div> {{ form }} <button class="btn btn-success">Save</button> </form> {% endblock content %} My models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=13, blank=True, null=True) rate = models.IntegerField(default=4) def __str__(self): return '{} Rate: {}'.format(self.user.username, self.rate) and My forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import … -
Many to one relationship search and serialization in django rest framework
I am kinda new to Django and trying to understand how I can search in different models and create nested serializer. This is the simple model file that I have class Company(models.Model): company_name = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) NIF = models.CharField(max_length=9, null=True, blank=True) class Office(models.Model): company = models.ForeignKey(Company) office_name = models.CharField(max_length=50, default='Main') direction = models.CharField(max_length=50) class Employee(models.Model): office = models.ForeignKey(Office) employee_ name = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) here the company has many offices and offices have many employees. So I am creating a search API in which a user can search the company_name or office_name or employee name and get the data in a relational format like this; company: { ------- office: { ------ Employee: { ------ } } } now my problem is filtering the data and serializing it in this format. I tried this Nested Serialization for serialization and also tried filter from here filter in django but not able to come up with the solution. Note: I am creating Django API by using django-rest-framework -
am actually configuring django on command prompt..... installed pip, python and django but whenever i run manage.py it raises an import error?
PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 22, in main() File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate virtual environment? PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 22, in main() File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py migrate Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of … -
Django - How to display multpile choices for Polls app
Following along the Django polls app tutorial, I was wondering if instead of having a Charfield for the choice Model and manually adding every response/choice to the database; Is it possible to have choices? For example: class Poll(models.Model): text = models.CharField(max_length=255) pub_date = models.DateField() def __str__(self): return self.text class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=255) votes = models.IntegerField(default=0) def __str__(self): return "{} - {}".format(self.question.text[:25], self.choice_text[:25]) You have standard choices for every Poll like this: class Poll(models.Model): text = models.CharField(max_length=255) pub_date = models.DateField() def __str__(self): return self.text class Choice(models.Model): VOTING_CHOICES = ( ('Aye', 'Aye'), ('Nay', 'Nay'), ('Abstain', 'Abstain'), ) question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField( max_length=7, choices=VOTING_CHOICES, default='Aye', )** votes = models.IntegerField(default=0) def __str__(self): return "{} - {}".format(self.question.text[:25], self.choice_text[:25]) Does that make sense? Every time I try to implement this, I either get an empty dictionary response when I POST from the form or the options show up in tuples(or do not render at all). -
problem of join between my django ORM tables
I am trying to join four tables where the three tables carry the primary key of the fourth table and this is my model. class patient(models.Model): choix = ( (0, 0), (1, 1), (0.1, 0.1), (0.15, 0.15), (0.2, 0.2), (0.25, 0.25), (0.3, 0.3), (0.4, 0.4), (0.5, 0.5), (0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9), ) date_creation=models.DateField(auto_now_add=True,null=True) Nom_patient=models.CharField(max_length=200,null=True) date_naissance=models.DateField(max_length=200,null=True) numero_telephone=models.CharField(max_length=30, null=True) adresse=models.CharField(max_length=100, null=True) matricule=models.CharField(max_length=200,default="Pas de matricule",null=True) assurance=models.CharField(max_length=200,default="Non assuré",null=True) compagnie=models.CharField(max_length=200,default="Pas de compagnie",null=True) medecin=models.CharField(max_length=200,null=True) pourcentage = models.FloatField(max_length=20,default='Pas de pourcentage',null=True, choices=choix) def __str__(self): return self.Nom_patient the second lab model class labo(models.Model): examen = ( ("Ac anti- HAV IgM B 70", "Ac anti- HAV IgM B 70"), ("Ac anti- HBc IgM B 70", "Ac anti- HBc IgM B 70"), ("Ac anti- HBe B 70", "Ac anti- HBe B 70"), ("Ac anti- HBs (Test qualitatif ) B 70", "Ac anti- HBs (Test qualitatif ) B 70"), ("Ac anti- HVs (Titrage) B 100", "Ac anti- HVC (Titrage) B 100"), ("Ac anti- HVC (Hépathie C) B 70", "Ac anti- HVC (Hépathie C) B 70"), ("Ag HBe B 70", "Ag HBe 70"), ("Ag HBs B 70", "Ag HBs B 70"), ("Antistreptolysine O ( ASLO) B 35", "Antistreptolysine O (ASLO) B 35"), ("Sérodiagnostic de Widal et Félix B 40", … -
how to Filter and get both tables using django
i'm working on a small project using Django and i would like to know how can i get the fields of the Client table too since i have a foreignkey, how can i filter where shared_with = 1 for example and get both of the tables this is my code : class ContactCenter(models.Model): contact = models.IntegerField(blank=False, null=False) contact_source = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(Client, related_name="contact_y", on_delete=models.CASCADE, null=True, blank=False) how can i get Client fields and ContactCenter both ? -
Django: How to display custom fields for inlines?
How do I display custom fields in my admin interface? Specifically, I have a function that is used to display images, and I would like that to show beside the name. Here is my code. models.py class Photo(models.Model): file = models.ImageField(upload_to='media/images') ... def __str__(self): return f"{self.title}" class Album(models.Model): photos = models.ManyToManyField(Photo,related_name="photos",blank=True,through="Photo") admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from .models import Photo, Album class PhotoInline(SortableInlineAdminMixin, admin.TabularInline): model = Album.photos.through extra = 2 class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") inlines = [PhotoInline] ... admin.site.register(Album, AlbumAdmin) Right now, in my admin interface, I only see the titles of each model. -
HEROKU DJANGO PYTHON APP crashing with application error
I am having difficulty with my first deploy of a heroku app to DJANGO. I have loaded the application and it worked, but did not load all css. It also did not size images properly and appeared to be missing a template and bootstrap style sheets. It also deleted images loaded into the application on restart of dyno. I have upgraded to the hobby plan. I have made the changes noted by heroku to include the following : First Commit : #BASE_DIR = Path(file).resolve().parent.parent Second Commit: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) I am using whitenoise for img handling. TRACEBACK 2021-05-06T23:38:58.920990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-05-06T23:38:58.921004+00:00 app[web.1]: worker.init_process() 2021-05-06T23:38:58.921005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-05-06T23:38:58.921005+00:00 app[web.1]: self.load_wsgi() 2021-05-06T23:38:58.921005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-05-06T23:38:58.921006+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-05-06T23:38:58.921014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-05-06T23:38:58.921014+00:00 app[web.1]: self.callable = self.load() 2021-05-06T23:38:58.921014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-05-06T23:38:58.921014+00:00 app[web.1]: return self.load_wsgiapp() 2021-05-06T23:38:58.921015+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-05-06T23:38:58.921015+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-05-06T23:38:58.921015+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-05-06T23:38:58.921016+00:00 app[web.1]: mod = importlib.import_module(module) 2021-05-06T23:38:58.921016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-05-06T23:38:58.921017+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-05-06T23:38:58.921017+00:00 app[web.1]: File "<frozen … -
Django Tables - Conditional Formatting (Display certain data)
Is there a way to display specific data using Django-tables2? I'm trying to use a Primary Key in my current Database to see if it matches the email of the user that is logged in. Once the user navigates to the page where the database is shown, it will only show data that is related to the user that is signed in. I've been looking up on Django-Tables2 Conditional Formatting but I am unsure on how to start. Some additional info: I am using Microsoft Graph API to sign in the users. -
'dict' object has no attribute 'user'
i am sending a post request from my frontend when i check it on my browser the successfully sent request looks like this user:"username" but when i try to print it in my views.py i get dict object has no attribute 'user' views.py @api_view(['POST']) def sendmail(request): print(request.data.user) note that request.data looks like this {'user': 'username'}, what am i doing wrong? -
ForeignKey between Shared and Tenants Applications, error
I'm using Django / Django-Tenants , i i would like to do a foreignKey between a shared Application and a Tenant one but i'm getting an error : from django.db import models from users.models import CustomUser from customer.models import Client from apps.contacts.models import Contact # Create your models here. class ContactCenter(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE, null=True, blank=False) contact_source = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(CustomUser, related_name="contact_y", on_delete=models.CASCADE, null=True, blank=False) Error Message : django.db.utils.ProgrammingError: relation "contacts_contact" does not exist NB: Contact is a Tenant Applciation not a shared one -
Django custom ManyToMany relation name
Consider the following 2 models: class Tag(models.Model): name = models.CharField(max_length=30) class Exercise(models.Model): name = name = models.CharField(max_length=30) tags = models.ManyToManyField(Tag, related_name='exercises') In admin.py: admin.site.register(Tag) When deleting a tag from the admin panel, a warning with relation object names are displayed which is not really informative. # Are you sure you want to delete tag3 ? The following elements will be deleted too. Tag: tag3 Relation exercise-tag: Exercise_tags object (3) Relation exercise-tag: Exercise_tags object (6) Relation exercise-tag: Exercise_tags object (9) How can one make a more informative message by displaying the actual exercise name instead of the relation name e.g Exercise_tags object (3) ? For instance: # Are you sure you want to delete tag3 ? The following elements will be deleted too. Tag: tag3 Relation exercise-tag: Advanced exercise 5 Relation exercise-tag: Introductory exercise on programming Relation exercise-tag: My exercise 2 -
Django doesn't recognize/can't find post_save edited field?
I'm trying to create a unique SlugField using a post_save model signal. If the SlugField already exists, a number should be appended to the slug to make it unique. However, Django does not seem to to recognize when the SlugField already exists. I'm using a single-tabled inherited MPTT model: class Text(MPTTModel): type = models.CharField(max_length=255, blank=False) # for STI. Essentially returns the class name. title = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255, blank=True) slug_order = models.CharField(max_length=255, blank=True) def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Book(Text): objects = BookManager() class Meta: proxy = True @receiver(post_save, sender=Book, dispatch_uid="create_book_slug") def create_book_slug(sender, instance, **kwargs): slug = slugify(instance.title) slug_exists = Book.objects.filter(slug=slug).exists() # This always seems to be False counter = 1 while slug_exists: counter += 1 new_slug = f"{slug}-{counter}" slug_exists = Book.objects.filter(slug=new_slug).exists() if counter > 1: slug = f"{slug}-{counter}" instance.slug = slug My test: b1 = Book.objects.create(title="book book") b2 = Book.objects.create(title="book book") self.assertEqual(b1.slug, "book-book") # True … -
Stop webpage from waiting for cancelled XHR requests
I'm working on a Django project and the Javascript for one of my pages makes some XHR requests that can take a while to complete. If the user goes to this page, they have to wait for these requests to finish before the site lets them go to another page. I've been trying to have the page cancels these requests when clicking to another page, but even if the requests cancel the page still waits quite a while before changing URLs. This is how my requests are structured. const controller = new AbortController() const signal = controller.signal let get_salesperson_sales = async() => { return await fetch(`/reports/salesperson-sales/${fromDate && toDate ? `from_date=${fromDate}&to_date=${toDate}` : ''}`, { signal }) .then(response => response.json()) .then(response => { document.getElementById('total_rep_sales').innerText = '$'+Number(response.total_sales.toFixed(2)).toLocaleString() return response }) .catch(error => { if (error.name === 'AbortError') console.log('Salesperson sales fetch was aborted.') else errorMessage.innerHTML += '<p>Error getting sales by rep: '+error.responseJSON ? error.responseJSON.details : 'Unexpected error'+'</p>' }) } There are 4 of these functions in total that I call with Promise.allSettled(). At the bottom of the page, I bind a couple functions to abort the requests. $('#date-filter').submit(() => { // Stop loading current report before submitting controller.abort() return true }) $(window).bind('beforeunload', () => … -
Is there code generator for Django like Gii?
I use Gii code generator with Yii2 framework for more that 3 years ago. Now I want to change to Django but I need a similar code generator. -
how to run some lines at the initialization of my django api in production?
I build an API in django, it worked perfectly until I tried to deploy it with gunicorn and nginx. I initiate some constants at the beginning of my views.py. So my code looks like this before defining all my views. from ... import... x = do_big_stuff() y = do_big_stuff2() z = do_big_stuff3() I do this to init x, y and z at the launching of the api (so when I enter python manage.py runserver) I use x, y and z in all my views after this. This init takes approximately 15 seconds then a request will take less than 1 second. It's not a problem But since I deployed this API with gunicorn and nginx I meet an issue : it looks like this lines are ran at EACH request. So it takes so much time and user always get "502 bad gateway" and I can see in my logs [CRITICAL] WORKER TIMEOUT (pid:23605) So i commented these lines and just add a print("hello world") to check and realised that hello world was printed at each request ... That was not the case during development. I assume my method is not good, but could anyone advice me please ? -
Django User registration/auth with Neo4j
i need a clear way to use Neo4j as default database and model of User registration and login in Django. i try many ways and I've done a lot of searching but cant find a clear way. Can anyone give me a practical example? -
Getting data from JSON to JS
In the django function, I send data to JS via JSON startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y') enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y') paymentparking = paidparking.objects.filter(expirationdate__range = (startdate, enddate)).values('expirationdate', 'price') return JsonResponse(dict(paymentparking)) How do I get price and expirationdate separately in JS? $.ajax({ type: "POST", url: "statistics", data: { 'startdate': finalDateStrStart,'enddate': finalDateStrEnd, }, dataType: "json", cache: false, success:function (data) { } }); This is what I get in the django function before sending the JSON: <QuerySet [{'expirationdate': datetime.date(2021, 4, 30), 'price': 300.0}, {'expirationdate': datetime.date(2021, 5, 5), 'price': 750.0}]> If success: function (data) { console.log(data) } As a result, I get: I need to get the price and expirationdate separately. How can this be done? -
ModuleNotFoundError: No module named 'scraper.items' when running django server
I am getting a weird error in a django scrapy web application. I am going to show my files structure first. | db.sqlite3 | manage.py | output.doc | +---accounts | | admin.py | | apps.py | | decorators.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | __init__.py | | | | | \---__pycache__ | | __init__.cpython-39.pyc | | | +---templates | | \---accounts | | company_register.html | | login.html | | user_register.html | | | \---__pycache__ | admin.cpython-39.pyc | apps.cpython-39.pyc | decorators.cpython-39.pyc | forms.cpython-39.pyc | models.cpython-39.pyc | urls.cpython-39.pyc | views.cpython-39.pyc | __init__.cpython-39.pyc | +---products | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | 0001_initial.py | | | __init__.py | | | | | \---__pycache__ | | 0001_initial.cpython-39.pyc | | __init__.cpython-39.pyc | | | +---templates | | \---products | | get_products.html | | | \---__pycache__ | admin.cpython-39.pyc | apps.cpython-39.pyc | models.cpython-39.pyc | urls.cpython-39.pyc | views.cpython-39.pyc | __init__.cpython-39.pyc | +---produp | | asgi.py | | settings.py | | urls.py | | views.py | | wsgi.py | … -
Is there an API to interract with porjects?
I'm developing a workflow-based application in Django. The purpose of this application is to grab some data about projects, and to create a project in a scheduler application. My corporate is testing "ONLYOFFICE Projects" for scheduling / projects managements. I've to import some Trello based projects, and add some projects from my django-based application. Is it possible to call an API entry point to create a project, manage users, groups... in ONLYOFFICE ? I've not seen anything in the docs... Thanks ! -
Django urls.py config gives page 404
I have a very simple Django installation with one app, but I cannot get the urls.py configured correctly. It's strange, because I have the same config in another application, which works perfectly. urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('subscribe/', include('newsletter.urls')), path('subscription-confirmation/<str:key>/', include('newsletter.urls')), path('admin/', admin.site.urls), ] APP urls.py from django.urls import path from newsletter.views import subscribe, subscription_conf urlpatterns = [ path('subscribe/', subscribe), path('subscription-confirmation/<str:key>/', subscription_conf), ] Error in browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/subscribe/ Using the URLconf defined in backoffice.urls, Django tried these URL patterns, in this order: 1. subscribe/ subscribe/ 2. subscribe/ subscription-confirmation/<str:key>/ 3. subscription-confirmation/<str:key>/ 4. admin/ The current path, subscribe/, didn’t match any of these. I'm pulling my hair out with this, what am I doing wrong? Thanks in advance. -
Trouble with Django annotation with multiple ForeignKey references
I'm struggling with annotations and haven't found examples that help me understand. Here are relevant parts of my models: class Team(models.Model): team_name = models.CharField(max_length=50) class Match(models.Model): match_time = models.DateTimeField() team1 = models.ForeignKey( Team, on_delete=models.CASCADE, related_name='match_team1') team2 = models.ForeignKey( Team, on_delete=models.CASCADE, related_name='match_team2') team1_points = models.IntegerField(null=True) team2_points = models.IntegerField(null=True) What I'd like to end up with is an annotation on the Teams objects that would give me each team's total points. Sometimes, a team is match.team1 (so their points are in match.team1_points) and sometimes they are match.team2, with their points stored in match.team2_points. This is as close as I've gotten, in maybe a hundred or so tries: teams = Team.objects.annotate(total_points = Value( (Match.objects.filter(team1=21).aggregate(total=Sum(F('team1_points'))))['total'] or 0 + (Match.objects.filter(team2=21).aggregate(total=Sum(F('team2_points'))))['total'] or 0, output_field=IntegerField()) ) This works great, but (of course) annotates the total_points for the team with pk=21 to every team in the queryset. If there's a better approach for all this, I'd love to see it, but short of that, if you can show me how to turn those '21' values into a reference to the outer team's pk, I think that will work? -
Transmitting JSON Django
I have a request for a model paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)) I need to take 2 fields from the request and pass them to JS I send it via return JsonResponse({'price': paymentparking.price,'expirationdate':paymentparking.expirationdate}) But I get an error АttributeError: 'QuerySet' object has no attribute 'price'