Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 403 Forbidden error in django applicaion if user is logged-in in my website. I am not getting this error for anonymous user
I am new to django and ajax both. I am getting 403 error only if I am logged-in user. If am logged out same is working fine. Here is my ajax call: $("div#mainCont").on("click","#detail_icon", function(){ var _tickName = $(this).parent().attr('id'); var csrf = $("input[name=csrfmiddlewaretoken]").val(); $.ajax({ method: "POST", url: 'performance', data:JSON.stringify({ csrfmiddlewaretoken: csrf, ticker: _tickName }), success: function (data) { console.log(data) } }); This is my view: class PerformanceView(APIView): def get(self,request, format=None): queryset = Advice.objects.all() serializer = AdviceSerializers(queryset,many=True) return Response(serializer.data) def post(self, request): data=json.loads(request.body) print(data) queryset = Stocks.objects.filter(ticker=data["ticker"]) serializer = PerformanceSerializers(queryset,many=True) return Response(serializer.data) Thanks in advance -
Image is not showing up on my website (django)
I'am new to django. I wanted to upload an image but it doesn't show up on website. Instead it shows broken image icon. I tried to use load static block but it still doesn't work. My html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Website</title> </head> <body> <h1>Hello</h1> {% load static %} <img src="{% static 'webdev/static/webdev/images/images.jpg' %}"> </body> urls.py file: from django.contrib import admin from django.urls import path from homepage import views urlpatterns = [ path('', views.home_page, name='home'), path('admin/', admin.site.urls), ] views.py file: from django.shortcuts import render from django.http import HttpResponse def home_page(request, *args, **kwargs): return render(request, 'home.html', {}) -
Trying to display webcam footage on webpage from OpenCV (Django) while using docker
I am trying to create a facial recognition attendance system - My project framework is DJango and I have deployed it on docker, however I am running into issues trying to access the webcam through docker. This is my code: views.py: class mycamera(object): def __init__(self): self.frames = cv2.VideoCapture(0) def __del__(self): self.frames.release() def get_jpg_frame(self): is_captured, frame = self.frames.read() retval, jframe = cv2.imencode('.jpg', frame) return jframe.tobytes() def livefeed(): camera_object = mycamera() while True: jframe_bytes = camera_object.get_jpg_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jframe_bytes + b'\r\n\r\n') @condition(etag_func=None) def display_livefeed(self): return StreamingHttpResponse( livefeed(), content_type='multipart/x-mixed-replace; boundary=frame' ) urls.py: from users import views as user_views path('vidstream/', user_views.display_livefeed, name='vidStream') Error code when access 0.0.0.0:8000/vidstream/: web_1 | [04/Jan/2022 17:47:16] "GET /vidstream/ HTTP/1.1" 500 59 web_1 | [ WARN:0@3.508] global /io/opencv/modules/videoio/src/cap_v4l.cpp (889) open VIDEOIO(V4L2:/dev/video0): can't open camera by index web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/wsgiref/handlers.py", line 138, in run web_1 | self.finish_response() web_1 | File "/usr/local/lib/python3.10/wsgiref/handlers.py", line 183, in finish_response web_1 | for data in self.result: web_1 | File "/code/users/views.py", line 81, in livefeed web_1 | jframe_bytes = camera_object.get_jpg_frame() web_1 | File "/code/users/views.py", line 75, in get_jpg_frame web_1 | retval, jframe = cv2.imencode('.jpg', frame) web_1 | cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:976: error: (-215:Assertion failed) !image.empty() in function … -
Which subscription events to monitor for and which actions to take?
I have a subscription product that offers users monthly and annual subscriptions without free trials. All the docs I've seen kind of assume that I should know what types of actions to take when a new user subscribes to my service. The Stripe docs on provision and monitor say the minimum events to monitor are: checkout.session.completed invoice.paid invoice.payment_failed But then what do after monitoring for these events? In the dj-stripe docs on webhooks there are some clues as to what I should be doing including: Notifying the customer via email "Invalidating a cache" "Fire off a celery task" Is there anything else I should consider doing? And how do I know when to do what? Sorry if these are newb questions but this all just seems really subjective and I am just grasping for some guidance. Of course with dj-stripe I will be adding a lot of info to the database and this is all handled automatically. And of know that I can and should email the user when an invoice is paid or payment failed. But what about checkout.session.completed? Why is this a minimum event to monitor for? When a checkout session is completed Stripe redirects the user back … -
How do I integrate Neo4j DB with Django application?
I've tried this "https://neomodel.readthedocs.io/en/latest/getting_started.html#connecting" but Didn't mention which code is need to be placed in which file. I installed neomodel package but it's still not recognizing neomodel. Also, I've tried Py2neo and neo4django. But it's not working in any way. Can anyone please suggest me something helpful for doing it? Thanks in advance. -
django-simple-menu multiple active at a time
I've select submenu of an item. But it selects top most parents and selects anothers what I've selected. Just like below. Though I've selected purchase submenu but it shows 1st one and selected one -
In Django, how do I obtain ONLY the file path from a FileField in a form without loading the file into memory?
For a Django form, I like and need the FileField feature where it allows the user to navigate to a file locally and select it, but on the backend I only want to retain the absolute file path WITHOUT loading the file into memory first. I'm dealing with files in the 300 million+ records and do not want to do any data storage in memory, only obtain its path on the system. I tried FilePathField but it mandates pre-specifying a home directory for the files, which would not allow for the navigation feature of FileField. -
Django FOREIGN KEY constraint failed on OneToOneField
So I've created 2 classes of models. One has an OneToOneField and this class was referenced by the other using the ForeignKey field. It returns an error whenever I save it even in Django admin. Model classes class First(models.Model): sample_field = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True) class Second(models.Model): another_field = models.ForeignKey(First, on_delete=models.CASCADE, blank=True, null=True, related_name='sample_related_name') Error Message IntegrityError at /admin/management/group/add/ FOREIGN KEY constraint failed Thank you! -
JS appending element to parent not working
I am trying to add the new row to my table, but the I am unable to append a new row to the table. If i console log the elements individually I get the expect response can anyone help me find a solution to the problem, below is the code Html <tbody id="tableProduct"> {%for product in products %} <tr> <td scope="row" class="rowCounter"></td> <td>{{product.nameP}}</td> <td>{{product.brand}}</td> <td>{{product.price}}</td> </tr> {%endfor%} </tbody> JS class UI { //Adding the new Product to the display static addProduct(product){ const table = document.querySelector('#tableProduct'); const newRow = document.createElement('tr'); newRow.innerHtml = ` <td scope="row" class="rowCounter"></td> <td>Camera</td> <td>Sony</td> <td>10000</td> `; console.log(table.firstElementChild); //Placing the new row into the table //table.insertBefore(newRow, table.firstElementChild); //table.insertBefore(newRow, table.firstChild); table.appendChild(newRow); console.log(newRow.innerHtml) } } document.querySelector('#productForm').addEventListener('submit', (event)=>{ event.preventDefault(); UI.addProduct(newProduct); }) -
Change Celery task to run on-demand with clicking a button
I have a celery task that runs periodically and fetches some data for all companies that use a certain accounting service. I now need to make that task run on-demand with a click of a button, and fetch only the current company's data. Modified celery task: @APP.task def import_data_for_company(company_id): for integration in settings.INTEGRATIONS: if integration["owner"]["company_id"] == company_id: print("omlette du fromage") Current button in Django template {% for integration in settings.INTEGRATIONS %} {% if company.company_id == integration.owner.company_id %} <div class="button"> <a class="btn" href="#">Import Data</a> </div> {% endif %} {% endfor %} I need to trigger that task from the Django template and pass a company ID as an argument while doing it. But according to this comment, I cannot pass arguments from the Django template. Writing a custom template tag/filter seems not to help here. What are my options for calling that function via this button? Have to note, that I'm very green at this still. -
Does not understanding what does the Operating system security website means?
For the FYP of Operating System subject , i create the django website buy domain from namecheap use Heroku for hosting and SSL . But my teacher is saying something different which i'm not getting what he want me to build read the email of my teacher kindly guide me what i have to build to show him the email : Unfortunately i do not see your project satisfying the requirements of the OS security project.i understand u worked hard building the web Application using django .However the project was not to build the web application alone ,it was to build install the OS the entire web application slack and then use SSL, in addition it was to build the certificate Authority from what i can see, You used the django web framework on a heroku service (with all the slack pre -installed ). -
FiedDoesNotExist with ManytoMany field
I have an issue while running migrations, I get this error : django.core.exceptions.FieldDoesNotExist: Profile has no field named 'following yet I have defined the field in my model, what could be the issue ? below is my model : class Profile(TimeStampedModel, models.Model): last_name = models.CharField(_('Last Name'), max_length=150, null=True, blank=True) gender = models.CharField(_('Gender'), null=True, max_length=30, choices=GENDER_CHOICES, blank=True) following = models.ManyToManyField(User, related_name='following', default=None, blank=True) What could be the issue ? -
How to show all objects by one on one page?
I am doing quiz app. I want questions to appear on one page but by one. For example, we have 5 questions. I see the first of them, answer this and only after that I can see the next one and the previous one disappears. How to do it? Plz I need help. It is really important. Thanks everyone! -
How to build sass files with django
I'm completly new with Django and python (and alone as tech in my company, not able to ask help to previous dev). I have to maintain an existing app written in django still developing new services fully written in node, which is my most important task (and my skills). I have a problem that i have fixed some bugs in UX, fixing CSS mostly. And I don't understand how to build sass. In manage.py, when i ask the list of commands the only things which is related to my problem is "collectstatic" which seems to not build but just collect static files (good naming so) in one folder. And obviously, it doesn't resolve my problem. Any suggestion ? I'm lost in this big new thing. Many love on every body who can help me. Do you know if there is an integrated tool ? Do i need to use an external compiler which is just not documented ? -
Filter doesn't work with prefetch_related_objects - Django
I'm trying to write a view that prefetch its request content so I can speed up the request execution (3.5s instead of 3min when chaining requests). The goal is to fetch some rows (Exchange_pair objects) depending on a root model value in the prefetch path (connection.exchange_id). connections__wallets__currency__base_pairs ^ | |_______________________________| depends on the current connection's exchange_id View: @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def get_portfolio_view(request): portfolio_id = request.GET.get('id') # get portfolio + prefetch connections (and other things...) portfolio = Portfolio.objects.prefetch_related( 'connections__exchange', 'connections__wallets__currency__metadata__images' ).get(id=portfolio_id) for connection in portfolio.connections.all(): # build filter pairs_queryset = ExchangePair.objects.filter( exchange_id=connection.exchange_id, quote_id__in=["825", "2781", "3408", "4687"], last_price__isnull=False, ) # prefetch for related connection prefetch_related_objects( [connection], Prefetch('wallets__currency__base_pairs', queryset=pairs_queryset) ) data = PortfolioSerializer(portfolio).data return Response(data) Models: class Connection(models.Model): exchange = models.ForeignKey(Exchange, related_name='exchange', on_delete=models.CASCADE) portfolios = models.ManyToManyField(Portfolio, related_name='connections') # ... class ExchangePair(models.Model): id = models.IntegerField(primary_key=True) # CoinMarketCap id exchange = models.ForeignKey(Exchange, related_name='pairs', on_delete=models.CASCADE) # ... The code works in 90% of the cases. But in some cases: the queryset filter doesn't work and it retrieves ExchangePair objects with the wrong exchange_id. This makes no sense to me, I can't figure it out, seems like prefetch_related_objects() contains a bug. -
How to provide a source directory in the [tool.django-stubs] directive of a pyproject.tom file?
I'm using a src directory as root source directory in my django projects. I'm trying to perform pre-commit actions on those django projects, with mypy and django-stubs. Is is a way to say in pyproject.toml than the source root is in src/ ? For now, I've: [tool.django-stubs] django_version = "3.2" django_apps = ["account", "seniors", "seniors_app"] django_settings_module = "seniors.settings.dev" ignore_missing_settings = true ignore_missing_model_attributes = true pre-commit run --all ... ModuleNotFoundError: No module named 'seniors' When I put django_settings_module = "src.seniors.settings.dev", I've some errors later on importing the other modules ( account...) Have you any ideas ? For sure I don't want to change my project layout ! Thanks ! -
Bootstrap 5 site header works on desktop but not on mobile
I am following the great Django series by Corey Schafer (https://www.youtube.com/playlist?list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p). Given that Bootstrap 5 has emerged since it's creation, i'm attempting to utilize it for my modified creation. The problem I am finding is that the header below is functioning properly desktop site (note: I've only activated the register.html link so far as I progress through the course), but the "hamburger" that should be created is inactive and unclickable on the mobile site. Here is the relevant file creating the header: base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'The6ixDjango/main.css' %}"> {% if title %} <title>{{ title }}</title> {% else %} <title>The6ixClan</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'The6ixDjango-home' %}">The6ixClan</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'The6ixDjango-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'The6ixDjango-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="{% … -
File not in request.FILES but in request.POST I'm using htmx to make post request
I have snippet of inputs that I render to the html page when a condition is met, everythings works appropriately except for the input with type file, I want to upload the files when a change has occured but the file object is not in request.FILES, it's in request.POST now I don't mind it being request.POST but the files is displayed as 'multiple': ['[object File]'] My partial template <div class="my-2"> <div id="uploaded"></div> <p class="lead">{{question.prompt}}</p> <input name="multiple" type="file" accept="image/*, .pdf" id="image_{{question.id}}" {% if question.required %}required{% endif %} {% if question.disabled %}disabled{% endif %} class="form-control" placeholder="{{question.placeholder}}" hx-post="{% url 'survey:file_multiple' %}" hx-trigger="change"> <input type="hidden" name="filemultipleId" value="{% if question.form_input_type == 'file-multiple' %}{{question.id}}{% endif %}"> </div> I am not rendering the form with django form as it will be difficult and near impossible to achieve the dynamicity I am looking for request.POST QueryDict <QueryDict: {'csrfmiddlewaretoken': ['TiLZFEWw88cqItD8MABv6lZKYDrNaVxGF4ZMDOV3sK43540z6uOcrx5uQO6iYldA', 'date': [''], 'dateId': ['20', '5'], 'multiple': ['[object File]'], 'filemultipleId': ['18'], 'fileId': ['17']}> Traceback Internal Server Error: /file-multiple/ Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super().__getitem__(key) KeyError: 'multiple' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/tomms/.local/share/virtualenvs/web-app-QB9eq0sY/lib/python3.9/site-packages/django/core/handlers/base.py", line … -
Deploy Django app with Nginx, Gunicorn, uvicorn, PostgreSQL
My app works on development mode (I run from a container with specified variable RTE=dev docker-compose up) I need to deploy the app to my domain and I have all settings in place for it (Nginx, Gunicorn, uvicorn, PostgreSQL). When I docker-compose up in Production mode I do not get any errors and I can't seem to find out where the issue is. settings.py class RuntimeEnvironment(Enum): """docstring: environment variables""" dev = 1 test = 2 prod = 3 RTE = RuntimeEnvironment[os.environ['RTE']] (...) if RTE is RuntimeEnvironment.dev: SECRET_KEY = 'django-insecure-l)lj4%c6(3v5r!0b9eac&0%%_500%ct4x1nbf5j5qsarmtn0#d' else: SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] (...) if RTE is RuntimeEnvironment.dev: DEBUG = True ALLOWED_HOSTS = [] else: DEBUG = False ALLOWED_HOSTS = ['pbstyle.dk', 'https://pbstyle.dk/'] nginx.conf upstream app_upstream { server app:8080; } server { listen 80; listen 443; server_name pbstyle.dk; location /static/ { alias /static/; } location /media/ { alias /media/; } location / { proxy_set_header Host $host; proxy_pass http://app_upstream; } } docker-compose version: "3.8" services: db: image: postgres:13-alpine volumes: - db_data:/var/lib/postgresql/data - ./dbscripts/:/dbscripts/ env_file: - db_${RTE}.env app: build: . ports: - 8000:8000 - 8080:8080 env_file: - db_${RTE}.env volumes: - .:/app/ - static:/static/ - media:/media/ depends_on: - db nginx: build: nginx/ ports: - 443:443 - 80:80 volumes: - ./ngin/${RTE}/conf.d/:/etc/nginx/conf.d/ - ./certs/:/etc/letsencrypt/ - static:/static/ … -
Django is not recongizing a users password when login is attempted
When trying to create a simple web page with login and sign up i ran into the issue of django not recognzing the created user. In views.py i created a simple message that displays "Incorrect password or email" if user does not exist. I created a user and made sure that the password was correct when i inputed it into the login form however it still gave me the message of "Incorrect password or email". Instead of redirecting to home like a created user should it errored and i could not figure out why it is not accepting the password/email in the form. views.py from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.models import User def home(request): return render(request, 'home.html') def signup(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] myuser = User.objects.create_user(email, password) myuser.email = email myuser.password = password myuser.save() messages.success(request, "Your account has been successfully created ") return redirect('signin') return render(request, 'signup.html') def signin(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email = email, password = password) if user is not None: login(request, user) email = user.email messages.success(request, "Successfully Logged In") return … -
Page not found, my template is there but I see an Page Not Found error
I saw different Q&A about this error, but I couldn´t find one similar to my case. I´m trying to create "read templates" from two classes, but I can´t. I already created the views and the models, but the templates don´t work. views: def readCoberturas(request): cobert = Coberturas.objects.all() dicCoberturas = {"Coberturas": cobert} return render(request, "AppURC/readCoberturas.html", dicCoberturas) Model (Coberturas): class Coberturas(models.Model): tipo = models.CharField(max_length=20) numeroPoliza = models.IntegerField() fechaContratacion = models.DateField() fechaVigencia = models.DateTimeField() detalle = models.CharField(max_length=40) def __str__(self): return f"Tipo de Cobertura: {self.tipo} | Poliza n°: {self.numeroPoliza} | Fecha alta: {self.fechaContratacion} | Vigencia hasta: {self.fechaVigencia} | Detalle: {self.detalle}" Url: path('readCoberturas/',views.readCoberturas, name='ReadCoberturas'), Template: {% load static %} {% block contenido %} {% for C in Coberturas %} <li>{{ c }}</li> {% endfor %} {% endblock %} I hope I have made this sufficiently clear. Thanks to all! -
Django - See exact value of foreign key import export
I have some models and some foreign keys assigned to them. What I want is to get the Foreign keys exact content rather than the ID of the foreign key. What I can do ? my models from django.db import models class MonkAttributes(models.Model): id = models.AutoField(primary_key=True) head = models.CharField(max_length=55) cloth = models.CharField(max_length=55) mouth = models.CharField(max_length=55) skin = models.CharField(max_length=55) eyewear = models.CharField(max_length=55) background = models.CharField(max_length=55) class MonkFiles(models.Model): id = models.AutoField(primary_key=True) uri = models.CharField(max_length=255) type = models.CharField(max_length=25) class MonkCreators(models.Model): id = models.AutoField(primary_key=True) address = models.CharField(max_length=255) share = models.IntegerField() class MonkProperties(models.Model): id = models.AutoField(primary_key=True) files = models.ForeignKey(MonkFiles, on_delete=models.CASCADE) category = models.CharField(max_length=55) creators = models.ForeignKey(MonkCreators, on_delete=models.CASCADE) class MonkDetailsModel(models.Model): id = models.AutoField(primary_key=True) dna = models.CharField(max_length=25) name = models.CharField(max_length=50) symbol = models.CharField(max_length=10) description = models.CharField(max_length=255) seller_fee_basis_points = models.IntegerField() image = models.CharField(max_length=255) external_url = models.URLField() attributes = models.ForeignKey(MonkAttributes, on_delete=models.CASCADE) properties = models.ForeignKey(MonkProperties, on_delete=models.CASCADE) def __str__(self): return self.name or '' exported json file is like this: I want to get the exact content of attributes and properties [ { "id": 1, "dna": "010001001110", "name": "Decentralized Monks Test Item", "symbol": "SYM", "description": "This image shows the true nature of Monks.", "seller_fee_basis_points": 100, "image": "https://ipfs.io/ipfs/QmNjsxLtyK5ZpmoyZFaPKFTXeDAmGQDq2vSSCfNXA279SB", "external_url": "http://0xmonks.com", "attributes": 1, "properties": 1 } ] -
Production web app - Django with Djongo or Flask with Mongo?
I am working on a new web app that will store data about transactions of multiple companies. As companies from various industries sell various products they need different columns (attributes) to describe each product. For example, food products require Best before date column, but books don't require it and instead they need Author and Genre columns. My way of thinking is that it is hard and inefficient to store this kind of data in relational, SQL database. Instead, I think that NoSQL such as MongoDB will be perfect for this case. Please correct me if I'm wrong. My question is: for such web app, which from the below options should I use? Django app with Djongo, which is an unofficial connector between Django and MongoDB Flask with MongoEngine Flask with PyMongo Other NoSQL technology. Maybe NoSQL is a bad choice in my case and should be avoided? My concerns are: Not sure if Djongo should be used in production, as support for it can be dropped any time (I expect this web app to last a few years) and I don't know if Djongo is reliable Not sure if Flask isn't too 'poor' and 'simple' for an app that is … -
Annotate QuerySet with the maximum of a date field and a manually created date
I have the following model: class Item(models.Model): last_used = models.DateTimeField() created_at = models.DateTimeField() I'm trying now to look at the average "lifetime" of items per month. Lifetime is how many days items are used, on average. I can calculate the overall average with the following: from django.db.models import IntegerField, F, Avg from django.db.models.functions import Cast, ExtractDay, TruncDate items = Item.objects.annotate(days_used=Cast(ExtractDay(TruncDate(F('last_used')) - TruncDate(F('created_at'))), IntegerField())+1) avg = items.aggregate(Avg('days_used'))['days_used__avg'] Now when I want to calculate this per month, I would like to annotate the query with a new field that is the maximum of created_at or the beginning of the month in question. This is needed so that the maximum lifetime value for all months is the number of days in that month. There's a function, Greatest that I think could be used for this, but I'm not sure how. Assuming we're interested in December, 2021, this is what I have at the moment: target_month = 12 items = items.annotate(created_max=Greatest(TruncDate(F('created_at')), TruncDate(F(timezone.datetime(2021, target_month, 1))) But using timezone.datetime is causing an error: AttributeError: 'datetime.datetime' object has no attribute 'split' NOTE: I'm aware that last_used may cause the value to go over the number of days but that's another issue we're tackling. -
How to get around the django Error : raw query must include primary key
Is there a way to run a query on Django without using the Primary key of the table? in the following code, I have a query that, at least I think, must be used only with SELECT DISTINCT p.type without adding the primary key of the table - in this case, the PK is NAME. Every time I run the code I get the same Error - raw query must include primary key is there a way to get around that? Code: def Query_result(request): AttackThreshold_res = request.POST.get('AttackThreshold') PokemonCount_res = request.POST.get('PokemonCount') sql_threshold_res = Pokemons.objects.raw(""" SELECT DISTINCT p.type FROM pokemons p INTERSECT SELECT DISTINCT p1.type FROM pokemons p1 WHERE p1.attack > %s INTERSECT SELECT DISTINCT p2.type FROM pokemons p2 GROUP BY ( p2.type ) HAVING Count(p2.type) > %s """, [AttackThreshold_res, PokemonCount_res]) return render(request, 'queries.html', {'sql_threshold': sql_threshold_res})