Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to have an external file input for choicefields in django?
I have ChoiceField in my Django model which consist of several choices and i am using the CheckboxSelectMultiple widget in forms to have multiple select options. models- BREAKFAST_CHOICES = (('fruits', 'A bowl of fruits with nuts'), ('tofu', 'Tofu Omlette'), ('1', 'Option 1'), ('2', 'Option 2'), ('3', 'Option 3'),) breakfast = MultiSelectField(choices=VBREAKFAST_CHOICES, null=True, blank=True, default=False) forms- widgets = { 'breakfast': forms.CheckboxSelectMultiple, } Now, in the future if I want to change the existing choice (options) with some other or add and delete options,how can i do this? Is there an easier way for a non programmer to just externally update a file and achieve this? i.e can my choicefield take an external file containing the list of options which can be edited as and when required. -
Apache2 + mod_wsgi + multiple virtual hosts for subdomains
I'm trying to setup two websites on a single server: domain.com subdomain.domain.com I am using Ubuntu 18.04.4 LTS, Apache/2.4.29, mod_wsgi/4.7.1, Python/3.8. Both the websites are Django applications. I created two virtual environments and installed mod_wsgi in each using the PyPi package and created two files in the mods-available directory and enabled the mods as described here: app1.load app2.load I created two configuration files under sites-available. The first configuration file is: <VirtualHost *:80> ServerName domain.com ServerAlias www.domain.com ServerAdmin abc@xyz.com #DocumentRoot /var/www/html LogLevel info ErrorLog ${APACHE_LOG_DIR}/error_app1.log CustomLog ${APACHE_LOG_DIR}/access_app1.log combined WSGIDaemonProcess app1 python-path=/home/ubuntu/app1 python-home=/home/ubuntu/anaconda3/envs/env1 WSGIProcessGroup app1 WSGIScriptAlias / /home/ubuntu/app1/app1site/wsgi.py <Directory /home/ubuntu/app1/app1site> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The second configuration file is: <VirtualHost *:80> ServerName subdomain.domain.com ServerAlias www.subdomain.domain.com ServerAdmin abc@xyz.com #DocumentRoot /var/www/html LogLevel info ErrorLog ${APACHE_LOG_DIR}/error_app2.log CustomLog ${APACHE_LOG_DIR}/access_app2.log combined WSGIDaemonProcess app2 python-path=/home/ubuntu/app2 python-home=/home/ubuntu/anaconda3/envs/env2 WSGIProcessGroup app2 WSGIScriptAlias / /home/ubuntu/app2/app2site/wsgi.py <Directory /home/ubuntu/app2/app2site> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> I get the following error logs: error.log [so:warn] [pid 8720:tid 140180032101312] AH01574: module wsgi_module is already loaded, skipping [mpm_event:notice] [pid 8727:tid 140180032101312] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.7.1 Python/3.8 OpenSSL/1.1.1 configured -- resuming normal operations [core:notice] [pid 8727:tid 140180032101312] AH00094: Command line: '/usr/sbin/apache2' [ssl:info] [pid 8733:tid 140179895777024] [client 73.16.240.233:49414] AH01964: Connection to child 66 established … -
How to customize form django with fields of the diferents Models
I need to display a field on a form and another field on a Model in html page. class CatracaForm(forms.Form): ra = forms.CharField(label='RA', max_length=30) class MotivoForm(forms.ModelForm): class Meta: model = Motivo fields = ['descrmotivo', 'obs'] In my HTML page I want show ra and descrmotivo field. The descrmotivo field should be a combobox component. How to make this? -
Calling a function inside a handler function | Razorpay | Django
I am not able to call a function inside a handler function. If I call the function complete() outside the handler function it throws me an errorJSONDecodeError. I want to call this function after the user pays and send the response data i.e razorpay_payment_id to the function complete(), so that I can parse the data in my server side/ success view. <script> var orderID = '{{order_id}}' var oID = '{{object.order_id}}' var name = '{{fullname}}' var email = '{{object.billing_profile}}' var keyID = '{{key_id}}' var orderAmount = '{{order_amount}}' function complete(){ var url = /success/ fetch(url, { method:'POST', headers:{ 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'razorpay_payment_id':razorpay_payment_id}) }) } var options = { "key": keyID, // Enter the Key ID generated from the Dashboard "amount": orderAmount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Monday", "description": "Test Transaction", "image": 'https://i.imgur.com/n5tjHFD.png', "order_id": orderID, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 "handler": function (response){ // alert(response.razorpay_payment_id); // alert(response.razorpay_order_id); // alert(response.razorpay_signature) var razorpay_order_id = response.razorpay_order_id var razorpay_payment_id = response.razorpay_payment_id var razorpay_signature = response.razorpay_signature var secret = '{{keySecret}}' var generated_signature = CryptoJS.HmacSHA256(razorpay_order_id + "|" + razorpay_payment_id, secret); // … -
Push rejected, failed to compile Python app. Push failed
I think the error is in requirement.txt but I don't know what My requirement.txt: asgiref==3.2.7 astroid==2.3.3 colorama==0.4.3 dj-database-url==0.5.0 dj-static==0.0.6 Django==3.0.5 django-cors-headers==3.2.1 djangorestframework==3.11.0 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 Pillow==7.1.1 pylint==2.4.4 python-decouple==3.3 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 static3==0.7.0 wrapt==1.11.2 -
Django: retrieving values of ManyToMany Relationship
I am attempting to implement a 'download csv' action in the django admin, to download the data associated with any model. To handle all models together, and to prevent the need for code changes if the model is changed, I am trying to implement one function (download_csv) that programmatically gets the fields associated with the model, and then saves a row for each object with the values of each field filled in. However, ManyToMany relationships result in an error such as: ManyToManyRel' object has no attribute 'value_from_object. How can I retrieve the values of these fields? The function works when downloading Lectures, but not Speakers, since the ManyToMany relationship is "reversed" (i.e. contained in the model Lecture). models.py class Speaker(models.Model): first_name = models.CharField(max_length=200) class Lecture(models.Model): lecture_title = models.CharField(max_length=200) speaker = models.ManyToManyField(Speaker) admin.py def download_csv(modeladmin, request, queryset): ''' Download CSV of all objects in queryset ''' try: main_model = modeladmin.corresponding_model except AttributeError: modeladmin.message_user(request, 'That action cannot be performed on these objects.') return fields = main_model._meta.get_fields() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=data.csv' writer = csv.writer(response, csv.excel) writer.writerow(fields) for obj in queryset: writer.writerow([field.value_from_object(obj) for field in fields]) return response admin.site.register(Speaker, SpeakerAdmin) admin.site.add_action(download_csv, 'export_csv') -
How to get a value passed throuhgt url to a class Create View in django?
Salutations good people of stack overflow, I read the docs and I been duckduckgoing this and I can't find and answer. I am pretty new to Django so if my approach is totally wrong please let me know. ^^ I am using Django 3.0 and I want to get a Primay Key of a model for a Post into a create view for a Comment Model with a foreign Key Post field, so that each Comment knows to which Post it belong in a one to many relationship. To accomplish I am defining the template as: <a href="{% url 'comment_new' post.pk %}"> <p class="text-center">Write a Comment</p> </a> In my urls.py I have: urlpatterns = [ path('<int:post>/new', CommentCreateView.as_view(), name='comment_new'), ] and in my views.py I have: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'Comment_new.html' fields = ('writing',) login_url = 'login' def get_object(self, **kwargs ): return models.objects.get(id=self.kwargs['post']) def form_valid(self, form): ''' Set the user which send the request as the form 'creator' ''' form.instance.user = self.request.user return super().form_valid(form) I'm trying to access the post int by overwriting get_object with return models.objects.get(id=self.kwargs['post']) , and the setting it to the comment model field in the form_valid with form.instance.post = self.post as I did … -
Why is my formset with filefield always valid?
I have an inlineformset_factory containing a filefield. Every time I submit the form, whether or not a file is attached, the formset is_valid() always returns True. I have set the blank parameter as False for the filefield. When I test the same formset by replacing the filefield with a charfield or just by the form itself (without inlineformset_factory), the code works as expected. Why is this formset always returning True for is_valid()? # models.py class Author(models.Model): author = models.CharField(max_length=128) description = models.CharField(max_length=1000) class BooksFile(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) books_file = models.FileField(blank=False) # forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('author', 'description') class BooksFileForm(forms.ModelForm): class Meta: model = BooksFile fields = ('books_file',) BooksFileFormSet = forms.inlineformset_factory( Author, BooksFile, form=BooksFileForm, fields=('books_file',), extra=1, can_delete=False, can_order=False ) # views.py class CreateAuthorView(CreateView): template_name = "author_create.html" model = Author form_class = AuthorForm def get_context_data(self, **kwargs): context = super(CreateAuthorView, self).get_context_data(**kwargs) if self.request.POST: form = self.get_form(self.form_class) context["books_file"] = BooksFileFormSet( self.request.POST, self.request.FILES, instance=form.instance ) else: context["books_file"] = BooksFileFormSet() return context def form_valid(self, form): context = self.get_context_data() books_file = context["books_file"] print(form.data.get("author")) print("books_file.is_valid()", books_file.is_valid()) # ***This always prints True*** return redirect(self.get_success_url()) def get_success_url(self): return reverse("author_list") # author_create.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form }} </div> <div> … -
How can I combine three inputs into one variable and use it to fetch data from a database using Django?
all! I am working on my first Django project and learning a lot along the way. So far, I have set up a very simple website and am having trouble with the next steps. Through this project, I am hoping to achieve a website that provides users with reliable resources based on how they answer the three questions they are asked. Website Explanation: The user opens the website and is prompted to click a button to go to the first step. The first step asks the user to choose the subject they would like a resource on (for now, all of the listed subjects are related to cooking). Then, they choose their level of expertise (beginner, intermediate, advanced). Finally, they choose a preferred medium for their resource (article/blog, video, book). Based on the subject, their level of expertise, and their preferred medium, the last page will give the user a resource that is retrieved from a linked database. Where I Am Stuck: So far, I have created five pages (home page, one page for each question, and a results page) and have set up the choices for each question. Now, I am having trouble finding a way to combine the … -
Django sum() function
I have a Cart model and I want to sum all the item values. I can successfully sum all the items subtotal individually but when I try to make the Grand Total I get the following error maximum recursion depth exceeded while getting the str of an object This is my model class class CartItem(models.Model): ... def get_cart_item_subtotal(self): meal_price = self.meal.price if self.options: options = self.options.price else: options = 0 if self.ingredients: ingredients = sum( [ingredient.price for ingredient in self.ingredients.all()] ) else: ingredients = 0 return (meal_price + options + ingredients) * self.quantity class Cart(models.Model): items = models.ManyToManyField("CartItem", blank=False) ... def get_cart_subtotal(self): return sum([item.get_cart_item_subtotal for item in self.items.all()]) If possible I would like to keep the sum in the Cart model since then I have to check if the minimum order is met. Thanks in advance for any help which could be provided -
Question about overriding the __init__ method of models.Model in Django
I created an app to keep track of inventory and modify it with a form. The updated_by field changes to the current logged in user when the update button is pressed. The only issue is that every instance's 'updated_by' field is changing. I great post suggested to override the init method of the models.Model. I am both new to django and python and do not what to write in my conditional. Also if someone could explain or reference what is going on i would be very greatful. Views.py def inventory_update(request): title = 'Update Inventory' UserInventoryFormset = modelformset_factory(Inventory, form=InventoryUpdateForm, extra=0) if request.method == 'POST': formset = UserInventoryFormset(request.POST) if formset.is_valid(): for form in formset: updated = form.save(commit=False) updated.updated_by = request.user updated.save() else: formset = UserInventoryFormset() context = {'formset': formset, 'title': title } return render(request, 'main/inventory_form.html', context) Models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item __original_stock = None __original_par = None __original_updatedBy = None def __init__(self, *args, **kwargs): super(Inventory, self).__init__(*args, **kwargs) self.__original_par = self.par self.__original_stock = self.stock self.__original_updatedBy = self.updated_by def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.par != self.__original_par or self.stock != self.__original_stock: # what goes … -
Django and post request to an external API in different views
So i want to create a Django App where my users can post data through a form and make a post request to an external API, but getting the response in the same page/view For example, i have my view class Home(TemplateView): template_name: 'home/index.html' And i have my index.html: <form id="formdata" > <select id="options"> <option id="sku">Option 1</option> <option id="sku2">Option 2</option> </select> <input name="number" type="text" id="number"> <select id="price"> <option id="price1">$5</option> <option id="price2">%10</option> </select> <button type="button" data-loading-text="enviando..." onclick="submitInfo()">Send</button> </form> Let's ignore the fact HTML may be wrong, it is a basic structure of a form with selects and input field, but note that i need to pass "product", "number" and "price" as parameters in the post request. The thing is that when the user clics on the submit button, they make a post request to an external api, i know i can do int with JavaScript using fetch, but the thing is that i need to pass my personal Token Key in the body params, also i'd like to hide the real api url hiding it with an url of my website, for example: www.myurl.com/my-api-call So i'm thinking about creating a "external_api_view" with post request, something like this: import requests import time … -
Vuejs axios.post method gives wbs disconnected error in console
I keep getting this error [WDS] disconnected! in the console when I try to run axios.post. I have done my research so I know that the The problem seems to be that I have not included the port number in url webpack-dev-server/client?http://127.0.0.0/ However I do not know how to make this change. -
Need help on checking/unchecking a checkbox based on the passed data
I am creating a website that a patient can manually insert their data and save into a database. Then, the data can be accessed and be modified like an “edit view”. I am using django. I need help on displaying the saved data on the html. I was able to figure out how to display the original data of the patient on the input that are text or integers. However, I can’t find a way to display the original data on the checkbox. First, I will search the patient’s name After searching the patient’s name, I would like the checkbox to be checked based on the data Before and After Could you help me on coding for the html? users = patient’s data form = form field to get an input Any help will be greatly appreciated. Thank you in advance. **** Need to modify {form.q1}} and {{form.q2}} to be checked or unchecked based on user.q1 and user.q2**** *user.q1 is MultipleChoiceField (this is the most troubled one) * *user.q2 is a true/false data * modify_patient.html <style> table { table-layout: fixed; font-family: arial, sans-serif; border-collapse: collapse; width: 80%; } th.one, th.three, { width: 15%; background-color: #dddddd; } th.two, th.four { width: … -
Baffling error filtering Django objects of derived class by values in foreign key linked class
An app I am converting from Django 1.10 to 3.0 contains classes defined as follows (including only relevant fields) : class DataSet(models.Model): ::: class SurveyRunDataSet(DataSet): survey_run = models.ForeignKey('survey.SurveyRun', null=True, on_delete=models.CASCADE, ..) ::: But the following call, which worked fine at Django 1.10, now fails at Django 3.0 : survey_run_id = .. report_ids = (SurveyRunDataSet.objects. filter(survey_run_id=survey_run_id,report__report_type=AnalysisReport.SUMMARY). values_list('report_id', flat=True).distinct()) The error is : Cannot resolve keyword 'survey_run_id' into field. Choices are: aggregatedataset, filtereddataset, flush_date, id, materalised_source_data_set, materialiseddataset, name, primary_dataset, psession_source_data_set, psessiondataset, report, report_id, source_data_set, surveyrundataset Most of the above choices are other classes that inherit from "DataSet". So Django goes delving upwards in a bizarre wrong direction in the class structure, while missing a field item which is right in front of its nose, in the very model the objects.filter() is being applied to. It makes absolutely no sense! The model tables in postgres are exactly as expected : # \d dataset_surveyrundataset dataset_ptr_id | integer | not null status | character varying(10) | not null base_dataset | boolean | not null schema_mapping | text | not null survey_run_id | integer | "dataset_surveyrundat_survey_run_id_8e235a8a_fk_survey_su" FOREIGN KEY (survey_run_id) REFERENCES survey_surveyrun(id) DEFERRABLE INITIALLY DEFERRED # \d survey_surveyrun id | integer | not null default nextval('survey_surveyrun_id_seq'::regclass) ::: … -
i stack over and over in djjango
i watched few videos to learn how to use Django. a lot of them coming older version of Django and because im a beginner in Django so it makes it harder. the problem is that in urls.py file they are showing how to make it with "url" way and i have the newer version of Django which is showing me with "path" way. what i did wrong here that it does not showing me: from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path("", views.home, name = "home"), path("adoptions/(\d+)/", views.pet_detail, name = "pet_detail"), ] cause what i actually did, i looked on the tutorial and implemented on the path. maybe i did it wrong i dont know. and this is not the first time that i stack on the same place. -
After validation error, keep user input using django
After validation errors appear - Django form, how do I retain the inputs that the user had entered? I didn't use {{form}} , {{form.as_p}}, {{form.as_table}} but manually outputed the form. -
How to upload and display videos on django
I have been trying to add a view that uploades videos and displays them in the main template, well while adding code, I realized that the view that uploades the file isn't being rendered while the view that shows the uploded file in the template gets rendered but it doesnt show anything because nothing is being uploded. I dont know where the error might be but I think it is on the views.py, maybe the urls.py. views.py def upload(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('home') print('succesfully uploded') else: form = PostForm() print('didnt upload') return render(request, 'home.html', {'form': form}) def home(request): contents = Post.objects.all() context = { "contents": contents, } print("nice") return render(request, 'home.html', context) urls.py urlpatterns = [ path('', views.home, name='home'), path('upload', views.upload, name='upload'), ] models.py class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('text', 'video') exclude = ['user'] home.html (uplodes the content and displays it) <div class="user-content"> {% for content in contents %} <li class="">{{ content.text }} {% if content.video %} <video class="video" width='400'> … -
How to import AbstractUser correctly
I am building an API by using DRF, and while I try to register an User django-registeration, I realized that I did not name my custom User differently, I have entries in my database, so if I can save my saved objects it will be better for my members. This is my model: class User(AbstractUser): bio = models.TextField() I have added to settings and set my forms # settings.py AUTH_USER_MODEL = "profiles.User" # forms.py from yogavidya.apps.profiles.models import User from django_registration.forms import RegistrationForm class UserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = User # urls.py path('accounts/register/', RegistrationView.as_view( form_class=UserForm, success_url="/" ), name="django_registration_register"), path('accounts/', include('django_registration.backends.one_step.urls')), path('accounts/', include('django.contrib.auth.urls')), now I get an error: You are attempting to use the registration view <class 'django_registration.backends.one_step.views.RegistrationView'> with the form class <class 'yogavidya.apps.profiles.forms.UserForm'>, but the model used by that form (<class 'django.contrib.auth.models.User'>) is not your Django installation's user model (<class 'yogavidya.apps.profiles.models.User'>). why does my UserForm uses User model different than I have imported ? How can I fix it ? Thanks -
Unable to display parent table with child table in a for loop with template tagging in Django
I want to display an unordered list of NBA teams from my teams table database. Within each team, I want an ordered list of players on that team. So basically I want to produce a list of all objects from my parent table and for each object from the parent table I want a list of all objects from the child table related the parent table. I understand that the problem is methods are not allowed in template tagging, so 'team.players_set.all()' would not be allowed. How else can I get the results that I want? class Teams(models.Model): name = models.CharField(max_length=20, unique=True) num_of_plyrs = models.IntegerField() def __str__(self): return f"{self.name} have {self.num_of_plyrs} players." class Meta: verbose_name_plural = "Teams" class Players(models.Model): name = models.CharField(max_length=20) team = models.ForeignKey(Teams, on_delete=models.CASCADE) def __str__(self): return f"{self.name} plays for {self.team}" class Meta: verbose_name_plural = 'Players' __________________________________________________________________________________ def teams(request): teams = Teams.objects.all() context = {'teams': teams} return render(request, 'one_app/teams.html', context) __________________________________________________________________________________ <h3>NBA Teams</h3> <ul> {% for team in teams %} <li> <p>Team: {{ team.name }}</p> <p>Number of players: {{ team.num_of_plyrs }}</p> <ol> {% for plyr in team.players_set.all() %} <li>{{ plyr.name }}</li> {% endfor %} </ol> </li> {% empty %} <li>There are no teams listed.</li> {% endfor %} </ul> -
why is it showing "type object 'CourseInstructor' has no attribute 'objects' "
i'm using class based views because classes can't be defined in function based views. i have two tables (Course, CourseInstructor) when i created the first table and checked it there was no such error but when i created the second it displayed that error from django.shortcuts import HttpResponse, render from django.views import View from .models import Course, CourseInstructor class Course(View): def get(self, request): courses = Course.objects.all() return render(request, 'examscheduling.html', {'courses': courses}) class CourseInstructor(View): def get(self, request): coursesInstructor = CourseInstructor.objects.all() return render(request, 'examscheduling.html', {'coursesInstructor': coursesInstructor}) -
How can I get this Django CreateView to call my Django-FSM transition?
I'm working on an application that allows logged in users to submit news articles to the database where they can be reviewed and editing before being published. Their submissions could also be rejected. I'm using the cool django-fsm package to manage the state changes and django-bootstrap-modal-forms to display the news submission form and submit it via Ajax. I'm having trouble getting my class-based view to trigger the django-fsm transition in my model. The data is saved to the database, but the receive() method never gets called, so I don't get the confirmation email, for example. I can call receive() manually from the command line and generate the email, so I know that part is working. Here's the code: # views.py class NewsSubmitView(LoginRequiredMixin, BSModalCreateView): template_name = "modals/submit_news.html" form_class = NewsSubmitForm success_message = "Success: News submitted." def form_valid(self, form): response = super(NewsSubmitView, self).form_valid(form) user = self.request.user form.instance.submitted_by = user form.instance.slug = slugify(form.instance.headline) return response def save(self, commit=True): instance = super().save(commit=False) instance.receive(activity_slug=self.kwargs.get("slug")) instance.save() return instance def get_success_url(self): return reverse_lazy("news", kwargs={"slug": self.kwargs["slug"]}) # models.py @transition(field=state, source=ArticleState.RECEIVED, target=ArticleState.RECEIVED) def receive(self, activity_slug, by=None): """Receive the submission""" self.slug = slugify(self.headline) self.activity = Activity.objects.get(slug=activity_slug) self.send_article_received_email() def send_article_received_email(self): context = { "submitter": self.submitted_by, "headline": self.headline, } msg_to_submitter = render_to_string( … -
Part of celery-beat periodic task not triggered
I have two celery-beat periodic tasks are configured with the same crontab schedule to run in the system. But at the start of month, one of them is not sending due task to celery worker. From the django admin panel, one task last_run_time is None, which indicates that it is not triggered. I tried to configure the crontab schedule to '''15 * * * *''' and it runs successfully at minute 15. -
Django Admin with Django debug toolbar same table being queried multiple times for each column?
I am using django-debug-toolbar and loading a large table with no foreignkeys. The table size is about 20,000 rows - 15mb - however the django list page is taking extremely long to load, 10s+ to load. When i remove columns from the list_display it seems to load faster. When I am querying the entire dataset however using Ref_ICD.objects.all() via get_queryset it doesn't seem to take that long to query, sub 3s - which is as expected because its a linear query. Can anyone tell me whats wrong with my code? Am i reading the django-debug-toolbar wrong? Either way the page loads really slow. class TimeLimitedPaginator(Paginator): def _get_count(self): if not hasattr(self, "_count"): self._count = None if self._count is None: try: key = "adm:{0}:count".format(hash(self.object_list.query.__str__())) self._count = cache.get(key, -1) if self._count == -1: self._count = super().count cache.set(key, self._count, 3600) except: self._count = len(self.object_list) return self._count count = property(_get_count) @admin.register(Ref_ICD) class ICDAdmin(admin.ModelAdmin, WYSIWYG): def get_queryset(self, request): con = get_redis_connection("default") qs = Ref_ICD.objects.filter(FullCode="J449") # qs = Ref_ICD.objects.all() # pickled_object = pickle.dumps(qs) # con.set('ref_icd', pickled_object) unpacked_object = pickle.loads(con.get('ref_icd')) # qs == unpacked_object return qs paginator = TimeLimitedPaginator show_full_result_count = False list_per_page = 10 search_fields = ['FullCode'] list_filter = ( 'CategoryCode', 'DiagnosisCode', 'FullCode', 'AbbreviatedDescription', 'FullDescription', 'CategoryTitle' ) … -
Django/HTML - How to stay on the same page after a search
I'm working on a Django project and i have a problem with URL pattern when i'm using form. So i have a search bar on the home page but also on the search page doing the same search : /home/ and /home/search/ When I search for the first time it redirects me to search wich is normal from home to home/search/. But when i want to search again i want to stay to this /home/search/ but it redirects me to another search like below /home/search/search/ It says error because obviously it's not in the url pattern mentioned in urls.py Actually what i've done is the following (i know it's dirty programming) : if url contains search then <form method="post" action=""> else <form method="post" action="search/"> If it is in home page then go to search page but if it is in search page stay here. I'm wondering if there is a better way to resolve this problem ? Thanks for reading guys and i hope you will help me.