Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registering multiple admin classes with a model in Django admin
I've two Admin classes for a single model: from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import * class ProductSummernoteAdmin(SummernoteModelAdmin): summernote_fields = ('description',) class ProductAdmin(admin.ModelAdmin): ... admin.site.register(Product, ProductSummernoteAdmin) I want to register both ProductSummernoteAdmin and ProductAdmin with Product model. How to do that? As, i can't register same model twice. -
How to search for the mode of a field in a one to many relationship in django's ORM?
I have this one to Many relationship between dish and restaurant. SPICINESS_CHOICES = ( ("M", "Mild") ("H", "Hot") ("SH", "Super hot") ) class Restaurant(Model): name = models.CharField(max_length=50) class Dish(Model): restaurant = models.ForeignKey(Restaurent) name = models.CharFiedl(null=True, max_length=50) price = models.IntegerField(max_length=10, null= False) spicy = models.CharField(null= True, choices=SPICINESS_CHOICES) I would like to be able to search Restaurants for the most occurring spiciness of their dishes or the mode of the spiciness of their dishes https://en.wikipedia.org/wiki/Mode_(statistics). Django does not seem to have functionality to implement this easily. So let's say we have three restaurants, Anny's, Domino and Verspucie. Anny's has different 8 dishes of which 2 dishes are labeled as being Hot, all other dishes are labeled as Mild, since the owner wants to be able to have a varied menu for children Domino has 9 different dishes of which 5 dishes are labeled as being Hot, 2 as being Super Hot and 2 as being mild. Verspucie has 10 different dishes of which 8 are labeled as being Super Hot, one 1 labeled as Mild and 1 is labeled as Hot. Because I want to find the correct restaurant from a whole list of restaurants, I would like to be able to … -
python manage.py runserver not working pls solve
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '3' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin 'a' in CORS_ORIGIN_WHITELIST is missing scheme or … -
Django | The id of the records of more than 1000 have a period
when I use the id of an object that is greater than 1000 on my django template I get a period. For example: {{item.id}} should be 1200 but the ouput is 1.200 How can I solve this? -
How to use aws boto library to test Django website?
I want to test my Django application before deploying using django.test module. Since I'm using DynamoDB for storing my data and all the URL endpoints are programmed using boto3 library to GET and POST data at DynamoDB. How can I test my Django views/url endpoints using boto3? Please comment for any extra information. Thank you!! -
Django - How can test models.ManyToManyField spanning multiple databases?
Now I have to integrate a set of apps spanning multiple databases. One database is 'default' which I can do migrations freely and many models are routed to it. Another is, for example, 'another_db' to which only Author model is routed, and I have no rights to change. I ran into a problem when I tested like: # one_app/tests.py ... class AuthorTest(TestCase): databases = '__all__' multi_db = True @classmethod def setUpTestData(cls): super().setUpTestData() cls.post_1 = Post(title="post_1_title") cls.post_1.save() cls.author_1 = Author(name="author_1_title") cls.author_1.save() def test_can_add(self): self.assertEqual(self.post_1.authors.count(), 0) self.post_1.authors.add(self.author_1) self.assertEqual(self.post_1.authors.count(), 1) # Here, the test fails. Test message shows: Creating test database for alias 'default'... Creating test database for alias 'another_db'... System check identified no issues (0 silenced). FE ====================================================================== ERROR: test_can_add (one_app.tests.AuthorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 274, in __call__ self._post_teardown() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1009, in _post_teardown self._fixture_teardown() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1177, in _fixture_teardown connections[db_name].check_constraints() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 331, in check_constraints bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: The row in table 'one_app_post_authors' with primary key '1' has an invalid foreign key: one_app_post_authors.author_id contains a value '1' that does not have a corresponding value in another_app_author.id. ====================================================================== FAIL: test_can_add (one_app.tests.AuthorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hiroyuki/PycharmProjects/some_app/one_app/tests.py", line 23, in test_can_add … -
Django admin panel has a weird look after upgrade
Right after upgrade to Django 3.1.2 I went to my admin panel. Main page has a standard look with no bugs. But as soon as I click on any object, I see this picture. Logs also look OK. [28/Oct/2020 15:04:52] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [28/Oct/2020 15:04:52] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 200 1789 [28/Oct/2020 15:04:52] "GET /static/admin/js/core.js HTTP/1.1" 200 5723 [28/Oct/2020 15:04:52] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 363 [28/Oct/2020 15:04:52] "GET /static/admin/js/actions.js HTTP/1.1" 200 6766 [28/Oct/2020 15:04:52] "GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 200 6918 [28/Oct/2020 15:04:52] "GET /static/admin/js/urlify.js HTTP/1.1" 200 8941 [28/Oct/2020 15:04:52] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 200 1360 [28/Oct/2020 15:04:52] "GET /static/admin/js/prepopulate.js HTTP/1.1" 200 1530 [28/Oct/2020 15:04:52] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [28/Oct/2020 15:04:52] "GET /static/admin/css/changelists.css HTTP/1.1" 200 6190 [28/Oct/2020 15:04:52] "GET /static/admin/js/vendor/jquery/jquery.js HTTP/1.1" 200 280364 [28/Oct/2020 15:04:52] "GET /admin-extended/jsi18n/ HTTP/1.1" 200 14892 [28/Oct/2020 15:04:52] "GET /static/admin/js/vendor/xregexp/xregexp.js HTTP/1.1" 200 128820 [28/Oct/2020 15:04:52] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [28/Oct/2020 15:04:52] "GET /static/admin/img/tooltag-add.svg HTTP/1.1" 200 331 [28/Oct/2020 15:04:52] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331 So I consider I don't have any problems with getting needed CSS files. What's the problem? Is it my mistake? EDIT1: When … -
Password recovery problem. Says the field is not filled in
Faced with the problem that the form is not validated. I want to make a password recovery form and use the built-in one, but for some reason it fails to validate. I printed out the request, form, form.errors. <QueryDict: {'csrfmiddlewaretoken': ['WHHpcIDpzHkV6NuCwhCcMHPdMLe7kiiF0q3zjRulXIgevmpTartl3T2lScowrUaA'], 'email': ['test.gmail.com', '']}>. <tr><th><label for="id_email">Email:</label></th><td><ul class="errorlist"><li> Negative field.</li></ul><input type="email" name="email" maxlength="254" required id="id_email"></td></tr>. <ul class="errorlist"><li>email<ul class="errorlist"><li>Mandatory field.</li></ul></ul>. file forms.py: from django.contrib.auth.forms import PasswordResetForm class UserForgotPasswordForm(PasswordResetForm): email = forms.EmailField(required=True,max_length=254) class Meta: model = User fields = ("email") file views.py: def UserResetPassword(request): if request.method == 'POST': form = UserForgotPasswordForm(request.POST) if form.is_valid(): form.save(from_email='blah@blah.com', email_template_name='market/email_template.html') -
Django Rest Framework: Rest-auth email verification - Server Error 500
I'm trying to enable email verification on Django Rest Framework with rest-auth. It works when I use console.Backend, however when I enable real emails via smtp, it gives me a Server Error 500 after registration. I'm using the same smtp settings as my node.js mail server which works perfectly, so I'm positive the smtp settings are correct. Does anyone have an idea what could cause this? I'm not sure what other code is responsible for this, please let me know if I need to provide something else. Here are the relevant settings: REST_SESSION_LOGIN = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory'#'none' #mandatory if enabled ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None LOGOUT_ON_PASSWORD_CHANGE = False OLD_PASSWORD_FIELD_ENABLED = False AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 6, } }, ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.zxcs.nl' EMAIL_PORT = 465 EMAIL_HOST_USER = 'info@xxxxx.nl' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxx' EMAIL_USE_TLS = True EMAIL_USE_SSL = False AUTH_USER_MODEL = 'users.CustomUser' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer', } -
How can I filter a queryset inside a django form?
I'm trying to add chat functionality to my app and right now I can add users to existing chats but what I need to do is filter users that are not already in the chat in the form. I'm using django form with passed arguments to filter my users but I'm not getting any results. My Chat model has a m2m field to user called 'users' and my User has a m2m field called 'friends' forms.py class AddUserToChatForm(forms.ModelForm): class Meta: model = Chat fields = ('users', ) def __init__(self, chat, friends, request, *args, **kwargs): self.request = request self.chat = chat self.friends = friends super(AddUserToChatForm, self).__init__(*args, **kwargs) self.fields['users'] = forms.ModelMultipleChoiceField(queryset=self.request.user.friends.exclude(user__in=chat.users.all()), widget=forms.CheckboxSelectMultiple (attrs={'class': 'add-people-to-chat-form'}), label='Friends:') views.py def add_users_to_chat(request, pk): chat = Chat.objects.get(pk=pk) friends = request.user.friends.all() if request.method == 'POST': form = AddUserToChatForm(chat, friends, request, request.POST) if form.is_valid(): users_to_add = form.cleaned_data['users'] chat.users.add(*users_to_add) chat.save() return redirect('messages') else: form = AddUserToChatForm(chat, friends, request, instance=None) return render(request, 'add_users_to_chat.html', {'form': form, 'chat': chat, 'friends': friends}) P.S. Using filter inside form queryset returns the entire list of user friends when using exclude returns an empty set. -
AppleOAuth2() is giving error __init__() takes at least 2 arguments (1 given). What is the argument which needs to be passed here?
class AppleOAuth2(BaseOAuth2): """apple authentication backend""" name = 'apple' ACCESS_TOKEN_URL = 'https://appleid.apple.com/auth/token' SCOPE_SEPARATOR = ',' ID_KEY = 'uid' -
How to add the result of a custom query to the Django Admin Site change_form template?
My web application manages hospitalizations and specialist examinations. Some of these exams may have been performed during a hospitalization, but I have no connection between the hospitalizations and the specialist exams. When the user modifies the data of an exam, I would like him to see at the bottom of the page all the admissions started before the exam and finished after the exam, because one of them could be the admissions where the exam was taken. How can I show the result of the query described above at the bottom of the "change_form" template of the Django Admin Site? Thanks in advance. -
Serialize dictionary to JSON in DRF
I have a method associated with the Statistic model returning the dictionary: def get_user_statistics(self, user): ... return { 'week_right: week_right, 'week_wrong': week_wrong, 'week_near' : week_near, 'days': days, 'day_right': day_right, 'day_wrong': day_wrong, 'day_near': day_near } where day_right, day_wrong, day_near and days are lists. I would like to send the result of this method in the form of JSON to the application written in Rect. However, when method get in generics.RetrieveAPIView looks like below: def get(self, request, *args, **kwargs): user = self.request.user user_stats = Statistic.objects.get_user_statistics(user) serializer = json.dumps(user_stats, cls=DjangoJSONEncoder) return Response(serializer) This Response is a simple string and I have to use JSON.parse JavaScript to process it. Is there any other way to serialize my dictionary to avoid using JSON.parse? -
Python Crash Course new_entry.save() causing me errors
So I'm following a book called Python Crash Course. And I'm currently working on its Django project, and I am encountering a problem that's apparently in the views.py. Here is the entire code for views.py: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise … -
How to run a function in Django after a certain time passed by
Having the model of Station with the below fields: class Station(models.Model): is_available = models.BooleanField(default=True) unavailable_until = models.DateTimeField(null=True,blank=True) I can define until when my station is unavailable by giving a DateTime value , so when that action happens the is_available value turns to False. I want to turn the is_available value to True every time the unavailable_until value passed by(comparing with the current time based on the timezone). How can I achieve an automation like this? Imagine that I have a lot of Station records which belong to station owners which can update the availability (assign new unavailable_until value if passed by) whenever they want. I think the logic could be something like: def turn_availability_to_true(station): if (station.unavailable_until < current_time): station.is_available = True But how can I implement a function like this to be called by its own when the unavailable_until value passed by? -
Two forms on the same model, pb save
I'm a beginner in django, and my code is not yet factorized I have a problem during registration or update, delivery address overwrites billing address ? forms.py ------------------------------------------------------- class AddressForm(ModelForm): class Meta: model = Address fields = ( 'address', 'address2', 'zipcode', 'city', 'country', 'phone1', 'phone2', ) class AddressDeliveryForm(ModelForm): class Meta: model = Address fields = ( 'address', 'address2', 'zipcode', 'city', 'country', 'phone1', 'phone2', )' views.py--------------------------------------------------------------- @login_required(login_url="index") def updateCustomer(request, pk): customer = Account.objects.get(id=pk) addressbilling = address.objects.get(users_id=pk,delivery_address=False) addressdelivery = address.objects.get(users_id=pk,delivery_address=True) account_form = AccountForm(instance=customer) address_form = AddressForm(instance=addressbilling) addressdelivery_form = AddressDeliveryForm(instance=addressdelivery) if request.method == "POST": account_form = AccountForm(request.POST, request.FILES, instance=customer) address_form = AddressForm(request.POST, request.FILES, instance=address) addressdelivery_form = AddressDeliveryForm(request.POST, request.FILES, instance=addressdelivery) if account_form.is_valid() and address_form.is_valid() and addressdelivery_form.is_valid(): account_form.save() address_form.save() addressdelivery.save() return redirect('console_admin:list_customer') context = { 'account_form': account_form, 'address_form': address_form, 'addressdelivery_form': addressdelivery_form, 'customer' : customer.id } return render(request, 'console_admin/customer_form.html',context) -
Why I'm getting "Request failed with status code 404"
views.py class SearchTodo(viewsets.ModelViewSet): serializer_class = todoserializer def get_queryset(self): status = self.kwargs["status"] return JsonResponse({"data":Todo.objects.filter(status=status)}, content_type='application/json') urls.py for rest framework router = routers.DefaultRouter() router.register(r"^todo/(?P<status>\w+)$",views.SearchTodo,"SearchTodo") router.register(r"todo",views.todoview,"todor") urlpatterns = [ path('admin/', admin.site.urls), path("api/",include(router.urls)) ] Axios code for filter object which has the status True const data = () => { axios .get(`http://127.0.0.1:8000/api/todo/True`) .then((res) => settasks(res.data)) .catch((error) => alert(error.message)); }; but whenever this function run I got a 404 bad request error where I'm getting wrong. -
Test password protected page django
I want to write test cases about password-protected pages. I have /management/edit page. it is loginrequired page. My test case currently likes below, but it is failed. I am expecting to get 200 but instead of I got redirection(302) Tests.py from django.test import TestCase, Client # Admin panel Test cases class PageTest(TestCase): # it will redirect user to loginpage def test_admin_page(self): response = self.client.get("/management/") self.assertEquals(response.status_code, 302) def test_edit(self): c = Client() c.login(username='admin', password='admin') response = c.get("/management/edit/") self.assertEquals(response.status_code,200) -
Markup Deprecated issue finding compatible textile
I'm updating Django project to the latest version, since django markup is deprecated I'm using it's replacement django-markup-deprecated It's throwing an error of missing textile for python File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/markup_deprecated/templatetags/markup.py", line 27, in textile raise template.TemplateSyntaxError("Error in 'textile' filter: The Python textile library isn't installed.") django.template.exceptions.TemplateSyntaxError: Error in 'textile' filter: The Python textile library isn't installed. [28/Oct/2020 14:15:29] "GET / HTTP/1.1" 500 166483 so I tried to install it this way pip install textile which doesn't work and throws a different incompatibility issue File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/markup_deprecated/templatetags/markup.py", line 30, in textile return mark_safe(force_text(textile.textile(force_bytes(value), encoding='utf-8', output='utf-8'))) TypeError: textile() got an unexpected keyword argument 'encoding' [28/Oct/2020 14:18:31] "GET / HTTP/1.1" 500 160593 -
OSError: Cannot load native module 'Crypto.Cipher._raw_ecb' on Apache mod_wsgi CentOS 8
I'm trying to run a django project on an apache server. The django server runs fine on its own but fails when running through mod_wsgi. It returns the error as follow : OSError: Cannot load native module 'Crypto.Cipher._raw_ecb': Trying '_raw_ecb.cpython-39-x86_64-linux-gnu.so': /home/user/django/centos_env/lib/python3.9/site-packages/Cryptodome/Util/../Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so: failed to map segment from shared object, Trying '_raw_ecb.abi3.so': /home/user/django/centos_env/lib/python3.9/site-packages/Cryptodome/Util/../Cipher/_raw_ecb.abi3.so: cannot open shared object file: No such file or directory, Trying '_raw_ecb.so': /home/user/django/centos_env/lib/python3.9/site-packages/Cryptodome/Util/../Cipher/_raw_ecb.so: cannot open shared object file: No such file or directory I checked that the file were there. I checked Python home variable and tried to import Crypto.Cipher from the python interpreter(which worked). Everything seems fine. I tried to compile pycryptodome from source but it didn't help either. -
How to override Django get_search_results method in ModelAdmin, while keeping filters working as expected?
I have a Model admin where I override get_search_result this way def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(OccupancyAdmin, self).get_search_results( request, queryset, search_term ) search_words = search_term.split(",") if search_words: q_objects = [ Q(**{field + "__icontains": word}) for field in self.search_fields for word in search_words ] queryset |= self.model.objects.filter(reduce(or_, q_objects)) return queryset, use_distinct The suggestion comes from here: Is there a way to search for multiple terms in admin search? django The problem I am facing is the following: neither the DateTimeRangeFilter from rangefilter nor my custom SimpleListFilter work as expected anymore. The filters seem like being disabled. I looked at the SQL queries being performed and they seem alright. I am pretty sure I am messing up with the querysets somehow but don't know how to debug this. -
Django: Avoid duplicates image uploads from admin panel
I have a model with an ImageField, which allow an image upload from the panel admin of Django. I would like to check if the image already exists, before saving the model. If it's the case, I would like to display a popup (or a warning on the same page) with both images, to allow users to compare images, and allow saving if it's a false positive. For the image comparison, I'm going to use imagehash.average_hash() algorithm which gave me good results from my tests. So my questions are: How to get the file content (to compute the aHash), before the model save. How to display a popup or modify the modelAdmin page to allow the check of false positive. Any help is appreciated! -
How to count the value of dictionary using queryset in django
I used .value('post_id') in django to bring the following values. <QuerySet [{'post_id': 3}, {'post_id': 2}, {'post_id': 1}, {'post_id': 3}]> If you count the value of each dictionary, you will have one, one, and two, respectively. Which queryset should I look for, instead of counting it as a queryset without for loop ? -
Django - very slow annotation when annotation more than 1 field
I'm building a chat functionality for my django app. I made Message model, which looks like this: class Message(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='messages_sent', blank=True, null=True) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='messages_received', null=True) message = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) Now I want to create a view with a list of users, ordered by the last message date with currently logged in user. def get_queryset(self): qs = UserModel.objects.all() user = self.request.user # exclude self qs = qs.exclude(pk=user.pk) qs = qs.annotate(last_sent_date=Max("messages_received__created_at", filter=Q(messages_received__sender=user))) qs = qs.annotate(last_received_date=Max("messages_sent__created_at", filter=Q(messages_sent__receiver=user))) qs = qs.annotate(last_message_date=Greatest('last_sent_date', 'last_received_date')) qs = qs.annotate(has_messages=Case( When(Q(last_received_date__isnull=False) | Q(last_sent_date__isnull=False), then=True), default=False, output_field=BooleanField() )) return qs.order_by(F('last_message_date').desc(nulls_last=True)) This was working very well, until I created many Message objects for 2 test users, each of them had 8k sent and 8k received messages (16k total). This slowed down the query significantly, and now it takes even 40-50 seconds (for small amounts it was below 500ms). After some investigation I discovered that the main problem is in those lines: qs = qs.annotate(last_sent_date=Max("messages_received__created_at", filter=Q(messages_received__sender=user))) qs = qs.annotate(last_received_date=Max("messages_sent__created_at", filter=Q(messages_sent__receiver=user))) Separately, they are very fast, but combined they are creating a very slow query. Is there some better way to annotate Max value from 2 fields or a way to annotate this … -
i want to get all categories filter as dropdown and want to show results
I am building an admin panel where i want to add filter system. For that I installed django-filters in system.py file and run the command to install it after that I did these below filter.py file: import django_filters from .models import * class ProductFilter(django_filters.FilterSet): class Meta: model = ProductModel fields = ['product_category'] views.py file: def createproduct(request): if request.method == 'POST': createProd = ProductForm(request.POST, request.FILES, request.GET) if createProd.is_valid(): # p_id = createProd.cleaned_data['product_id'] p_name = createProd.cleaned_data['product_name'] p_sku = createProd.cleaned_data['product_sku'] p_tags = createProd.cleaned_data['product_tags'] p_category = createProd.cleaned_data['product_category'] p_image = createProd.cleaned_data['product_image'] p_brand = createProd.cleaned_data['product_brand'] p_desc = createProd.cleaned_data['product_desc'] p_price = createProd.cleaned_data['product_price'] insert_products = ProductModel(product_name=p_name, product_sku=p_sku, product_tags=p_tags, product_category=p_category, product_image=p_image, product_brand=p_brand, product_desc=p_desc, product_price=p_price) insert_products.save() create = ProductForm() else: createProd = ProductForm() all_products = ProductModel.objects.all() product_filter = ProductFilter( request.GET, queryset=all_products) all_products = product_filter.qs return render(request, 'create.html', {'create': createProd, 'all_prods': all_products, 'product_filter': product_filter}) I wrote this code for filtering functionality : all_products = ProductModel.objects.all() product_filter = ProductFilter( request.GET, queryset=all_products) all_products = product_filter.qs return render(request, 'create.html', {'create': createProd, 'all_prods': all_products, 'product_filter': product_filter}) This is my models.py class ProductModel(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100) product_sku = models.CharField(max_length=200) product_tags = models.CharField(max_length=100) product_category = models.CharField( max_length=1000, default="Uncategorized") product_image = models.ImageField(upload_to='images/') product_brand = models.CharField(max_length=100) product_desc = models.TextField(max_length=255) product_price = models.CharField(max_length=100) So,after writing these codes …