Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are best practices for API error response handling?
It is best practice to handle such API errors by try and catch or the API response suppose to be like Google, Facebook and Microsoft API call Google API call example Facbook API call example Microsoft API call example -
How do I get the current item in the model from the request?
When a submit button is clicked, I want to be able to know what item the user was on. The button would be on an item's page that the user gets taken to when they click on an item. This button is is part of a django form (PlaceBid) that allows the user to bid for the item. So I want to be able to update what the item's highest bid is if the bid is higher than the current highest. This means that I need to know what item the user was viewing. I also want to save the bid in a model called Bid and in that model I also need to know what listing the bid is for. So how do I get the correct item from the model? The models: Listing() is the model for the item Bid() is the model for the bid views.py: def bid(request): if request.method == 'POST': form = PlaceBid(request.POST) if form.is_valid(): current = Listing.objects.get(pk=request.id) # my attempt to get the current item highest = current.highest_bid if form.cleaned_data['bid'] < highest: obj = Bid() obj.price = form.cleaned_data['bid'] obj.item = current obj.user = User.objects.get(pk=request.user.id) obj.save() current.highest_bid = form.cleaned_data['bid'] current.save() return HttpResponseRedirect(request.path_info) forms.py: class PlaceBid(forms.Form): … -
'function' object has no attribute 'owner'
@login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) _check_topic_owner(request) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context) def _check_topic_owner(request): if topic.owner != request.user: raise Http404 The problem is when im trying open page in web app. Is thow problem "'function' object has no attribute 'owner'" -
Multiselect field in Django
I have a product model with multiselect field in django with choices. So that vendors can choose for which age group the product is for and customers can filter products based on their age. The issue here is if the vendor selects two age groups the products is for. eg. Child and Adult. In database it is put as Age(Child, Adult). Then if the customer must filter that product using only child or adult it won't display the product. The customer choose both to display. Clearly I don't want this to happen. I want the customer filter the product either by child or adult or both. Here is the code: {% for i in aging %} <li class="list-group-item"> <input class="filter-checkbox" data-filter="age" value="{{ i.0 }}" type="checkbox" />&nbsp; {{ i.1 }} </li> {% endfor %} def filter_data(request): age_group = request.GET.getlist('age[]') products = Product.objects.all().order_by('-id').distinct() if len(age_group) > 0: products = products.filter(age=age_group).distinct() t = render_to_string('ajax/category-products.html', {'data': products}) return JsonResponse({'data': t}) $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this).val(); var _filterKey=$(this).data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); // Run Ajax $.ajax({ url:'/filter-data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ console.log(res); $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); Please tell me if there is other way. I have been on this for several days. -
connection to server at "databaseendpoint", port 5432 failed: FATAL: password authentication failed for user "databasename"
I have a Django project which is deployed to Heroku and has been linked to a website domain name (e.g. https://www.myapp.com). I've recently tried connecting it to an AWS RDS Postgres Database, however when I try to access the site using my website URL and perform a POST request it comes up with the error in the title. What's interesting is that it works fine using the Heroku domain name (appname.herokuapp.com) and if I run it locally. Even more bizarre is that it's trying to use the database name as the username and I cannot find any reference to this in my code. Any help with this would be appreciated, I'm going round in circles here. Details: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) (only uses this when running it locally) Heroku Config Vars postgres://username:password@database-1.xxxxxxxx.eu-west-2.rds.amazonaws.com:5432/databasename I've tried removing the config and running heroku run python3 manage.py migrate to revert to the sqlite database and it still tries to look at the postgres db with the database name as the user Are there any other sources I have forgotten about where I define the database details? -
Django: Filter on model column with Regex
I have phone numbers stored as (921) 414-1313 in the database and I want to run a search lookup on that field, but I don't want to force them to include (, ' ', ) or -. I'm using Postgres and tried to work with SearchVector initially, however it ran into the same challenge (so for now, I'm doing it the old fashioned way). I have a model definition that returns an "unformatted" number as 9214141313, but I can't figure out how to query against my custom definition inside of the model? Ultimately, I want a customer to be able to type in 921414 and get the response for the matching record. GitHub: https://github.com/varlenthegray/wcadmin/blob/dev/main/views.py#L25 Model: class JobSite(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quickbooks_id = models.IntegerField(editable=False, null=True, blank=True) name = models.CharField(max_length=200, null=True, blank=True) first_name = models.CharField(max_length=200, null=True, blank=True) last_name = models.CharField(max_length=200, null=True, blank=True) print_on_check_name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) address_2 = models.CharField(max_length=200, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=20, null=True, blank=True) phone_number = models.CharField(max_length=30, null=True, blank=True) email = models.CharField(max_length=400, null=True, blank=True) service_interval = models.IntegerField(default=12) next_service_date = models.DateField(null=True, blank=True) primary_technician = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) active = models.BooleanField(default=True) access_code = models.CharField(max_length=10, … -
How Initial Foreign Key event in Function based View in Django
I have two models, one is link to the other using foreign key. The Event model is view on the detail page. What I want is to initial the foreign key foreign element to the my Function based view that helps me process the form in Ajax and save. I want to initial the event field with the current Event being viewed Views.py def create_attendance(request, slug): model = get_object_or_404(Event, slug=slug) context = { 'event': model } response_data = { 'msg':'Your form has been submitted successfully' # response message } if request.POST.get('action') == 'post': fullname = request.POST.get('fullname') phone_number = request.POST.get('phone_number') email = request.POST.get('email') company = request.POST.get('company') position = request.POST.get('position') event = model.objects.get(event=name) Attendance.objects.create( fullname = fullname, phone_number = phone_number, email = email, company = company, position = position, event = event ) return JsonResponse(response_data) print(event) return render(request, 'create_attendance.html', context) Model.py class Event(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = models.SlugField(max_length=150, blank=True) class Attendance(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, null=True, blank=True) fullname = models.CharField(max_length=100) -
Is there a way to collapse Django Admin Modules in the lefthand nav sidebar?
In a project with multiple app modules, each containing many models, the lefthand side navbar of the default Django admin page has a lot of entries which results in a lot of scrolling. Is there a way to collapse or toggle the visibility of a single module? A cursory glance through the Django docs was unfruitful, but that doesn't mean it isn't there. -
should i have a table for each product type in a database
i am very confused about this, i have three different types of products, first i have physical products which simply are art products and affiliate products, and digital products such as courses , books, art pictures, my first approach was to create a separate table for each one like this: class Category(models.Model): name = models.CharField() class ArtType(models.Model): name = models.CharField() class PhysicalArtProduct(modes.Model): category = models.ForeignField(Category) madeOf = models.ManyToManyField(AffeliateProduct) artType = models.ForeignKey(ArtType) ........ class AffeliateProduct(models.Model): ........ class Course(models.Model): artType = models.ForeignKey(ArtType) ....... class Book(models.Model): ....... because PhyscialArtProduct are related to AffeliateProduct because PhysicalArtProduct are made of AffeliateProduct that's why i had to add many-to-many field in PhysicalArtProduct my second approach is to make a single Product table and a ProductType table and build the relationship between the products themselves and the category and arttype by adding the necessary tables which approach i should go with here, any help would be really appreciated -
Django Import-Export import error - localtime() cannot be applied to a naive datetime
Using: Python 3.10.4 Django 4.06 Django-import-export 2.8.0 I am trying to import data to use as demo data into my django application. I keep getting an error of localtime() cannot be applied to a naive datetime (after working around another error that I asked separately). I am not worried about this particular field being naive datetime. It's one that needs to be set manually in real application. ### models.py class Reservation(models.Model): reservation = models.OneToOneField(Vehicle, on_delete=models.CASCADE, primary_key=True,) delivered = models.BooleanField('Delivered',default=False) date_reserved = models.DateTimeField('date reserved', default=datetime.datetime.now) ... ### admin.py class ReservationResource(resources.ModelResource): class Meta: model = Reservation exclude = ('id',) import_id_fields = ('reservation',) fields = ( 'reservation', 'delivered', 'date_reserved', ... ) class ReservationImportExport(ImportExportModelAdmin): resource_class: ReservationResource @admin.register(Reservation) class ReservationAdmin(SimpleHistoryAdmin, ReservationImportExport): fields = ["delivered","date_reserved",...] ### demo-reservations.yaml (Note: Problem happens using different data file formats) - reservation: 50001 delivered: False date_reserved: 7/15/2022T00:00:00+00:00 ... Here's the error (slightly obfuscated) Line number: 1 - localtime() cannot be applied to a naive datetime 50001, False, 7/15/2022T00:00:00+00:00, CHRIS EDWARDS, 16, ROSE TYLER Traceback (most recent call last): File "c:\Users\...\lib\site-packages\import_export\resources.py", line 670, in import_row diff = self.get_diff_class()(self, original, new) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 221, in __init__ self.left = self._export_resource_fields(resource, instance) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 242, in _export_resource_fields return [resource.export_field(f, instance) if instance else … -
How two make the object to update of a form static?
I have some objects created. I would like updating them if needed. Problem : If I try to update one object his title change. For example: I would like to update this object «2022-07 - Django - tesr - Multi-device - IAB - CPM». The string to update is testr to test. How can I do that without changing the header. @login_required def update_campaign_naming_tool(request, pk): # Instance to update cnt = get_object_or_404(CampaignNamingTool, id=pk) if request.method == 'POST': form = CampaignNamingToolForm(data=request.POST, instance=cnt) if form.is_valid(): form.save() msg = "«{}» successfully updated".format(str(cnt)) messages.success(request, msg) return redirect('list_of_campaign_naming_tool') else: msg = "{} already exists. \ Please check your attributes !".format(form.instance) messages.error(request, msg) context = { 'cnt': str(cnt), 'form': form, } return render(request, 'update.html', contex) form = CampaignNamingToolForm(instance=cnt) context = { 'cnt': str(cnt), 'form': form, } return render(request, 'update.html', context) The form -
Blocked by CORS policy - 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'
I am trying to send a POST request to my backend but keep getting an error. Access to XMLHttpRequest at 'http://localhost:8000/api/create-room' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using Django + Next.js. I have the django-cors-headers dependency installed. In settings.py I have included 'corsheader' in INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE. I am also using the config CORS_ALLOW_ALL_ORIGINS: True. For the frotend, I am sending the POST request using axios. axios.post('http://localhost:8000/api/create-room', {some data}) In past projects, I've never had this problem sending requests to my Django backend. How can I satisfy the access control check No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Django models saves database entries starting with id 2 (not id1)
Following is my model class Post(models.Model): post_title = models.CharField(max_length=100) description = models.TextField(null=False, blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__ (self): return str(self.post_title) Following is my query def posts(request, pk): post_list = Post.objects.get(id=pk) return render(request, 'testing/posts.html', {'post_list': post_list} ) I have checked the database entry - it starts with id-2. Also, the URL with id-1 isn't working. Note: I am using MySQL database Why does it happen? -
new separate django project on database which already hosts another django project
I need to develop a new django project (let's call it new_django) using a SQL Server 2019 database named AppsDB which already hosts another django project (let's call it old_django). The two apps are completely separate. Unfortunately, I can't get a new database for each new django project, so I have to reuse AppsDB. What I don't understand is, how can I tell django not to overwrite the existing auth_... and django_... tables generated by old_django? My first idea was to use different schemas for the two project, but django doesn't support this with a SQL Server database as far as I know. Some workarounds suggest to change the database default schema for a given user like this anwser. But I won't get a new user for every project either. And relaying on manually changing the db schema every time before I migrate something will most certainly cause a mess at some point. I'm stuck with the current setup and would like to know if anyone has come up with a more elegant solution or different approach to solve my problem? Any help is much appreciated! -
Django Import-Export import error for one-to-one field - KeyError: 'id'
Using: Python 3.10.4 Django 4.06 Django-import-export 2.8.0 I am trying to import data to use as demo data into my django application. I keep getting a KeyError. ### models.py class Reservation(models.Model): reservation = models.OneToOneField(Vehicle, on_delete=models.CASCADE, primary_key=True,) delivered = models.BooleanField('Delivered',default=False) date_reserved = models.DateTimeField('date reserved', default=datetime.datetime.now) ... ### admin.py class ReservationResource(resources.ModelResource): class Meta: model = Reservation exclude = ('id',) import_id_fields = ('reservation',) fields = ( 'reservation', 'delivered', 'date_reserved', ... ) class ReservationImportExport(ImportExportModelAdmin): resource_class: ReservationResource @admin.register(Reservation) class ReservationAdmin(SimpleHistoryAdmin, ReservationImportExport): fields = ["delivered","date_reserved",...] ### demo-reservations.yaml (Note: Problem happens using different data file formats) - reservation: 50001 delivered: False date_reserved: 7/15/2022T00:00:00+00:00 ... Here's the error (slightly obfuscated) Traceback (most recent call last): File "c:\Users\...\lib\site-packages\import_export\resources.py", line 661, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 353, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 340, in get_instance import_id_fields = [ File "c:\Users\...\lib\site-packages\import_export\resources.py", line 341, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' Tried Already: Removed SimpleHistoryAdmin from Admin registration Put breakpoints in debugger - it is clear that it is ignoring the "import_id_fields" value. If I manually change the value to 'reservation' when it calls get_import_id_fields(self), I get further (a second issue I will ask separately - guessing stackoverflow wants 1 issue … -
How to get the previous and next related post in django?
views.py def post_details(request,pk): post = Post.objects.get(id=pk) # next_post = Post.objects.filter(id=pk) context={'post':post,'next':next_post} return render(request, 'blog/post_detail.html', context) blog-detail <div class="s-content__pagenav group"> <div class="prev-nav"> <a href="#" rel="prev"> <span>Previous</span> Tips on Minimalist Design </a> </div> <div class="next-nav"> <a href="#" rel="next"> <span>Next</span> Less Is More </a> </div> </div> models #this is my model class User(AbstractUser): # pass name = models.CharField(max_length=200) bio = models.TextField(null=True) email = models.EmailField(unique=True, null=True) avatar = models.ImageField( null=True, upload_to='blog_media', default="images/avatar.svg") facebook = models.URLField(blank=True, null=True) twitter = models.URLField(blank=True, null=True) dribbble = models.URLField(blank=True, null=True) instagram = models.URLField(blank=True, null=True) class Category(models.Model): name = models.CharField(max_length=20) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) title = models.CharField(max_length=200, blank=False); description = models.TextField(null=True,blank=True) image = models.ImageField(upload_to='blog_media') url = models.URLField(null=True, blank=True) body = HTMLField() created = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django : trying to call the get method after the post method for a class view
I made a classview to upload the files in an azure blobstorage, shows a table of the history of the uploaded files and allows to display them in the right part of the page. I have a problem when a file is uploaded by the POST method, the file selected earlier is not executed by the GET method, so the content is not loaded in the context and cannot be displayed in the template. I thought of two solutions. The first one is calling the GET method at the end of the POST method. However, this doesn't work and it doesn't seem to be efficient according to the stackoverflow documentation. That's why I left it as a comment at the end of the POST method. The other solution is a redirect to this same classview, however this does not work : ValueError: The view documents.views.view didn't return an HttpResponse object. It returned None instead. How can I execute this get method without copying the lines of code in the post method. views.py class DocumentUpload(FormView) : model = TblDocument template_name = 'documents/documents.html' form_class = FilesForm def get_context_data(self, *args, **kwargs): # Call the base implementation first to get a context context = … -
KeyError: 'author' in def_validate Django
I am getting this error inside django validation. if attrs['author'].id == self.context['request'].user.pk: KeyError: 'author' Here is my django model and serializer code. class CalendarTime(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='calendartimes') time= models.CharField(max_length=50) date = models.CharField(max_length=300) timestamp = models.DateTimeField(auto_now_add=True) allowstocks = models.BooleanField(default=False) stock = models.IntegerField(default='0') class Meta: constraints = [models.UniqueConstraint(fields=['author', 'time','date'],name='unique_calendartime')] class CalendarTimeSerializer(serializers.ModelSerializer): class Meta: model = CalendarTime fields = ("id","author","allowstocks","stock","time","date","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') The validate code works fine in other functions.Does anybody know where the issue comes from? -
How to use Postgres & MongoDB simultaneously in Django?
I am looking for a solution to work with Postgres and MongoDB simultaneously in my Django project. I have large data which I would like to store in MongoDB and Postgres for user management, billing, and other things to manage. I have tried to use a library pip install django, which is outdated, and not able to find any solution. Please guide me with an authentic solution! Thanks -
Django: how do i substract numbers from another number and return the new_value in django
i have a model field called main_all_earning and it looks like this main_all_earning = models.IntegerField(default=0), i also have a form where user are allowed to input any amount they want to withdraw from main_all_earning, i have written the logic for it to subtract the value from the form which is called amount from the main_all_earning, but the main_all_earning does noot update. What could be the issue? Views.py def withdrawal_request(request): user = request.user profile = Profile.objects.get(user=user) main_all_earning = profile.main_all_earning if request.method == "POST": form = WithWithdrawalRequestForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user if new_form.amount > main_all_earning: messages.warning(request, "You cannot withdraw more than your wallet balance.") return redirect("core:withdrawal-request") elif pending_payout >= main_all_earning: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") elif new_form.amount >= main_all_earning: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") else: new_form.save() main_all_earning = main_all_earning - new_form.amount messages.success(request, f"Withdrawal Request Is Been Processed... You would get a bank alert soon") return redirect("core:withdrawal-request") else: form = WithWithdrawalRequestForm(request.POST) context = { "form":form, "main_all_earning":main_all_earning, } return render(request, "core/withdrawal-request.html", context) context = { "form":form, "main_all_earning":main_all_earning, } return render(request, "core/withdrawal-request.html", context) -
can you pass array into django url without passing in path
say I have a url I want to pass data to like this: {% url 'video_form' {'text': 'text', 'file': video.file, 'image': image} %} and get it like this: def video_form(request): print(text) print(file.url) print(image.url) kind of like POST instead of GET. Can I pass the values in the backend instead of the url like this: path('video_form/<str:text>/', views.video_form, name='video_form') which would not let me pass text inputs in them. -
why is uwsgi cursing and removing instances?
I am trying to test-run a django project on my VPS for the first time. I followed a step-by-step tutorial on a blog (thanks to a nice guy on #django channel at liberachat). The setup involves uWSGI and nginx. The django project files are at /srv/www/site/*. uwsgi configuration is at /etc/uwsgi.d/mysite.com.ini, and nginx configuration is at /etc/nginx/conf.d/mysite.com.conf. Here is what happens when I start uwsgi (systemctl start uwsgi): Jul 29 14:35:09 mysite.com uwsgi[6998]: [uWSGI] getting INI configuration from mysite.com.ini Jul 29 14:35:09 mysite.com uwsgi[6318]: Fri Jul 29 14:35:09 2022 - [emperor] curse the uwsgi instance mysite.com.ini (pid: 6998) Jul 29 14:35:09 mysite.com uwsgi[6318]: Fri Jul 29 14:35:09 2022 - [emperor] removed uwsgi instance mysite.com.ini How do I interpret and fix that? contents of /etc/uwsgi.d/mysite.com.ini: procname-master = demosite # Now paths can be specified relative to here. chdir = /srv/www/ # allow nginx uid = 981 gid = 981 chmod-socket = 644 socket = server.sock # Task management ; Max 4 processes processes = 2 ; Each running 4 threads threads = 2 ; Reduce to 1 process when quiet cheaper = 1 ; Save some memory per thread thread-stack-size = 512 # Logging plugin = logfile ; Log request details … -
400 error when posting PushSubscription object to server
I am setting up push notifications using service workers + websockets using Django Channels and Django WebPush to receive the subscription and send a message back to the service worker. While I am able to register a service worker and receive the PushSubscription object containing details of a push subscription. I then try to send this subscription to an end point in webpush 'save_information' that should have the subscription. However, when I attempt to do this I get the error: Response {type: 'cors', url: 'http://127.0.0.1:8000/webpush/save_information', redirected: false, status: 400, ok: false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 400statusText: "Bad Request"type: "cors"url: "http://127.0.0.1:8000/webpush/save_information"[[Prototype]]: Response This is the code I have in my service worker/ the code related to getting a subscription and sending through the subscription: const saveSubscription = async (subscription) => { const browser = navigator.userAgent.match(/(firefox|msie|chrome|safari|trident)/ig)[0].toLowerCase(); const data = { status_type: 'subscribe', subscription: subscription.toJSON(), browser: browser, }; const res = await fetch('http://127.0.0.1:8000/webpush/save_information', { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json' }, credentials: 'include' }); handleResponse(res); } const handleResponse = (res) => { console.log(res); } ... self.addEventListener('activate', async () => { try { const applicationServerKey = urlB64ToUint8Array('***') const options = { applicationServerKey, userVisibleOnly: true } const subscription = await … -
Python multiple single dictionary return [closed]
[{'ITEM': '001', 'Name': 'test', 'Count': '01', 'cid': 1}][{'ITEM': '002', 'Name': 'test1', 'Count': '02', 'cid': 1}] i want to convert in single list Like That, [{'ITEM': '001', 'Name': 'test', 'Count': '01', 'cid': 1},{'ITEM': '002', 'Name': 'test1', 'Count': '02', 'cid': 1}] I want to return it Also. I tried lots of but unable to get solution. Thanks in advance. -
Why does my django app sometimes takes ages to load a small page
I have a very simple Django app running on a vps running Ubuntu 22.04, sometimes the page loads (for example the admin screen) take >10 seconds, while other times it's instant. I'm serving using Gunicorn, the website receives no traffic yet. What would be a good way to diagnose this? What are some common mistakes in config?