Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload Large video file to Azure Blob using Javascript. for now file size should be 150GB as the max
function uploadBlobFromText() { // your account and SAS information var sasKey ="*******************"; var blobUri = "*************************"; var blobService = AzureStorage.File.createFileServiceWithSas(blobUri, sasKey); var files = document.getElementById('id_video_file').files; var file = files[0]; var customBlockSize = file.size> 1024.1024*32 ? 1024*1024 *4 :1024 *512 blobService.singleBlobPutThresholdInBytes = customBlockSize; var finishedOrError = false; var speedSummary = blobService.createFileFromBrowserFile('containername', 'directoryname', file.name, file, {}, function(error, result, response)) { finishedOrError = true; if (error) { console.log(error);} else {alert('Upload successfully!'); } }); };` this is i have done but giving me error StorageError {name: "StorageError", message: "An HTTP header that's mandatory for this request i…ae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z", code: "MissingRequiredHeader", headername: "x-ms-blob-type", statusCode: 400, …} name: "StorageError" message: "An HTTP header that's mandatory for this request is not specified.↵RequestId:bf55651e-401e-0103-7bae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z" code: "MissingRequiredHeader" headername: "x-ms-blob-type" statusCode: 400 requestId: "bf55651e-401e-0103-7bae-1366fb000000" stack: "StorageError: An HTTP header that's mandatory for this request is not specified.↵RequestId:bf55651e-401e-0103-7bae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z↵ -
Django - Aggregate with a Case where the values are not from the database
Let me start with saying that: Yes I know that I can just save the ratings as number to my database and I know it would be a lot easier that way. Nonetheless, if I was doing it this way(I am, I shouldn't be most probably but I am) so I want to solve it with the current setup as is, with only adjusting the rating_point property if possible. utils.models.Choices is basically a wrapper around regular python dictionaries, can share that too if needed. Tried to keep the code as clean as possible and am showing you all as little as possible to avoid any confusion, still seems large but I think all has to be here to easily debug it. from django.db import models from django.db.models import Avg, When, Case, Value from mptt.models import TreeForeignKey from utils.models import Choices class Product(CommonFields, ProductRelatedMixin): @property def rating_point(self): comment = self.comments.model return self.comments.aggregate( whatever=Avg( Case( *[ When( rating=rating, then=Value(comment.rating_points_map.get(rating)) ) for rating in comment.ratings.choices ], output_field=models.IntegerField() ) ) ) class Comment(CommonFields): ratings = Choices( POOR="POOR", OKAY="OKAY", GOOD="GOOD", AMAZING="AMAZING", EXCELLENT="EXCELLENT", ) rating_points_map = { ratings.POOR: 1, ratings.OKAY: 2, ratings.GOOD: 3, ratings.AMAZING: 4, ratings.EXCELLENT: 5, } user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='comments') product = models.ForeignKey('Product', … -
Django webapplication displaying source code in chrome, but working fine in firefox
In search portal of django, when the button search is clicked, it's displaying results in source code in chrome and newer versions of firefox. But, it's working fine in older versions of firefox. Is there anything to be done with code -
Django showing unnecessary information
I got my python script to run the way I want it, but for some reason I am getting some info showing up that I do not want. In this image, I dont want anything printed before the word "Acute". My python code is getting a wikipedia article, summarizing it, and printing the best sentences. However, no where do I have code to print the other stuff that is showing up. Once the generate button is clicked (which in this case it is) Here is my code: urls: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.urls import path from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.button), url(r'^output',views.output,name="script"), url(r'^external',views.external), ] Views.py from django.shortcuts import render import requests from subprocess import run,PIPE import sys def button(request): return render(request,'index.html') def output(request): data=requests.get("https://regres.in/api/users") print(data.text) data=data.text return render(request,'index.html',{'data':data}) def external(request): out=run([sys.executable,'textSummary.py'],shell=False,stdout=PIPE) print(out) return render(request,'index.html',{'data1':out}) index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Card layout</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet"> </head> <body> <h1 class="StorySpinner"><u>Story Spinner</u></h1> <main> <div class="container"> </div> <section class="cards"> <div class="card"> <div class="card__image-container"> <img … -
What is the correct way to link home and about page in django urls?
Right now what I am doing is this: pages app > urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] project > urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This seems to work fine. I am able to go to the homepage and the about page fine, but I have seen other people do as in the following: project > urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), path('about/', include('pages.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) So basically, in the project urls file, the line 'path('about/', include('pages.urls')),' is added. So I was wondering what is the correct way of linking the about page in the project urls file. -
Django - Heroku push succeeds but getting AttributeError (module has no attribute)
I pushed my web app to Heroku and it built / deployed fine, but I get this error when I access it: AttributeError at / module 'wakemeup.models' has no attribute 'environment' Exception Location: /app/lib/UsefulFunctions/googleUtils.py in <module>, line 16 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] It works fine locally, so my first thought was a PYTHONPATH issue, but it seems to be similar: Python Path: ['C:\\Users\\ravioli\\projects\\dcp', 'C:\\Program Files (x86)\\Python38-32\\python38.zip', 'C:\\Program Files (x86)\\Python38-32\\DLLs', 'C:\\Program Files (x86)\\Python38-32\\lib', 'C:\\Program Files (x86)\\Python38-32', 'C:\\Program Files (x86)\\Python38-32\\lib\\site-packages'] Directory structure (simplified) googleUtils.py (simplified) import os import sys import io import copy from urllib.error import HTTPError # Import - Google from google.oauth2 import service_account ... # Import - Application from lib.UsefulFunctions.dataUtils import get_setting import wakemeup.models.environment as env class GoogleDriveManager(): ... I originally had the import wakemeup.models.environment as env line as from wakemeup ... import but that was giving me a circular dependency error, so I changed it and it works fine locally. Not sure if that has to do with it. How can I fix this so it works on Heroku? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x102980b70>
I have been trying to fix this but I am not able to understand it. I am using Python 3.7.2, Django 2.1.11 and Django-weasyprint 0.5.4. I have read other issues like these but none of them fit my problem. I have tried fixing the issue of value error by using export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 but these also does not seem to be working. Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x102980b70> Traceback (most recent call last): File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen … -
Django how to assign a function for sending emails from to an HTML button
I am new to django and i would like to know how i can give the function "Initial_Report(request):" to an html button so that every time is clicked it performs the given function. Views code def home(request): return render(request, 'home.html') def Initial_Report(request): noc_emails = Employee.objects.exclude(Position__Position__contains='Customer').values_list('Email', flat=True) cs_emails = Employee.objects.filter(Position__Position__contains = 'Customer').values_list('Email', flat=True) noc_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', noc_emails) cs_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', cs_emails) send_mass_mail((noc_message,cs_message), fail_silently=False) return render(request,'InitialReport.html') Urls urlpatterns = [ path('', views.home, name='home.html'), path('admin/', admin.site.urls), path('Initial_Report', views.Initial_Report, name = 'Initial_Report' ), ] Home.html <button> Send Initial Report</button> -
Django Celery RabbitMQ access denied (403) ACCESS_REFUSED
I have a django project with heroku with celery integrated. I've got the rabbitmq add-on through heroku and have tested my task locally to success. The issue I'm having is connecting my remote server to rabbitmq/cloudamqp. I believe the credentials I'm using are the culprit of the problem, but I'm unsure where I'm going wrong. I'm using the credentials provided to me via the cloudamqp dashboard. This includes: AMQP URL User & Vhost Password In my settings.py I have: CELERY_BROKER_URL= "amqp://{User}:{Password}@{AMQP URL}:5672/" I've tried a variety of other forms with similar results. The latest error output is: amqp.exceptions.AccessRefused: (0, 0): (403) ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile. Am I using the right credentials? Do I need to create a rabbitmq user through the command line and not the admin dashboard? -
How can I filter a Django query with a list of values in queryset?
I am new to this, and can't figure out where I've gone wrong. I am using the Django rest framework my output is like this I want to use the filter in "views.py" to filter by "rate_types".how can I write a query for this case? [ { "submitted_candidate_id": 1, "submit_candidate": [ { "candidate": [ { "rate_types": "Daily", }, { "rate_types": "Daily", }, ] } ] } ] -
django project with selenium- wire, browser gets closed after URL loaded
I am working on a very small django project. I am using Selenium-wire in my project because I need to collect the network request. Everything works as expected and when I head over to 127.0.0.1:8000 selenium-wire opens up a new chrome browser to start exploring and collecting the network data. so far so good. unfortunately, after around 30 seconds the window (Chrom browser) that was opened by Seleniumwire gets closed without any error. Can you please help me with this matter? Here is my code: def home(request): # Download and install Chrome web driver driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get('https://www.google.com') context = { 'posts': Post.objects.all } return render(request, 'blog/home.html', context) Do you think that something like this is because of django? because when I use my code in python I do not see this problem. -
getting NoReverseMatch.Reverse for '{props.url}' not found.Trying to make a link in django with the name being a dynamic value
<a href="{% url '{props.url}' %}"><input type='submit' value='REGISTER' id={props.card_id + '1'}/></a> Im creating a component where in theres a link which has a name which points to one of the items in urlpatterns of urls.py based of the name value which is in props.url. But im unable to put the value in the href of a tag -
Using APScheduler in clock.py on Heroku to call def send_email_reminder from main app
I have an app that tracks users borrowing equipment. In the application I have an app "tool_req". In the views.py file I have a def called "send_email_reminder". I want this to run once a day to send emails to the borrower that the rental period is over. I have installed APScheduler and have a file "clock.py" to run in the background on Heroku. My Procfile looks like this: Procfile.py ... web: gunicorn trydjango.wsgi clock: python clock.py ... When I push the app using the following clock.py file I see the message every 3 minutes in my logs. clock.py from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): print('This job is run every three minutes.') sched.start() So far so good. However, when I put in the code to run the send_email_reminder, i.e.,: clock.py from apscheduler.schedulers.blocking import BlockingScheduler from tool_req.views import send_email_reminder sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=3) def timed_job(): send_email_reminder('request') sched.start() I get this error: app[clock.1]: ModuleNotFoundError: No module named '/app/trydjango/settings' I have tried a lot of things including various combinations of the following in my clock.py file, to no avail. import os from apscheduler.schedulers.blocking import BlockingScheduler from tool_req.views import send_email_reminder from django.contrib.auth.models import User from tools.models import Tool, Literature … -
Django - improve the query consisting many-to-many and foreignKey fields
I want to export a report from the available data into a CSV file. I wrote the following code and it works fine. What do you suggest to improve the query? Models: class shareholder(models.Model): title = models.CharField(max_length=100) code = models.IntegerField(null=False) class Company(models.Model): isin = models.CharField(max_length=20, null=False) cisin = models.CharField(max_length=20) name_fa = models.CharField(max_length=100) name_en = models.CharField(max_length=100) class company_shareholder(models.Model): company = models.ManyToManyField(Company) shareholder = models.ForeignKey(shareholder, on_delete=models.SET_NULL, null=True) share = models.IntegerField(null = True) # TODO: *1000000 percentage = models.DecimalField(max_digits=8, decimal_places=2, null=True) difference = models.DecimalField(max_digits=11, decimal_places=2, null=True) update_datetime = models.DateTimeField(null=True) View: def ExportAllShare(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="shares.csv"' response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response) writer.writerow(['date','company','shareholder title','shareholder code','difference','share']) results = company_shareholder.objects.all() for result in results: row = ( result.update_datetime, result.company.first().name_fa, result.shareholder.title, result.shareholder.code, result.difference, result.share, ) writer.writerow(row) return (response) -
django-channels: keeping track of users in "rooms"
TL;DR - How do I maintain a list of users in each room so that I can send that data to the front-end to display a list of participants in this room. I'm designing a collaborative web application that uses django-channels for websocket communication between the browser and the server. A room can be joined by more than one user and every user should be aware of every other user in the room. How would I go about achieving this using django-channels (v2)? I already went through the documentation and a few example projects available online but none of them have added a similar functionality. I also know about django-channels-presence but the project doesn't seem to be actively maintained so I didn't really bother looking into examples using that. Here's what I've come up with so far: - For every room, I create an object in the database and those objects can keep track of the users that are in the room. So for e.g in the WS consumer's connect() method I could do a get_or_create_room() call and room.add_participant(self.user_name) (or fetch this from the scope) and in the disconnect() method I could remove myself from the room. The problem with … -
the best way to update data users upload
when I create something I call A, then the data on B, C, D has been changed, then I wanna change the data of A, so the B , C, D will change relatively, my solution is before changing A, rollback the data on B, C, D it used to be, then do the same thing as creating A again, is there any better solution for this? -
Is there a java script I can write to switch between the locale files I've created?
so I have this select tag that get the languages from the setting but I don't know how to write if the user choose Spanish get the Spanish file to translate text <label>Language:</label> <select name="language" id="id_language"> {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option> {{ lang.1 }} </option> {% endfor %} </select> <h1>{% trans hello %}</h1> <h2>{% trans 'This is a translation template' %}</h2> -
Django bufsize must be an integer
I am trying to run python code with a click of an html button and have it run a python script. I would prefer to just use a normal button rather than using a form to create a "submit" button (like I have it for my first card I created in index.html), but with the tutorial I followed, that's how it was done and couldn't find a way around it. All I want to do is run a script that I created with a click of a button. I am trying to do it with Django, but cant seem to fix this error. TypeError at /external/ bufsize must be an integer Request Method: POST Request URL: http://127.0.0.1:8002/external/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: bufsize must be an integer Exception Location: C:\Users\12673\anaconda3\lib\subprocess.py in __init__, line 702 Python Executable: C:\Users\12673\anaconda3\python.exe urls: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.urls import path from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.button), url(r'^output',views.output,name="script"), url(r'^external',views.external), ] Views.py from django.shortcuts import render import requests from subprocess import run,PIPE import sys def button(request): return render(request,'index.html') def output(request): data=requests.get("https://regres.in/api/users") print(data.text) … -
How To Use Django Password Reset for Users Password Reset Instead of Admin's only?
I am desiging a website using python django on backend,sites manages different users so how I can enable password reset functionality in that,I have tried django password reset but it seems that it only works for Admin credentials..How to use it for multiple users ? -
Force Django to Run a Test Against A Real, Production Database
I'll start by saying that I understand that in 99.99999% of cases, this should be avoided. I believe I have a valid use case, however. We are a large company with a huge MySQL cluster which houses I-don't-even-know-how-many-millions of records across thousands of tables. We are writing a Django application which accesses 4 schemas in the cluster which amounts to about 100 tables. We are never writing to these tables, only reading from a large cross section of them. I have used Django to machine generate read-only, unmanaged ORM classes for these tables and it is working beautifully in practise. All I want is one test which hits a REST endpoint and checks if it answers 200 OK. I need no tests beyond that because in 6 months we are moving away from this data source entirely. We don't have write access to this data. The amount of security and administrative effort we would need to go through in order to be able to change a single byte of data in the cluster would represent weeks of meetings and discussion, and then we'd be rejected. If we wrote code to add, update, or delete data from this source, it would … -
Django ConnectionAbortedError
So I am trying to solve api issue. I am making request to django backend using axios from my frontend application. They are running on seperate domains. My django app is running in a virtual environment. If I make a request using postman I will get my response no problem but if I make request using my front end application I get the following error. Traceback (most recent call last): File "c:\laragon\bin\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\laragon\bin\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\laragon\bin\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Thomas\.virtualenvs\qb_project-vSd1QFH0\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\laragon\bin\python\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine This is the axios method axios.get('http://mybackend/api/oauth') .then(response => { context.commit('CONNECTION', response) console.log(response) resolve(response) }).catch(error => { console.log(error) reject(error) }) and this is my method for returning my response urls.py urlpatterns = [ path('api/oauth', oauth, name='oauth') ] api.py @api_view(['GET']) def oauth(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT ) data = auth_client.get_authorization_url([Scopes.ACCOUNTING]) request.session['state'] = auth_client.state_token return Response(data) So for some reason the connection is being closed, before the … -
Unable to save my admin.py changes in my model
I am pretty new to django. I am trying to save my admin.py list_editable changes in my model. I am using 'def clean(self):' in my model for validationError and if there is no validation i need to save my changes. class DashBoard(models.Model): """Dashboard to be used to upload all my items""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length = 255, null = True) tranScription = models.CharField(max_length = 255, null = True) videoUrl = models.CharField(max_length = 255, null = True) audioUrl = models.CharField(max_length = 255, null = True) imageUrl = models.CharField(max_length = 255, null = True) foodQuality = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) ambience = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) cleanliness = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00)) mediaType = models.CharField(max_length = 255, default ='mp4') date = models.CharField(max_length = 255, default= datetime.today().strftime("%Y-%m-%d")) isUploaded = models.BooleanField(max_length = 255, default = False) def clean(self): if value < 0 or value > 1: raise ValidationError(u'%s is not between 0 and 1' % value) def __str__(self): return self.title -
How to loop through millions of Django model objects without getting an out of range or other error
I have millions of objects in a Postgres database and I need to send data from 200 of them at a time to an API, which will give me additional information (the API can only deal with up to 200 elements at a time). I've tried several strategies. The first strategy ended up with my script getting killed because it used too much memory. This attempt below worked better, but I got the following error: django.db.utils.DataError: bigint out of range. This error happened around when the "start" variable reached 42,000. What is a more efficient way to accomplish this task? Thank you. articles_to_process = Article.objects.all() # This will be in the millions dois = articles_to_process.values_list('doi', flat=True) # These are IDs of articles start = 0 end = 200 # The API to which I will send IDs can only return up to 200 records at a time. number_of_dois = dois.count() times_to_loop = (number_of_dois / 200) + 1 while times_to_loop > 0: times_to_loop = times_to_loop - 1 chunk = dois[start:end] doi_string = ', '.join(chunk) start = start + 200 end = end + 200 [DO API CALL, GET DATA FOR EACH ARTICLE, SAVE THAT DATA TO ARTICLE] -
Exception Type: NoReverseMatch - Django
after researching for hours I cannot get rid of this error, I hope someone can help me. Models: class Puja(models.Model): seller = models.OneToOneField(Seller, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True) title = models.CharField(max_length=100) video = models.FileField(blank=True) photo = models.ImageField(blank=True) published_date = models.DateTimeField("Published: ",default=timezone.now()) bidding_end = models.DateTimeField() starting_price = models.IntegerField(default=1) #slug = models.SlugField(null=True) def __str__(self): return str(self.title) #def get_absolute_url(self): # return reverse('bidding_list_detail', args=[str(self.id)]) #slug time def get_absolute_url(self): return reverse('bidding_list_detail',args={'id': self.id}) Views: class bidding_list(ListView): model = Puja template_name = 'bidding_templates/bidding_list.html' """return render(request= request, template_name='bidding_templates/bidding_list.html', context = {"Pujas": Puja.objects.all})""" class bidding_list_detail(DetailView): model = Puja template_name = 'bidding_templates/bidding_list_detail.html' urls: path('admin/', admin.site.urls), path("bidding_list/", bidding_list.as_view(), name="bidding_list"), path('<int:pk>', bidding_list_detail.as_view(), name='bidding_list_detail'), admin: class PujaAdmin(admin.ModelAdmin): list_display = ('seller','title','video','photo','published_date','bidding_end','starting_price') admin.site.register(Puja,PujaAdmin) template 1: {% extends 'header.html' %} {% block content %} <h1>Pujas</h1> {% for Puja in object_list %} <!--object_list--> <ul> <li><a href="{{ Puja.get_absolute_url }}"> {{ Puja.title }} </a></li> </ul> {% endfor %} {% endblock %} template 2: {% extends 'header.html' %} {% block content %} <div> <h2>{{ object.title }}</h2> <p>{{ object.seller }}</p> </div> {% endblock %} Note that, whenever I remove <a href="{{ Puja.get_absolute_url }}"> from the first template, the objects "puja" in the model get properly displayed on the template, but I cannot access them. They normally exist on the admin … -
Django/DRF - Serialize Queryset avoiding N+1 problem with SerializerMethodField
I am using this model configuration. class Project(models.Model): name = models.CharField(max_length=64) class Platform(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_platforms") is_deleted = models.BooleanField(default=False) Now, I am getting my queryset using this code. queryset = Project.objects.prefetch_related("project_platforms") I want to serialize this queryset using the following Serializer. class ProjectSerializer(serializers.ModelSerializer): platforms = serializers.SerializerMethodField("_platforms") class Meta: model = Project fields = ["id", "name", "platforms"] def _platforms(self, obj: Project) -> list: platforms = PlatformSerializer(obj.project_platforms.filter(is_deleted=False), many=True).data return platforms Now, even though I have used prefetch_related, when I call the serializer on my queryset, it still causes one query for each project in fetching the platforms for each project. I cannot use platforms = PlatformSerializer(read_only=True, many=True) since the PlatformSerializer is declared below ProjectSerializer. Is there any solution to this? Am I doing something wrong?