Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter with many to many fields aggregate data
In my frontend, there is an option for the filter, in every filter request, it should show how many items in a particular category. for example, you can check this site, https://www.navingocareer.com/vacatures they show how many items for per category in each filter request, i am going to implement similar feature in my app At first see my codes: this is my models.py class IndustryType(models.Model): name = models.CharField(max_length=200) class Tags(models.Model): name = models.CharField(max_length=200) class Books(models.Model): name = models.CharField(max_length=200) industry = models.ManyToManyField( IndustryType, blank=True, ) tags = models.ManyToManyField( Tags, blank=True, ) and this is my views.py file import django_filters class BookFilterSet(django_filters.FilterSet): industry = django_filters.ModelMultipleChoiceFilter( field_name='industry', queryset=IndustryType.objects.all(), ) tags = django_filters.ModelMultipleChoiceFilter( field_name='tags', queryset=Tags.objects.all(), ) class Meta: model = Books fields = [ 'industry', 'tags' ] class Books(generics.ListAPIView): serializer_class = BookDetailsSerializer filter_backends = [ django_filters.rest_framework.DjangoFilterBackend, ] filter_class = BookFilterSet queryset = Books.objects.all() Currently code is working great based on my expection, now i am trying to implement item count in every request based on it's current query params similar to the given website. Does anyone have idea how i can do it? Like i want to show many items in for per industry with current params, how many items for for tags with … -
Store responses from server per model instance Django
I have a Django server, with an engine backend communicating with the Django backend through GRPC. The Django server has the database and stores users and the users' text documents. When writing in each of these documents the text is sent to a backend engine running NLP models. The backend returns suggestions based on the text and sends them back to the Django backend, which sends them to the client. However the suggestions returned do not belong to any document and are in this case global. This means that they pop up in all documents for all users. I could add a field to the document model in django with these, however since the suggestions are very temporary (They are meant to be fixed) I was wondering if there was any other way to approach this more client sided. The architecture as a whole also feels very clumsy with the Django database in between the client and the actual machine learning engine, however it would be a lot of code to change all of this, do you guys have any suggestions? -
Chunking a django-import-export
I am reading this article about chunking a large database operation. I am also using django-import-export and django-import-export-celery in my admin site and I would like to implement chunking into them. The problem I have is django-import-export already handles the file import, as well as the whole process of importing, in the background. I tried using django-import-export's bulk imports, but one of the caveats is: Bulk operations do not work with many-to-many relationships. so chunking is what we thought was the alternative. Is it possible to perform chunking inside the django-import-export? -
ERROR (EXTERNAL IP): Internal Server Error: /login/
My project works well in development but when in production throws an error. I suspect it is the django cacheops settings that have been applied... Here's the traceback Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/workspace/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/templates.py", line 73, in rendered_content return real_rendered_content.fget(self) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/workspace/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 168, in render with context.bind_template(self): File "/workspace/.heroku/python/lib/python3.9/contextlib.py", line 117, in __enter__ return next(self.gen) File "/workspace/.heroku/python/lib/python3.9/site-packages/debug_toolbar/panels/templates/panel.py", line 48, in _request_context_bind_template updates.update(context) DEBUG_TOOLBAR_CONFIG = {'SHOW_TOOLBAR_CALLBACK': 'library.settings.show_toolbar', 'SHOW_TEMPLATE_CONTEXT': True, 'ENABLE_STACKTRACES': True, } CACHEOPS_DEGRADE_ON_FAILURE=True CACHEOPS_ENABLED = True CACHEOPS_REDIS = { 'host': 'localhost', 'port': 6379, #'db': 1, } CACHEOPS_DEFAULTS = {'timeout': 60*60} CACHEOPS = {'libman.*': {'ops':'all'},} CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/2", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } SELECT2_CACHE_BACKEND = 'select2' INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] The reason I say it is cacheops is because when I hash this it works CACHEOPS_DEGRADE_ON_FAILURE=True Please help whoever can... -
How to solve "object of type 'Course' has no len()" error that I am getting after using paginator in a view function?
This is my model. I have a many to one relationship. class Course(models.Model): course_name = models.CharField(max_length=100) class Coursegk(models.Model): question = models.CharField(max_length=1000) option_one = models.CharField(max_length=100) option_two = models.CharField(max_length=100) option_three = models.CharField(max_length=100) option_four = models.CharField(max_length=100) answer = models.CharField(max_length=100) courses = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="display") This is my views.py page def showcourses(request): details = Course.objects.all() paginator = Paginator(details, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'index.html', {'data':page_obj}) def displaymcqpage(request, courses_id): displaymcq = Course.objects.get(id=courses_id) paginator = Paginator(displaymcq, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'coursegk.html', {'display':page_obj}) Now paginator is working fine for the index.html page. But when I go to coursegk.html page from index.html page I am getting "object of type 'Course' has no len()" error. How to use paginator for the displaymcqpage function? -
Django create post
I am trying to create a new post to a forum, and it does work, i am also printing if the form is valid, but when i go to check after the post is not posted. In the admin page, the post is there, approved, but missing the tags and category fields. They was added when the post was created, if not i get an error. But I have to manually add them in the admin page to get the post posted to the forum. Here is my Post in models class Post(models.Model): title = models.CharField(max_length=400) slug = models.SlugField(max_length=400, unique=True, blank=True) user = models.ForeignKey(Author, on_delete=models.CASCADE) content = HTMLField() categories = models.ManyToManyField(Category) date = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) tags = TaggableManager() comments = models.ManyToManyField(Comment, blank=True) # closed = models.BooleanField(default=False) # state = models.CharField(max_length=40, default="zero") def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title Here is my views.py @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n form is valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() return redirect('forums') context.update({ 'form': form, 'title': 'Create New Post' }) return render(request, 'forums/create_post.html', context) The … -
Seperate folder for django models
I am working on Django project that will utilize different apps to fulfill certain task. Since these apps will be referring to much same data to complete these task I figure it makes since to create a separate folder with the models like this: --Project --App1 --App2 --models ---model1.py ---model2.py Right now I'm having trouble with Django recognizing the models as existing, every time I run a makemigrations Django does not detect that any changes have been made I attempted to put a __init__.py file in the /models folder but this doesn't seem to do anything. -
Django importing of module
I am just going through some Django code: from django.shortcuts import render I have few question regarding this: This render thing how do we know this needs to be imported from django.shortcuts? Can we see render it lies in this folder django.shortcuts,? Where is this located on a drive django.shortcuts ? thank you! -
Understanding AUTHENTICATION_BACKENDS
I am trying to understand how things work when one writes the following in settings.py: AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", "master_password.auth.ModelBackend" ) In particular, the documentation states: If a backend raises a PermissionDenied exception, authentication will immediately fail. Django won’t check the backends that follow. Given this, how can the second and the third backend in the above example get a chance when a user has entered an incorrect password and the first backend has denied him access? More specifically, the third backend pertains to django-master-password, which should let the user in if he used a master password even if it does not match the user's password. So, how will that backend ever get a chance? -
NoReverseMatch at /users/password_reset/
I am trying to set up my Password Reset function for my application but getting errors after i send the reset password to my email. here is the error message: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Below is my urls.py codes: ` urlpatterns = [ path('signup/', views.user_signup, name='signup'), path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('user_profile/<int:id>/', views.user_profile, name='user_profile'), ]` -
Squashing migrations speeded up tests - and not just the database setup part
I have been struggling with slow tests - really slow tests. I thought that was probably due to inefficient data setup within my tests. I did some 'before' time measurements and then, for unrelated reasons, squashed all my migrations. Then I ran my tests again. I did not change any of the test code - only the migrations - but the tests are dramatically faster. I had expected some improvement in the database setup number reported with --timing but I had not expected much change in the speed with which the tests themselves run. Can anyone offer an explanation for this? Before Method DB setup DB teardown Running Test Total elapsed MySQL 124.2s 3.6s 794.5s 925.0s MySQL keepdb 1 123.8s 0s 742.5s 869.2s MySQL keepdb 2 4.3s 0s 742.2s 759.1s SQLite run 1 4.9s 0s 886.7s 896.3s SQLite run 2 4.3s 0s 778.1s 785.2s After squashing migration Method DB setup DB teardown Running Test Total elapsed MySQL 107.8s 6.5s 200.0s 319.5s MySQL 109.3s 6.9s 205.3s 326.4s SQLite run 1 34.3s 0s 128.2s 166.9s SQLite run 2 1.5s 0s 124.6s 130.3s -
django_filters issue with gte, lte
I am trying to filter by DateField using django_filters lib. Following the doc I encounter an issue with the "gte" and "lte" lookup_expressions (I tried both). The problem is that it only return results if the date I input in my datepicker is the exact date, which I would suspect would be the expected "iexact" or "exact" lookup_expression results. This is my simplified code, note that I have tried using only one date (removing end_date in both model and filter.py) and the result was the same so I don't believe this is a range issue Model class Replacement(models.Model): start_date = models.DateField( null=True, blank=True) end_date = models.DateField( null=True, blank=True) filter.py #not sure if this DateInput is related to the issue, just a way to attach "date" type so as to get a datepicker on template class DateInput(forms.DateInput): input_type = 'date' class ReplacementFilter(django_filters.FilterSet): start_date = DateFilter(field_name="start_date", lookup_expr='gte') end_date = DateFilter(field_name="end_date", lookup_expr='gte') class Meta: model = Replacement fields = ['start_date', 'end_date'] start_date = django_filters.DateFilter( widget=DateInput(attrs={'type': 'date'})) end_date = django_filters.DateFilter( widget=DateInput(attrs={'type': 'date'})) Views def replacement_list_page(request): replacements = Replacement.objects.all() replacement_filter = ReplacementFilter(request.GET, queryset=replacements) print(replacement_filter) return render(request, "replacements/replacementlist.html", {"replacement": replacements, 'filter': replacement_filter}) Thanks -
How i link myproject folder path to template xyz page in django to download files from buttons
How I link myproject folder path to template xyz page in Django to download files from buttons. After executing my code Django save my files in myproject folder but how do I link my template xyz page buttons to myproject folder path to download my .csv, and .aln files? -
Local development with Telegram Login Widget
Is it possible to make Telegram Login Widget work on localhost? I made a simple django application, which sends a template with JS code given to me. Dev server is running on address:port 127.0.0.1:80, in the settings of the bot domain is http://127.0.0.1, data-auth-url is also http://127.0.0.1. When I open the page, login button is displayed with the desired avatar, but when I click button, in telegram I get a message about successful login, but in the browser I get an error Bot domain invalid. How can I fix this error? Or development on a remote server is the only way? -
How to upload file in wagtail
I'm new to wagtail I'm using AbstractEmailForm to build a form but I find out that forms in wagtail don't have field to upload file I looked in wagtail documents to upload file but I didn't I found an example on internet but that for images I'm not looking for only images -
How do I change the font size and / or font family when using django-tables2?
Table definitions: ''' import django_tables2 as tables from django_tables2.utils import A from cliente.models import Cliente class BrowseCliente(tables.Table): nome = tables.Column(verbose_name='Nome',orderable=True) tipo = tables.Column(verbose_name='Tipo',orderable=False) cidres = tables.Column(verbose_name='Cidade',orderable=False) estado = tables.Column(verbose_name='UF',orderable=False) celular = tables.Column(verbose_name='Celular',orderable=False) email = tables.Column(verbose_name='E-Mail',orderable=False) dddres = tables.Column(verbose_name='DDD Res',orderable=False) foneres = tables.Column(verbose_name='Fone Res',orderable=False) class Meta: model = Cliente template_name = "django_tables2/bootstrap4.html" fields = ('nome', 'tipo', 'cidres', 'estado', 'celular', 'email', 'dddres', 'foneres') attrs = {"class": "table table-striped"} ''' Template {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} {% include 'partials/_menu4.html' %} {% render_table table %} {% include 'partials/_footer.html' %} {% endblock %} The result is a little too big for my customer´s taste. I appreciate any help. -
not able to change my EMAIL_HOST_USER i django
i am making a website in django where i have used smpt mail to send mail to user to change password when forgotten, everything is working right so far, but now i want to change my EMAIL_HOST_USER , when i change it, it dosen't send any mail to user, please tell me how can i change it EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'abc@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True i want to change abc@gmail.com to xyz@gmail.com plsss help -
Game Level data for each user in Database
I'm creating a game in Django where there are like 500 levels. How do I store game level data for each user in database ( data can be stars for each level ). The game is more like the candy crush where each user earns stars for each level. Is JSON suitable for this? Should I use a separate table for each level? Or should I use single table for all levels with level_id as Primary Key and user_id as Foreign Key? -
How to show two list of data in flutter
I am trying to fetch an api using flutter and dart and http package. Here in my code i am trying to fetch this api model : class OfferModel2 { OfferModel2({ required this.offer, required this.manager, }); late final List<Offer> offer; late final List<Manager> manager; OfferModel2.fromJson(Map<String, dynamic> json) { offer = List.from(json['offer']).map((e) => Offer.fromJson(e)).toList(); manager = List.from(json['manager']).map((e) => Manager.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['offer'] = offer.map((e) => e.toJson()).toList(); _data['manager'] = manager.map((e) => e.toJson()).toList(); return _data; } } class Offer { Offer({ required this.id, required this.offerTitle, required this.image, required this.user, required this.click, required this.category, required this.packages, }); late final int id; late final String offerTitle; late final String? image; late final User user; late final int click; late final Category category; late final List<Packages> packages; Offer.fromJson(Map<String, dynamic> json) { id = json['id']; offerTitle = json['offer_title']; image = json['image']; user = User.fromJson(json['user']); click = json['click']; category = Category.fromJson(json['category']); packages = List.from(json['packages']).map((e) => Packages.fromJson(e)).toList(); } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['id'] = id; _data['offer_title'] = offerTitle; _data['image'] = image; _data['user'] = user.toJson(); _data['click'] = click; _data['category'] = category.toJson(); _data['packages'] = packages.map((e) => e.toJson()).toList(); return _data; } } class User { User({ required this.id, required … -
Running python/python3 manage.py runserver inside a venv responds with "wrong architecture" error
I spent about all day yesterday attempting to troubleshoot this issue, I've done everything from reinstalling Django, pipenv, etc to changing the Rosetta settings in my terminal. Below is what my terminal responds with after running the command in the venv. I have classmates that are also running on a M1 chip and aren't having this issue. I have psycopg2 installed as well and have verified it is by using the pip list command. This is my first post on Stackoverflow so I apologize for any inconsistencies or formatting. ((django-env) ) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> import psycopg2 as Database File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): no suitable image found. Did find: /Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture /Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.7_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/Users/stevenlopez/.local/share/virtualenvs/django-env-KW2l6c6v/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in … -
Django bootstrap: File is not being sent with the Post when using a modal form
In my Django App there is a page where users can upload files from their local machine (and do other things). The flow I built is so that users click on "+", a modal form comes up, users browse for a file on their local machine, select it and when they click save I submit the form. However, for some reason, the file isn't getting posted but it seems like I am posting only the name of the file. But I can't figure out why. file page ... <div class="list-files__btn-plus-wrp"> <a class="list-files__btn-plus" href="#" data-bs-toggle="modal" data-bs-target="#modal"> <img src="{% static 'action/img/project/files/icon_plus-file.svg' %}" alt="+"> </a> </div> {% include 'action/forms/modals/modal.html' %} modal.html <div class="modal fade" tabindex="-1" role="dialog" id="modal" > <div class="modal-dialog" role="document"> <div class="modal-content"> <!-- Popup --> <div class="pop-up-form"> <div class="pop-up-form__wrp"> <!-- Title --> <div class="pop-up-form__title-wrp"> <h2 class="pop-up-form__title">Dialog Title</h2> </div> <!-- END Title --> <!-- Form --> <form action="{% url 'action:project_files' project_id=project.id %}" method="POST" class="pop-up-form__form"> {% csrf_token %} <!-- Input File Name --> <div class="pop-up-form__input-wrp"> <label class="pop-up-form__label" for="fileName">File Name</label> <input class="pop-up-form__input" id="fileName" name="fileName" type="text" placeholder="File Name"> </div> <!-- END Input File Name --> <!-- Input Link --> <div class="pop-up-form__input-wrp"> <!-- Link --> <div class="pop-up-form__input-two-wrp"> <label class="pop-up-form__label" for="inputLink">Link</label> <input class="pop-up-form__input" id="inputLink" name="inputLink" type="text" placeholder="https://"> </div> … -
Djano how to apply multiple logic from same fuction depend on user page visite?
I wrote an function for download csv file. I have two type of user doctor and patient. When any user visit patient.html page he can download all patient data. I know I can write another function for downloads all doctor data when anyone visit doctor.html page but I want to do it in same function. here is my code: def exportcsv(request,slug=None): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) all_patient = Patient.objects.all() all_doctor = Doctor.objects.all() if slug == None: if all_patient: response ['Content-Disposition'] = 'attachment; filename=AllPatientData'+str(datetime.date.today())+'.csv' writer.writerow(['patient_id','patient_name','date_of_birth','age','phone','email','gender','country','state','city','zip_code','address']) for i in all_patient: writer.writerow([i.patient_id,i.patient_name,i.date_of_birth,i.age,i.phone,i.email,i.gender,i.country,i.state,i.city,i.zip_code,i.address]) if all_doctor: response ['Content-Disposition'] = 'attachment; filename=AllDoctorData'+str(datetime.date.today())+'.csv' writer.writerow(['docter_id_num','doctor_name','doctor_speciality','doctor_experience','date_joined']) for i in all_doctor: writer.writerow([i.docter_id_num,i.doctor_name,i.doctor_speciality,i.doctor_experience,i.date_joined]) return response my urls.py path('all-doctor/',AllDoctors.as_view(),name='all-doctor'), now it's downloading all patients and doctor data together. I want it will download only all doctor data when visit doctor.html page and all patient data when visit patient.html page. any idea how I can do it from this exportcsv view function? I think we can add different url parameter in exportcsv view but I don't know how to do that. -
File Structure in Django
I am learning Django and making an ecommerce website. My File Structure is as follows: [![My project File Structure][1]][1] Now I am uploading some pictures but could not able to access in the web. {% load static %} <div class="card" style="width: 18rem;"> <img src='{% static "images/aws.png" %}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> The above example is of an part of an carousal. Please help where I am missing something. How to give link to images in my web. [1]: https://i.stack.imgur.com/Eio3H.jpg -
DetalView get_context_data into ListView
I have a bit of a long question. I am writing a bookkeeping system in django I have a model for supplier as follows class Supplier(models.Model): supplier_name = models.CharField(max_length=50) supplier_number = models.IntegerField() def __str__(self): return self.supplier_name and also the expense model as class Expense(models.Model): invoice_number = models.CharField(max_length=50) invoice_date = models.DateField() supplier_name = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='expenses') description = models.CharField(max_length=100) def amt_excl_vat(self): if self.supplier_name.intra_community is None: vat_amount = (Decimal(self.expense_vat.vat_rate)/100)/(1+(Decimal(self.expense_vat.vat_rate)/100))*self.amt_incl_vat amt_excl_vat = self.amt_incl_vat - vat_amount else: vat_amount = 0 amt_excl_vat = self.amt_incl_vat - vat_amount return amt_excl_vat in my SupplierDetailView(DetailView) I calculated some values in def get_context_data like def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs["pk"] supplier = get_object_or_404(Supplier, pk=pk) expenses = supplier.expenses.all() expenditure_ex = 0 for item in expenses: expenditure_ex += item.amt_excl_vat() context['expenditure_ex'] = expenditure_ex return context the results give me correct values. I want to get the value of expenditure_ex in the SupplierListView(ListView) sorry for a long question TIA -
Nginx Reverse Proxy very slow on image upload
I use Nginx as a Reverse Proxy for a Django Project with Gunicorn. It is used for https. Everything on the site is loaded fast, except when I send a POST request with multipart form data. Then it takes 26 seconds for a 2 Megabyte image to process the request. For a 60 Kilobyte image it takes several seconds but still way too long. I measured the processing time of the Django view with the python time module and got around 80 milliseconds. During testing on a local development server it took around a second to process the request. And on the deployment server all media files are served quickly. So I guess the cause is an unsuitable configuration of Nginx with the multipart form request. My conf file is mostly untouched. I tried all StackOverflow solutions with modified cache settings and once with denabled cache but without success. Is there an information and configuration that I missed?