Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: get() missing 1 required positional argument: 'id'; RequestFactory
I'm testing a view UserProfilePage with a mock request object using RequestFactory. An error is being raised when invoking the GET handler; saying a positional argument is missing. Yet there are not positional arguments within the request. What would be raising this error? Traceback (most recent call last): File "C:\..\site-packages\django\test\testcases.py", line 1201, in setUpClass cls.setUpTestData() File "C:\..\authors\test\test_views.py", line 110, in setUpTestData request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) File "C:\..\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\..\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) TypeError: get() missing 1 required positional argument: 'id' class TestViewUserQuestionsPostedPage(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("ItsMe") viewer = get_user_model().objects.create_user("ItsYou") request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) cls.view = UserProfilePage.as_view()(request).view_class cls.view_context = cls.view.get_context_data() def test_viewed_profile_of_user(self): self.assertIsInstance(self.view, Page) self.assertIn('user', self.view_context) self.assertEqual(self.view_context['object'], self.user) class Page(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data() context['search_form'] = SearchForm() return context class UserProfilePage(Page, SingleObjectMixin): model = get_user_model() pk_url_kwarg = "id" def get(self, request, id): return HttpResponse("Hi") authors_patterns = ([ path("<id>", av.UserProfilePage.as_view(), name="profile") ], "authors") urlpatterns = [ path("users/", include(authors_patterns, namespace="authors")) ] -
How can I add query paramater with html form?
Now I'm making a web app with django. I want to put more than 2 query paramaters into my URL, but if I put some keywords into my search box and send them, the query paramater will show only these keywords. For example, current URL is like below. https://example.com/jobs?area=SYDNEY If I search something, it becomes below. https://example.com/jobs?query=something This is not what I want. What I want is https://example.com/jobs?area=SYDNEY&query=something How can I do it? <form action="" method="get"> <input type="text" name="query" value="{{ request.GET.query }}"><input type="submit" value="Search"> </form> -
HTMX sortable works only once, rendering makes it disabled
I am referring to BugBytes channel on YouTube about sortable menu with Django. (Django and HTMX #6 (part 1) - Building a Sortable Drag and Drop Interface ) https://www.youtube.com/watch?v=V-f_yYKUJo8 (Django and HTMX #6 (part 2) - Building a Sortable Drag and Drop Interface ) https://www.youtube.com/watch?v=5Fuwo4tVXmE Some people got stuck by the same issue but found a clue getting through it. I couldn't have any complication. Same question found in StackOverflow here."Sortable JS breaks upon htmx rendering a partial" And I don't think that Answer seems to show any solutions. In my case, following the BugBytes tutorial video and the repository, I made the following Django files. books.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>List Books</title> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://unpkg.com/htmx.org@1.7.0" integrity="sha384-EzBXYPt0/T6gxNp0nuPtLkmRpmDBbjg6WmCUZRLXBBwYYmwAUxzlSGej0ARHX0Bo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script> </head> <body> <section id="book_list"> {% include 'list_books.html' %} </section> <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) htmx.onLoad(function(content) { var sortables = content.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable = sortables[i]; new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); } }) </script> </body> </html> list_books.html {% csrf_token %} <form class="sortable" … -
Unable to add initial/auto tags tags using tagulous by post-save signal
I am Unable to add initial/auto tags tags using tagulous by post-save signal. I am working on a project which contains smart phones Brands, models, and their specific firmware files. What I want to do is to while posting a table I want to copy brand name model name and the files title into the tags field along with presets of tags. To do so I am using post save signals from django and it outputs the following: I am trying to do add initial tags and also want to copy the title model brand fields to tags but code throughs below error def tag_set(sender, instance,*arg, **kwargs): ans= array_tag(instance) instance.Tags.add(ans) post_save.connect(tag_set, sender=resource) def array_tag(instance): return [instance.title ,instance.desc,instance.size, instance.Brand.title ,instance.Model.title ,instance.Categories.title] Error 'list' object has no attribute 'pk' below are the code settings i used Models.py class Skill(tagulous.models.TagTreeModel): class TagMeta: initial = [ "Python/Django", "Python/Flask", "JavaScript/JQuery", "JavaScript/Angular.js", "Linux/nginx", "Linux/uwsgi",] space_delimiter = False autocomplete_view = "resource_skills_autocomplete" class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(max_length=200, null=True,blank=True) Tags = tagulous.models.TagField( to=Skill, help_text="This field does not split on spaces" ) Settings.py SERIALIZATION_MODULES = { 'xml': 'tagulous.serializers.xml_serializer', 'json': … -
I want to use like button with ajax but I have a problem.The error I get when I click the like button(Not Found: /like)
POST http://127.0.0.1:8000/like 404 (Not Found) I am quite a novice at this. I think the error is due to the url redirection, but the urls I use do not work, what should I use? What I'm trying to achieve is to like the post without refreshing the page when I click the like button. models.py class Post(models.Model): likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') views.py @ login_required def like(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('postid')) post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) urls.py urlpatterns = [ path('like', like, name='like'), ] myscript <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> post_detail.html {% if request.user.is_authenticated %} <div class="pr-2"> <span class="" id="like_count">{{post.like_count}}</span> <button class="btn btn-link text-dark p-0 border-0 btn-outline-light" id="like-button" value="{{post.id}}"> <svg width="1.5em" height="1.5em" viewBox="0 0 16 16" class="bibiheart"fill="currentColor"xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd"d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 … -
running an old django project on a new database
I have a django project code, there are 10 applications in it, and about 50 models that have relationships (foreign keys) with each other. There are no migration files. I need to run this project. The database is empty. Tell me, pls, what should be my steps for the correct launch of the project? Are the following commands sufficient? python manage.py makemigrations python manage.py migrate python manage.py runserver -
How to include model-choice-iterators into views
I have been looking at form fields in the django documentation Iterating relationship choices but finding it a little hard to understand. I want to develop a form field with an iterator whereby, In the select I get the title of the cruise, and in the options for data-ship_name I get the according ship names, and for text I get the destinations. However, I am not sure how to implement the form into the views/html. Here's what I have tried: models.py from django.db import models class Cruises(models.Model): id = models.CharField(db_column='ID', primary_key=True, max_length=200) # Field name made lowercase. title = models.CharField(max_length=200, blank=True, null=True) ship_name = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'items' def __str__(self): return self.title class Destination(models.Model): location = models.ForeignKey(Cruises, on_delete=models.CASCADE, blank=True, null=True) destination = models.CharField(max_length=200, blank=True, null=True) views.py from django.shortcuts import render from .models import Cruises def basic(request): #form_destination = Cruises long_list = Cruises.objects.values('title', 'ship_name') return render(request, 'cruises/basic.html', context = {'long_list':long_list}) forms.py from django import forms from cruises.models import Cruises, Destination class CruiseSelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex, attrs) if value: option['attrs']['data-ship_name'] = value.instance.ship_name return option class destinationForm(forms.ModelForm): class Meta: model = Destination … -
In a Django template, how do you refer to a static image using a variable?
The following is what I have in my Django template: {% extends 'base.html' %} {% load static %} {% block content %} {% for department in departments %} <img src="{% static 'store/images/product_name.jpg' %}" alt="product photo"> <p>{{ department.name.title }}</p> {% endfor %} {% endblock content %} The same image displays for each iteration, but I want each element in the for loop to display its own image. The path to the each image is stored as a value in the "image_location" key for each item. This is what I've tried (the key, "department.image_location", has the value "store/images/<product_name>.jpg"): {% extends 'base.html' %} {% load static %} {% block content %} {% for department in departments %} <img src="{% static department.image_location %}" alt="product photo"> <p>{{ department.name.title }}</p> {% endfor %} {% endblock content %} I have also tried: "{% static {{department.image_location}} %}" I have also set the key value to "product_name.jpg" and then trying: "{% static /store/images/ %}{{department.image_location}}" None of these work. Is there a way to use a key's value to show a static image? -
__init__() missing 1 required positional argument: 'get_response' error on Django HttpOnly JWT solution
I currently have a Django setup that followed the guide below. Pretty much, it's a workaround that allows for HTTPOnly cookies to be used with Django Rest Framework JWT authentication. It worked fine in Django 3.2, but I'm attempting to upgrade to Django 4, and I'm now running into the error below How to store JWT tokens in HttpOnly cookies with DRF djangorestframework-simplejwt package? Error: __init__() missing 1 required positional argument: 'get_response' I'm still a bit new to Django and DRF, so I have no idea what could be going on. -
Form Issue trying to add a word to an URL
This is my form: <form method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> How can I append a word after the last character of the next link: http://127.0.0.1:8000/saturday/ Sorry and Thank You. -
ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must be in YYYY-MM-DD format. Is there a way to change the date format?
I'm scraping a website for data to include in my project and while fetching the date it comes in a mm-dd-yyyy format like so "July 9, 2022". Is there a way to bypass this and avoid the error? for test_job in final_jobs: newjob = Jobs.objects.create( title = test_job['title'], location = test_job['location'], date_posted = test_job['date_posted'], closing_date = test_job['closing_date'], ) the error: ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must be in YYYY-MM-DD format. -
i set null = true and blank = true but still get "django.db.utils.IntegrityError: (1048, "Column 'massenger_name' cannot be null")"
im trying to run my page but i get this error "django.db.utils.IntegrityError: (1048, "Column 'massenger_name' cannot be null")" and i makemigrations and imgrate again but still i have same problem and my database is mysql this my models.py from django.db import models # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=255,null=True,blank=True) action_time = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.massenger_name) and this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input) name_in_model.save() return render(request , 'index.html') and this my index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static 'CSS/style.css' %}"> </head> <body> <div id="form"> <form class="row" method="POST"> {% csrf_token %} <div class=""> <input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name" required> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button> </div> </form> </div> </body> </html> and this my setting.py """ Django settings for Eid_G project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path … -
Google Login failed {error: 'popup_closed_by_user'} on Google login in Django
I am aware that this question has been asked multiple times. However, they were usually issues related to localhost. I have a django site where I used react for the frontend. Everything runs perfectly when I have my react at port 3000 and django at 8000. Even the google login But when I run npm run build I pasted the build folder in the django root and make all the changes in settings.py Now I directly went to localhost:8000 this error shows up on google login Manifest: Line: 1, column: 1, Syntax error. Google Login failed {error: 'popup_closed_by_user'} sometimes its even a 403 error. I tried it on both localhost and heroku and it won't work. I've been stuck on this for days. Would appreciate some help -
Hide and show elements inside Django HTML template
I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $(".button_order").click(function(){ $(".myorders").show(); $(".myproducts").hide(); $(".mysupplier").hide(); }); $(".button_supplier").click(function(){ $(".myorders").hide(); $(".myproducts").hide(); $(".mysupplier").show(); }); }); </script> syle.css looks like; .myorders, .myproducts, .mysupplier{ font-size: 25px; display: none; } This works perfectly fine until I use normal data like; <body> {%block content %} <button class="button_order" >ORDERS</button> <button class="button_supplier" >SUPPLIER</button> <p class="myorders" > This is my order </p> <p class="mysupplier"> my supplier is cool </p> </body> But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part. <p class="myorders"> <!-- {% for element in orders %} {% for key,val in element.items %} <ul><li>{{key}}:{{val}}</li></ul> {% endfor %} <hr class="new1"> {% endfor %} --> </p> I should get product data from data base only when PRODUCT button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data. my views.py looks like from django.shortcuts import render client = MongoClient("mongodb://localhost:27017/") db=client.inventory_data def home(request): collection_data_1 = db['orders'] … -
How to show username in django admin form for the connected model?
I have two models one is user model and another one is cars model. class User(models.Model): id = models.BigAutoField(primary_key=True) username = models.CharField(max_length=50, verbose_name="User Name") class Cars(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cars') Now on /admin/app/cars/1/change/ page i want to see the username as a normal text in that form below the dropdown of users. I tried with inline stack but that didn't worked, and throwing error, User has to foreign key to Cars. -
Stripe MetaData Working Properly But Not Showing Up on Stripe Dashboard
I've implemented Stripe checkout on a Django app and it's all working correctly except that it's not showing up on the Stripe Dashboard, even though it's showing in the event data on the same page. Have I formatted it incorrectly or am I overlooking something obvious? This is how I added meta data: checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items = line_itemz, metadata={ "payment_type":"schedule_visit", "visit_id":visit_id }, mode='payment', success_url= 'http://localhost:8000/success', cancel_url = 'http://localhost:8000/cancel',) Here is a screenshot of the Metadata section empty, but in the events the Metadata is there as it should be: Again I can access the metadata every where else but would like it to show up on the dashboard so my team can more easily access that information. -
Use data as Django response field name?
I have the following data class: class IndustryScore: industry: str score: Decimal class Foo: ... industry_scores = List[IndustryScore] I want the response to be something where the key of the response is the industry and the score is the value. For example: { "automotive": 5.1, "construction": 10.0, "technology": 8.6, } Right now I have a serializer like this: class IndustryScoreSerializer(serializers.Serializer): industry = serializers.Charfield() score = serializers.DecimalField() but the response is something like this instead: [ { industry: "automotive", score: 5.1 } ] How can I change the serializer so I get the expected JSON structure? -
Docker-compose volume not creating new directory
i'm writing docker compose yml file and i have problem with setting volume that would create new directory. This is my directories tree ├── backend │ ├── projectname │ ├── manage.py │ └── requirements.txt ├── docker-compose.yml ├── Dockerfile └── README.md Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 WORKDIR /app COPY backend/requirements.txt . COPY backend/ . RUN pip install -r requirements.txt docker-compose.yml version: "3.9" services: app: build: . volumes: - ./backend:/app ports: - 8000:8000 command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=name - POSTGRES_USER=name - POSTGRES_PASSWORD=pass container_name: postgres Problem is when i'm running docker-compose, then it creates no data/db directory with database data. -
Unittest for close_old_connections
On current project we had a problem with recovery a connection to DB, after some problems with a DB pod. We found a solution for this problem: from functools import wraps from django import db def cleanup_db_connections(func): @wraps(func) def wrapper(*args, **kwargs): try: r_val = func(*args, **kwargs) except db.OperationalError as e: db.close_old_connections() r_val = func(*args, **kwargs) return r_val return wrapper Now we want to create a unittest for this decorator and solution in general and we faced with new problem: We can reproduce the problem with connection (connection.close() or connection.creation.destroy_test_db()) but our solution, which works in the application, does not solve the problem in the test. If I understand correctly, it depends on Django - in unittest its doesn`t recover connection after close. I have a two questions: Am I right in understanding at the problem? Could I make Django recover connection? Is there a way for me to test this decorator? -
file.write returning two \n\n
I have a markdown file called CSS.md: # CSS CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page. My main goal is to have a input field where I can edit this file, save it, and return the web page with the new file. Here's the code: def edit_page(request, page): data = {'edit':''} with open(os.path.join('.\entries',f'{page}.md'), 'r', encoding='utf-8') as editing_page: for line in editing_page.readlines(): data['edit'] += line edit = EditPage(data) if request.method == 'GET': return render(request, 'encyclopedia/edit_page.html', { 'edit':edit, 'page':page, }) elif request.method == 'POST': form = EditPage(request.POST) if form.is_valid(): content = form.cleaned_data['edit'] with open(os.path.join('.\entries',f'{page}.md'), 'w', encoding='utf-8') as edited_page: edited_page.write(content) # FIXME ta duplicando o \n return HttpResponseRedirect(f'/wiki/{page}') When I run print(editing_page.readlines()) before clicking the submit button (POST method): ['# CSS\n', '\n', 'CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page.\n'] After clickin the submit button, even without any alteration, it duplicates the \n: ['# CSS\n', '\n', '\n', '\n', 'CSS is a language that can be used to add style to an [HTML](/wiki/HTML) page.'] I tried to do writelines but it did not work... -
The difference between
what is the difference between request.post.get('blog','') AND request.post.get('blog') I am not able to figure out what is the difference between this two and they what they return, iT will be great help if someone tell me -
Modify patch.object variable to test
Hey guys need some general guidance. Im trying to write some tests for a django app but im a bit confused how mock/patch works. If i use patch.object on a function. and run a test how do i then change a variable in it to do another test. For eg. if my function was simple like def myfunc(potato): number = count(potato) if number >0: print('foo') else: print('bar) How do I test both if number was greater than 0 or less than 0? (My real function takes a queryset and filters a model to find out the count then uses the count in a if/else.). Bonus question I am also trying to test that a email was sent but when I try to use use: self.patchobject.assertEqual(len(mail.outbox),1) I am getting an assertion error.. -
Django import into many to many relationship with custom through table
I am not sure the proper way to import using django-import-export tsv files into many to many relationship tables. What I have done is create a books table, a genre table and a bookgenre through table which contains the foreignkeys to each of the other tables. So what I have is: class Book(models.Model): title = models.CharField(max_length=255) class Genre(models.Model): genre = models.CharField(max_length=64) class BookGenre(models.Model): book_id = models.ForeignKey('Book', on_delete=models.CASCADE) genre_id = models.ForeignKey('Genre', on_delete=models.CASCADE) Then I import all three tables and the relationships are working but I can't figure out a way to make a view or template that works effectively. I am thinking there must be a better way to create a many to many relationship and import data into it. Any Ideas? -
How to use data from postgresql in django?
I have switched from sqlite to postgresql following Django: What are the best practices to migrate a project from sqlite to PostgreSQL the fourth answer. Here are my updated settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'scraper', 'USER':'user', 'HOST':'localhost', 'PORT':5432, } } However, I cannot seem to find/grab any of the data from my database. Here's some example data from the database: I have tried python manage.py dumpdata But get this: [{"model": "auth.permission", "pk": 1, "fields": {"name": "Can add log entry", "content_type": 1, "codename": "add_logentry"}}, {"model": "auth.permission", "pk": 2, "fields": {"name": "Can change log entry", "content_type": 1, "codename": "change_logentry"}}, {"model": "auth.permission", "pk": 3, ... I wanted to upload that data based on my current app: models.py from django.db import models class Cruises(models.Model): title = models.CharField(max_length=200) #ship_name = models.CharField(blank=True, null=True,max_length = 200) def __str__(self): return self.title views.py from django.shortcuts import render #from .models import Cruises from .models import Cruises def basic(request): #form_destination = Cruises long_list = Cruises.objects.values('title') return render(request, 'cruise_control/basic.html', context = {'long_list':long_list}) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.basic, name = 'basic') ] basic.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Cruises</title> </head> <body> <h1> Cruise Control </h1> <form action="/action_page.php"> <label for='destination'>Destination</label> <input … -
Django Extract functions always groups by Day
I have DateTimeField - snap_at. I need GROUP PY this field by Day, Week, Month etc. I try it qs .annotate(month=ExtractMonth('snap_at')) .values('month') .annotate( .... ) .annotate( .... ) .values( ... ) ) But, judging by the output, Django made a grouping by Days. SQL output SQL - SELECT COUNT(*) FROM (SELECT "wb_stockshistory"."snap_at" AS "col1", EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC') AS "month", COUNT(DISTINCT "wb_stockshistory"."good_id") AS "goods_count", COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "goods_sales_count", SUM("wb_stockshistory"."sales") AS "total_sales", COUNT(DISTINCT "wb_good"."brand_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "brands_sales_count", COUNT(DISTINCT "wb_good"."supplier_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "suppliers_sales_count", SUM("wb_stockshistory"."revenue") AS "total_revenue", ROUND(AVG("wb_stockshistory"."price"), 2) AS "avg_price", ROUND(AVG("wb_stockshistory"."rating"), 2) AS "rating", COUNT(DISTINCT "wb_good"."brand_id") AS "brands_count", COUNT(DISTINCT "wb_good"."supplier_id") AS "suppliers_count", ROUND((SUM("wb_stockshistory"."feedbacks") / COUNT(DISTINCT "wb_stockshistory"."good_id")), 2) AS "feedbacks", ROUND((SUM("wb_stockshistory"."revenue") / COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0)), 2) AS "avg_sales" FROM "wb_stockshistory" INNER JOIN "wb_good" ON ("wb_stockshistory"."good_id" = "wb_good"."id") GROUP BY EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC'), "wb_stockshistory"."snap_at") subquery SQL - SELECT "wb_stockshistory"."snap_at", EXTRACT('month' FROM "wb_stockshistory"."snap_at" AT TIME ZONE 'UTC') AS "month", COUNT(DISTINCT "wb_stockshistory"."good_id") AS "goods_count", COUNT(DISTINCT "wb_stockshistory"."good_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "goods_sales_count", SUM("wb_stockshistory"."sales") AS "total_sales", COUNT(DISTINCT "wb_good"."brand_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) AS "brands_sales_count", COUNT(DISTINCT "wb_good"."supplier_id") FILTER (WHERE "wb_stockshistory"."sales" > 0) …