Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass data from DetailView to FormView hidden inputs
I've tried several articles on StackOverflow and none of them seem to answer my question. I'm relatively new to this, so I'm sure I'm just missing something basic. I have a DetailView that has a button. When the user clicks the button, I want it to pass 2 field values to the FormViews hidden input fields. I just don't know where to start. Here is my code: views.py class RequestInfoView(CreateView): template_name = 'request_info.html' form_class = RequestInfoForm success_url = '/thanks/' def form_valid(self, form): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] state = form.cleaned_data['state'] vendor = form.cleaned_data['vendor'] product_name = form.cleaned_data['product'] message = name + " " + email + " " + state + " " + str(product_name) html_message = render_to_string('mail_request.html', context=({'name': name, 'email': email, 'phone': phone, 'state': state, 'product': product_name})) try: send_mail('Sales Inquiry from: ' + name, message, email, ['test@example.com'], html_message=html_message) except BadHeaderError: return HttpResponse('Invalid header found.') return super().form_valid(form) class ProductDetailView(DetailView): context_object_name = 'product_detail' model = Product queryset = Product.objects.all() template_name = 'product_details.html' def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['image'] = ProductImage.objects.all() return context forms.py class RequestInfoForm(forms.ModelForm): state = forms.CharField(widget=forms.Select(choices=STATE_CHOICES, attrs={ 'class': 'form-control select2', 'style': 'width:100%;' })) vendor = forms.CharField(widget=forms.HiddenInput(), required=True) product = forms.CharField(widget=forms.HiddenInput(), required=True) class Meta: model … -
Django URL redirecting issue
i have a redirect url problem when the user complete editing his profile informations ,i want to redirect to the profile page , but it display to me 404 error this is My view.py file : def ProfileView(request, pk=None): prof = Profile.objects.all() if pk: pr = User.objects.get(pk=pk) else: pr = request.user context= { 'pro':prof, 'profile':pr } return render(request,'profile.html',context) def update_profile(request,id): profile = get_object_or_404(Profile,id=id) form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile) if request.method=='POST': if form.is_valid: form.save() return redirect(reverse('profile-detail')) context = { 'form':form } return render(request,'profile_update.html',context) thi is my url.py file : urlpatterns = [ path('admin/', admin.site.urls), path ('',index), path ('events_details/<id>',events_details,name="events_details"), path ('evenements/',evenements,name="events"), path ('projets/',projets,name="project"), path ('project_detail/<id>/',project_detail,name="project-detail"), path ('create_post',create_post,name="create_post"), path ('project_detail/<id>/update_post',update_post,name="update_post"), path ('project_detail/<id>/delete_post',delete_post,name="delete_post"), #------------------------------------------------------------ path ('profile/',ProfileView,name="profile-detail"), path ('profile_update/<id>',update_profile,name="profile-update"), path('tinymce/', include('tinymce.urls')), path('accounts/', include('allauth.urls')), path('api-auth/', include('rest_framework.urls')) ] -
Datatables Editor - Loading Select Options from database in a Django App
I have a Django app and I'm using Datatables to display the information(json is received with url:'all_json'). That part works great, but now I'm working with the editing part. The first thing I want to do, which I'm having problems with, is to load "select options" straight from the database. I have more than one field that needs to be populated from the database, so I'm guessing that I have to make more than one ajax call. 'all_json has all the entries in the main table in the database, but it does not include all the options in the category and specialty tables. I need to display all the options. Right now I'm trying ti display the categories. Below is the latest code: html ... <body> <div id='container'> <table id="results_table" class="formdata" summary="Schedule"> <thead> <tr> <th></th> <th scope="col">Scheduled</th> <th scope="col">Venue</th> <th scope="col">Category</th> <th scope="col">Specialty</th> </tr> </thead> </table> ` <script> var editor; $(document).ready(function() { editor = new $.fn.dataTable.Editor({ ajax: 'all_json', table: "#results_table", fields: [{ label: "Category", name : "Venue.category", type: "select", placeholder: "Category" }, { label: "City", name : "Venue.city.sector", type: "select", placeholder: "City" }] }); // Activate an inline edit on click of a table cell $('#results_table').on( 'click', 'tbody td:not(:first-child)', function … -
Create two independent admin sites with Multiple databases in djnago-admin but i'm unable to fetch data from 2nd DB
I want to create two admin-site with two different DBs.It seems i am able to access default database but not frommydb2database .In djngao-admin interface when i click on a model from database mydb2 getting error relation "foo" does not exist i have also run migrations for both the database $ ./manage.py migrate $ ./manage.py migrate --database=mydb2 I have to two Apps app1 & app2 I have used Following Reference to write this code Click here Click here settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb1', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'mydb1-host', 'PORT': 'xxxxx', }, 'mydb2': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb2', 'USER': 'xxxx', 'PASSWORD': 'xxxxxxx', 'HOST': 'mydb2-host', 'PORT': 'xxxx', } } app1.models.py: from django.db import models class Foo(models.Model): user = models.IntegerField() status = models.TextField() createdat = models.DateTimeField(db_column='createdAt', blank=True, null=True) # Field name made lowercase. updatedat = models.DateTimeField(db_column='updatedAt', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'foo' app1.Fields.py: from django.contrib import admin from app1.models import * #this model belong to mydb1 class FooFields(admin.ModelAdmin): list_display = ['user','status','createdat','updatedat'] list_filter = ['status'] list_per_page = 20 app1.admin.py from django.contrib import admin from app1.models import * from app1.Fields import * admin.site.register(Foo, FooFields) app2.models.py: from django.db import models #this model … -
Django rest framework Knox
I'm using the django rest framework Knox app for token authentication. I'm struggling to understand exactly how a client would initially obtain a token. I've read the code for the knox Login view, but it appears that one already needs to have a token, in order to access this view. Although I am aware that I can write my own endpoint to allow a client to exchange a username and password for a token, I'm still not clear on exactly what the Login View provided by knox is supposed to do. Presumably, if I have a token, I am already logged in. I am new to this, as I expect is obvious from my question. -
is there a efficient way to use the field of related model in list_display?
i have two models user(built-in django) model and a another model called usertypes which have user as a foreign key in it i made the usertypes model inline with user model. In usertypes model there is a field called staff_status, i wants to use this(staff_status) field in list_display. I have found a solution to this problem using callable but i also read that using callable func slows the process because it hits the database many times and then i read that using get_queryset can solve the problem, but i don't know how to use the query_set to solve this problem or is there another more efficient way to solve this problem. class UserTypesInline(admin.TabularInline): model = UserTypes raw_id_fields = ['user'] class UserAdmin(BaseUserAdmin): inlines = [UserTypesInline] list_display = ('username','staff',) def staff(self, instance): return instance.usertypes.staff_status # def get_queryset(self,request): # qs = super(UserAdmin, self).get_queryset(request) # a = qs.select_related('usertypes') # return a admin.site.unregister(User) admin.site.register(User, UserAdmin) class UserTypes(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) staff_choices = ( ('', ''), ('Admin', 'Admin'), ('Chef', 'Chef'), ('Delivery Boy', 'Delivery Boy'), ) staff_status = models.CharField(max_length=15, choices=staff_choices, default=staff_choices[0][0]) def __str__(self): return self.staff_status -
using greater than (>) or less than (<) inside {% if statement %} doesnt work
I am writing a code for a paginator on my website on my home.html file. When i tried to put a '>' and a '<' the atom text editor read it as an html code. And then the color of the codes after the signs changed as if it they were an html code. {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'-3' %} <a class="btn btn-outline-info mb-4" href="?page={{num}}"> and it made the other page numbers on my paginators disappear. This is how my paginator should look like: ufortunately this happened: im missing two sets of numbers before and after my current page. -
Login from on site into another with different domains and server
I'm using Django and I have the following case. My main website on dummy.com has the normal login form from Django. The Django application is providing an API. I have a Single Page Application on another server with the domain auth.dummy.com My SPA is using JWT to authenticate the user so he can be logged in into the page auth.dummy.com by using the API provided by dummy.com How can I archive it that the user who logs in on the domain auth.dummy.com automatically gets logged in into the main website dummy.com? But I always want to keep the default behaviour from Django so Users can log in into the site from the main domain as well and not only from auth.dummy.com Is there a special name for this kind of authentication? I'm confused by all this names: JWT, SSO, OAuth etc. -
Vue load PDF response from another domain?
Is it possible to load a PDF response from another domain using VueJs? I have a Django view that creates an in memory PDF - it's never saved on the server. I'd like to be able to display this PDF in the Vue frontend with the frontend domain. For example if you have: backend api: api.backend-site.com frontend: my-public-site.com How do you display the PDF with the domain my-public-site.com? class PdfView(TemplateView): def render_to_response(self, context, **response_kwargs): pdf = Report.build_pdf() if pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="%s"' % 'testing.pdf' return response -
Getting data using jquery-datatables
I want to paginate data from the backend and i want to download csv table with all data using jquery datatable, but since it is already comes paginated the csv will only return the first page.. is there a way to get all data using jquery datatable and without modifying the server side url or should i do all the work and the csv handling from the backend without using jquery data-table? -
openEdx server error on exchange_access_token with azuread-oauth2
I'm now working on deploying openEdx system and encounter an error while logging in via Azure AD from the mobile device. The web Azure AD login is working fine and I can also get access_token from azure ad. But, when I try to exchange azure token with openEdx token via /oauth2/exchange_access_token/azuread-oauth2/ url, I'm getting the following error due to the empty response. AttributeError: 'NoneType' object has no attribute 'get' Hence I'm fairly new to the openEdx, its hard for me to figure out the issue. Please help to direct me into the right path to fix this issue. Following is the detail error log. Thanks in advance Apr 1 12:38:45 edxapp [service_variant=lms][django.request][env:sandbox] ERROR [edxapp 24509] [exception.py:135] - Internal Server Error: /oauth2/exchange_access_token/azuread-oauth2/ Traceback (most recent call last): File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/openedx/core/djangoapps/oauth_dispatch/views.py", line 57, in dispatch return … -
PostgreSQL IP inet comparison using django
In my PostgreSQL database, I have a table of network devices. I am building a django app that has to interact with this table. I am using models with .get() and .filter() methods, but I am not sure how to deal with the following query: select * from my_table where ip << inet '10.93.1/24' This should get records like 10.93.1.*, but not 10.93.13.*, so I can't just use: items = MyTable.objects.filter(ip__startswith='10.93.1') What is the django equivalent for this query? -
InlineFormSet in UpdateView loads with empty FileFields
I need a user to be able to edit the data in the InlineFormSet foreign key model. Currently, all the fields for all the instances of the fk model are loaded with the right data except for the FileField which is empty. How can I get the files to be loaded in the input field along with the rest of the data? OutcomeMediaFormSet = inlineformset_factory( Outcome, OutcomeMedia, formset=BaseOutcomeMediaFormSet, fields=('media', 'outcome_type', 'is_public', 'author'), extra=1, widgets={'media': FileInput(attrs={ 'class': 'custom-file', 'multiple': True }), 'outcome_type': Select() } ) class OutcomeUpdateView(UpdateView): model = Outcome form_class = OutcomeForm def get(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) outcomemedia_form = OutcomeMediaFormSet(instance=self.object) context = self.get_context_data(form=form, outcomemedia_form=outcomemedia_form) return render(request, self.get_template_names(), context) def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) outcomemedia_form = OutcomeMediaFormSet(request.POST, request.FILES, instance=self.object) context = self.get_context_data(form=form, outcomemedia_form=outcomemedia_form) if not all([form.is_valid(), outcomemedia_form.is_valid()]): return self.form_invalid(form, outcomemedia_form) return self.form_valid(form, outcomemedia_form) def form_valid(self, form, outcomemedia_form): form.save() outcomemedia = flatten_formset_file_fields(outcomemedia_form) for media in outcomemedia: media.author = self.request.user media.save() return redirect('outcomes:outcome-list') def form_invalid(self, form, outcomemedia_form): context = self.get_context_data(form=form, outcomemedia_form=outcomemedia_form) return render(self.request, self.get_template_names(), context) class OutcomeMedia(models.Model): ANALYZED_DATA = 'AD' POSTER = 'PO' RAW_DATA = 'RD' REPORT = 'RE' OTHER = 'OT' OUTCOME_TYPES = BLANK_CHOICE_DASH … -
'CharField' object has no attribute 'is_hidden' when passing initial value to a form's CharField which uses a TinyMCE widget
I'm setting up a site where users can create "lectures" which have a stylized lecture text. The style is facilitated by the TinyMCE plugin applied when filling out the lecture_text field when creating a lecture. Creating the lecture works fine, but I'd like this stylized text to already be in the lecture text area of the lecture update form. To my understanding, I can set the default content of the TinyMCE CharField with the initial argument. Here is my code right now: the editLecture HTML passes the lecture ID to the editLecture view ... <form method="post" action="{% url 'openvlab:editLecture' lecture_id %}"> {% csrf_token %} {{ lecture_form.as_p }} <script src="https://cloud.tinymce.com/5/tinymce.min.js?apiKey=re1omq7fkhbmtyijhb3xvx4cfhyl3op33zggwlqkmbt5swvp"></script> <script>tinymce.init({ selector:'textarea' });</script> <button type="submit">Save changes</button> </form> the editLecture view passes the lecture ID to the lecture update form def editLecture(request,id_string): ... lecture_form = LectureUpdateForm(lecture_id=id_string) ... the lecture update form class LectureUpdateForm(forms.ModelForm): def __init__(self,*args,**kwargs): lecture_id=kwargs.pop("lecture_id") lecture = Lecture.objects.get(id__exact=lecture_id) super(LectureUpdateForm, self).__init__(*args,**kwargs) self.fields['lecture_text'].widget = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10}, ), initial=lecture.lecture_text # this is where I try to define the initial content of the editor ) class Meta: model = Lecture fields = ['lecture_title', 'lecture_description', 'lecture_text'] When trying to access the lecture editing page, however, I get an AttributeError: 'CharField' … -
How to use a Bootstrap Modal to delete a object using Class Based Views in Django?
I´m using CBV in Django to delete items. What I want to do is when I click the button to remove, instead of redirecting me to the post_confirm_delete view I want to pop up a modal in which I show the question if the user want to delete the object and a button for confirm and the other to delete the object. I have tried this in the HTML: <button class="btn" data-toggle="modal" data-target="#fm-modal-grid">Delete</button> <div class="modal fade" id="fm-modal-grid" tabindex="-1" role="dialog" aria-labelledBy="fm-modal-grid" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button class="close" data-dismiss="modal" aria-label="Cerrar"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="container-fluid"> <div class="row"> <div class="col-12 col-sm-6"> <p>Are you sure you want to delte {{post.title}}</p> </div> </div> </div> </div> <div class="modal-footer"> <a href="{% url 'blog:post_remove' pk=post.pk %}" class="btn">Delete</a> <button class="btn btn-primary" data-dismiss="modal">Cancelar</button> </div> </div> </div> </div> And I have this in the delte CBV in the views class: class PostDeleteView(DeleteView, LoginRequiredMixin): model = Post success_url = reverse_lazy('post_list') template_name = 'blog/post_list.html' And the url file looks like this: urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('article/', views.ArticleView.as_view(), name="article"), path('newpost/', views.CreatPostView.as_view(), name="new_post"), path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/remove/', views.PostDeleteView.as_view(), name='post_remove'), ] When I press the Delete button inside the modal, it redirect me to my index, … -
Django cannot execute python manage.py runserver
I got this error right after reinstalling my windows and python accordigly now i cant execute python manage.py rusnerver -
Why pre_save signal doesn't work on other files besides the model file?
I'm trying to create a hook for when i made a new save() on some model and for a reason that i don't understand the receiver method is not called if the decorated method is in another file. I've a class called Pizza and i want to use the pre_save method from django.db.models.signals to perform a action before the content is saved # models.py file class Pizza(models.Model): name = models.CharField(max_length=200) # actions.py file from .models import Pizza from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save, sender=Pizza) def before_action(instance, **kwargs): logger.info("Before action method was called.") The code above doesn't work unless i put the method before_action within the Pizza model like this: # models.py file from django.db.models.signals import pre_save from django.dispatch import receiver class Pizza(models.Model): name = models.CharField(max_length=200) @receiver(pre_save, sender=Pizza) def before_action(instance, **kwargs): logger.info("Before action method was called.") How can i split this 2 responsibilities on each file? i would like to keep all actions in a separated file I've also tried to follow this answer but it didn't work: https://stackoverflow.com/a/8022315/2336081 -
How to group author's books annotation by kind?
I'm playing with the book/author django documentation. Is there a way to get books from author grouped by kinds in an array agg? (pgsql) The following query is correct but I need information from authors table. Books.objects.values('kind').annotate(rating_min=Min('rating'),.. Etc. Can I get author's books rating range grouped by kind ? Author.objects.values('book__kind'). annotate(rating_min=Min('book__rating')) Author.objects.annotate(rated_books=ArrayAgg('book'),...? Expecting something like author.rated_books =[ {'kind': 'fantasy', 'rating_min' : 2, 'rating_max' : 5, 'total' : 6}, ] Any idea to combine both? -
How to expose session data in an error in django view
I have series of views with forms in django that the user must follow as part of signup. (there a many different signup pathways) However there can be an occasional error in the view. How can I expose the user's current state (which is stored via the session) in the error reporting so that it can be debugged more easily? (Note errors are currently setup up to email admin via logging) Should this be setup in logging or have to be raised as part of the error? in production.py .... 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'mail_admins'], 'propagate': True } } -
Failed to find python function/method
Im trying to call a python function from views.py when a button on my html webpage is clicked (WITHOUT page being refreshed). However, I get an error Not Found: /mymethod with a request of "GET /myfile/mymethod HTTP/1.1 404". For some reason my call to mymethod function from my html file is wrong and request looks to be looking for a file/method within my html file. views.py from flask import Flask app = Flask(__name__) def index(request): return HttpResponse("Testing") @app.route('/mymethod') def mymethod(): print("HELLO WORLD!!") myfile.html <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $("a").click(function(e) { $.getJSON('/mymethod', function(data) { //do nothing }); return false; }); </script> -
Simple search form in django
I have simple model (person with first name and last name) I have created admin for this model where i can add/edit/remove objects. My questions are: 1. Is it possible to use django forms to create simple form(without css and etc.) to search objects in db? (i choose field and then value to search) Or django forms used only for post requests? 2. How can i add AJAX functionality to the search form, so my page stay without reloading? Honestly i googled for two hours and didn`t find any information (or maybe i googled wrong questions) -
Updating a cached Django view in background
I have a Django view that does a time-consuming database read, so it is cached for 1 hour: import time from django.http.response import HttpResponse from django.views.decorators.cache import cache_page @cache_page(60 * 60) # 1 hr def my_expensive_view(request): time.sleep(5) return HttpResponse("Welcome to world's fastest app!") But this still means that some unlucky visitor once per hour gets hit with a 5-second load time. I'd instead like to set (update) the cache periodically in the background. (As mentioned by the docs, the cache used is caches["default"].) This essentially would tell my_expensive_view() when called from the URL mapper to always read from the cache, with the cache updated in the background.* However, this seems like it calls for a redesign given that Django caches live within a single process. I've seen libs such as django-background-tasks and redis-queue, but am wondering: is there a lightweight way to create this behavior using Django itself? *Granted, this might make the app user/client wait a tiny fraction of time if the cache-write operation is blocking, but here it is the function computation itself, not the cache-write, that is assumed to take up the most time. -
Custom user model auth form modification
I created own user model which is using e-mail as username and I decided to use own views for it. So I created the form for an user authentication. It works good, but there is one problem: it marks input type as "text" in HTML output, but I need it marked as "email" I've tried to override "__init__" function with updating widget attributes, but it works only with "placeholder", "id" and other tags, Modifying "username" didn't work as well class CustomUserAuthForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'type': 'email', 'placeholder': 'e-mail'}) self.fields['password'].widget.attrs['placeholder'] = 'password' self.username = forms.EmailField(widget=forms.EmailInput(attrs={'autofocus': True, 'type': 'email', 'placeholder': 'e-mail'})) I want to get: <input type="email" name="username" autofocus="" placeholder="e-mail" required=""> But I get: <input type="text" name="username" autofocus="" placeholder="e-mail" required=""> -
How to check if save() was called from django admin
I want to save two objects, one of them is related through ForeignKey('self'). I want to check if save() method was called through django admin or as recursive method from the save() itself. Since I want to save two instances of the object and not infinite amount of them. The model: prev_work = models.ForeignKey('self', on_delete=models.CASCADE, editable=False, null=True, blank=True) Code for saving: prev_work = Work(chapter=self.chapter, job=self.job, prev_work=self) prev_work.save() I'm expecting to save two objects but I don't know how to stop the program from calling save each time it comes to the end of the method. I done it through other means but still I would like to know how can I check if method was called from django admin. Thanks! -
How do I calucate the average across all my rows using two columns?
I'm using Python 3.7 and Django. I want to write a DJango query to give me the average across all rows in my table. My model looks like class StatByDow(models.Model): total_score = models.DecimalField(default=0, max_digits=12, decimal_places=2) num_articles = models.IntegerField(default=0) day_of_week = IntegerField( null=True, validators=[ MaxValueValidator(6), MinValueValidator(0) ] ) and I attempt to calculate the average like this everything_avg = StatByDow.objects.all().aggregate(Avg(Func(F('total_score') / F('num_articles')))) but this results in the error File "/Users/davea/Documents/workspace/mainsite_project/venv/lib/python3.7/site-packages/django/db/models/query.py", line 362, in aggregate raise TypeError("Complex aggregates require an alias") TypeError: Complex aggregates require an alias What's the right way to calculate the average?