Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django variable doesn't get passed to template
Basically, what happens here, the list user_data doesn't get passed to the template, I can't figure out why. Does anyone have any ideas please? When I use the search bar I just get the else condition from the template, and it never shows any variable. I also tried to create different variables to pass to the template, but none of them got passed for some reason... Thank you very much! This is in my views.py @login_required(login_url='login_user') def profiles(request): context = {} if request.method == "POST": data = request.POST.get('search_input') if len(data) > 0: username_result = NewUser.objects.filter(username__icontains=data).distinct() email_result = NewUser.objects.filter(email__icontains=data).distinct() user_data = [] for account in username_result: user_data.append((account, False)) context['usernames'] = user_data return render(request, "profiles/search_user.html", context) else: return render(request, "profiles/profiles.html") return render(request, "profiles/profiles.html") Then my template look like this: {% extends 'profiles/base.html' %} {% block title %}One For All{% endblock %} {% load static %} <!-- importing css file --> {% block style %}<link rel="stylesheet" type="text/css" href="{% static 'css/search_user.css' %}">{% endblock %} {% block content %} <!-- navigation bar --> <div class="navBar"> <!-- logo and logo spacers --> <div class="logo_spacer"></div> <div class="logo"></div> <!-- Sign Up Button --> <a class="homeBtn" href="{% url 'profiles' %}">Home</a> {% if is_self %} <a class="settingsBtn" href="{% url 'settings' … -
Design users with multiple accounts i.e (Instagram) in Django
Im Preplanning for project where users have multiple accounts each same as like instagram users with multiple accounts. I need to select any of the account after login token received from JWT. and when i calling api my views should display data based on the particular account. My question is, 1.How to store the choice of the user in backend after login? 2.If i store using sessions then is that data will be private to the particular user or if i login with other user on the same tab, same session data from previous user is still visible to this user also right? Please help on this. Thanks in advance. -
How to get a proper and query with django where not exists statement
So I have this query which I would like to use as a filter: select * from api_document ad where not exists ( select 1 from api_documentactionuser ad2 where ad2.user_id=4 and ad2.action_id=3 and ad.id = ad2.document_id limit 1 ) What I've tried with django is: q = queryset.exclude( Q(documentactionuser__action__id=3) & Q(documentactionuser__user=current_user), ) while queryset is a queryset on the api_document table. When I print the generated query however, django keeps separating the two conditions into two queries instead of simply using and, which in turn gives me the wrong data back: select * FROM "api_document" WHERE NOT ( EXISTS(SELECT 1 AS "a" FROM "api_documentactionuser" U1 WHERE (U1."action_id" = 3 AND U1."document_id" = ("api_document"."id")) LIMIT 1) AND EXISTS(SELECT 1 AS "a" FROM "api_documentactionuser" U1 WHERE (U1."user_id" = 1 AND U1."document_id" = ("api_document"."id")) LIMIT 1) ) I've tried chaining exclude().exclude(), filter(~@()).filter(~@()) and the above variant and it all returns nearly the same query, with the same data output -
How to fix out of sync Django migration with unique constraint
I had a model that looked something like this: class FooBar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) bar = models.ForeignKey(Bar, on_delete=models.CASCADE) <some other fields> class Meta: constraints = [ models.UniqueConstraint(fields=['foo', 'bar'], name='foobar_candidate_key') ] I deleted the fields foo and bar and made the migrations and ran the migrations. I had not deleted the Meta class when I did this. I noticed that I forgot to remove the Meta class and removed it. Then I made the migrations again and tried to migrate. I got an error like: django.db.utils.OperationalError: (1091, "Can't DROP 'foobar_candidate_key'; check that column/key exists") How can I fix? I have considered using --fake but I'm worried that the constraint is still in the database constraints and I need it removed? -
Can you help me install django?
I tried installing django via command prompt. (pip install django) It was successfully installed and when I try using the command django-admin --version to check if it's there I get this ('django' is not recognized as an internal or external command, operable program or batch file.) Can anyone help on how I can install it the proper way and set it up in my computer for use? -
when im was installing django this keep happening
This is normal text **C:\Program Files\Python310\myproject>python manage.py migrate Traceback (most recent call last): File "C:\Program Files\Python310\myproject\manage.py", line 21, in main() File "C:\Program Files\Python310\myproject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python310\lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Program Files\Python310\lib\site-packages\django\core\management_init_.py", line 420, in execute django.setup() File "C:\Program Files\Python310\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python310\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Program Files\Python310\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Program Files\Python310\lib\site-packages\django\contrib\auth\models.py", line 98, in class Group(models.Model): File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 192, in new new_class.add_to_class(obj_name, obj) File "C:\Program Files\Python310\lib\site-packages\django\db\models\base.py", line 369, in add_to_class value.contribute_to_class(cls, name) File "C:\Program Files\Python310\lib\site-packages\django\db\models\fields\related.py", line 1920, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model( File "C:\Program Files\Python310\lib\site-packages\django\db\models\fields\related.py", line 1286, in create_many_to_many_intermediary_model "verbose_name": _("%(from)s-%(to)s relationship") File "C:\Program Files\Python310\lib\site-packages\django\utils\functional.py", line 191, in mod return str(self) % rhs File "C:\Program Files\Python310\lib\site-packages\django\utils\functional.py", line 155, in __text_cast return func(*self.__args, self._kw) File "C:\Program Files\Python310\lib\site-packages\django\utils\translation_init.py", line 95, in gettext return _trans.gettext(message) File "C:\Program Files\Python310\lib\site-packages\django\utils\translation\trans_real.py", line 374, in gettext … -
mock assert_called_with treat argument as unordered list
I have some mocked function and I try to test that the arguments I pass there are correct. One of the arguments is a list generated based on DB queryset, lets say [{"id": 1}, {"id": 13}] The function doesn't care about the order of dicts in a list, so it works the same with a reversed (shuffled) list. I also have a test to check arguments are passed correctly: function_mock.assert_called_once_with( argument1='some_string', argument2='another_string', argument3={'some_dict_key': False}, ... my_list=[{"id": 1}, {"id": 13}], ) The problem is that on different environments queryset produces records in different order, resulting in [{"id": 1}, {"id": 13}] on some environments and [{"id": 13}, {"id": 1}](different order) on other. This results in tests pass on some environments and fail on other. Is there a way to inform mock that this argument should be treated as an unordered list? Something similar to my_list=mock.any_order([{...}, {...}]) P.S. I know about call_args_list so I can check arguments one by one, and apply set when necessary, but I'd like to avoid this solution unless there is better one. -
Google Translate API logging permission denied
I am using the Google Translate API v2 and I am able to get the translations but I also get these errors on the side which I am not able to resolve. Failed to submit 1 logs. Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 67, in error_remapped_callable return callable_(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 946, in __call__ return _end_unary_response_blocking(state, call, False, None) File "/usr/local/lib/python3.7/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.PERMISSION_DENIED details = "Permission 'logging.logEntries.create' denied on resource (or it may not exist)." debug_error_string = "{"created":"@1659523475.735415900","description":"Error received from peer ipv4:142.250.194.234:443","file":"src/core/lib/surface/call.cc","file_line":966,"grpc_message":"Permission 'logging.logEntries.create' denied on resource (or it may not exist).","grpc_status":7}" > The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/google/cloud/logging_v2/handlers/transports/background_thread.py", line 114, in _safely_commit_batch batch.commit() File "/usr/local/lib/python3.7/site-packages/google/cloud/logging_v2/logger.py", line 385, in commit client.logging_api.write_entries(entries, **kwargs) File "/usr/local/lib/python3.7/site-packages/google/cloud/logging_v2/_gapic.py", line 149, in write_entries self._gapic_api.write_log_entries(request=request) File "/usr/local/lib/python3.7/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py", line 615, in write_log_entries metadata=metadata, File "/usr/local/lib/python3.7/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__ return wrapped_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/google/api_core/retry.py", line 291, in retry_wrapped_func on_error=on_error, File "/usr/local/lib/python3.7/site-packages/google/api_core/retry.py", line 189, in retry_target return target() File "/usr/local/lib/python3.7/site-packages/google/api_core/grpc_helpers.py", line 69, in error_remapped_callable six.raise_from(exceptions.from_grpc_error(exc), exc) File "<string>", line 3, in raise_from google.api_core.exceptions.PermissionDenied: 403 Permission 'logging.logEntries.create' denied on resource (or … -
how to create custom periodic task in celery in django
I want to create a shedular while a API was getting hit after that i have to create the after that i have to stop the shedular in another api was get hitting API1 --> trigger the celery cron for 3 min periodic task API2 --> stop the celery periodic task how -
How to solve the pip install for virtualenwrapper
C:\Users\LENOVO>pip install virtualenwrapper-win Defaulting to user installation because normal site-packages is not writeable ERROR: Could not find a version that satisfies the requirement virtualenwrapper-win (from versions: none) ERROR: No matching distribution found for virtualenwrapper-win How to solve this issue -
Channels-redis wont install using pip
im trying to install channels-redis using pip install -U pip channels-redis but it cause the following error: Error: Using legacy 'setup.py install' for hiredis, since package 'wheel' is not installed. Installing collected packages: hiredis, async-timeout, aioredis, channels-redis Running setup.py install for hiredis ... error error: subprocess-exited-with-error × Running setup.py install for hiredis did not run successfully. │ exit code: 1 ╰─> [19 lines of output] C:\Users\APA\AppData\Local\Temp\pip-install-lvqc1hfx\hiredis_65bd53516444439e81ff8540ee5b60d1\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, imp, os, glob, io C:\Users\APA\Desktop\KM-APP\KM\Repo\env\lib\site-packages\setuptools\dist.py:771: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running install C:\Users\APA\Desktop\KM-APP\KM\Repo\env\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( running build running build_py creating build creating build\lib.win-amd64-cpython-310 creating build\lib.win-amd64-cpython-310\hiredis copying hiredis\version.py -> build\lib.win-amd64-cpython-310\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-cpython-310\hiredis copying hiredis\hiredis.pyi -> build\lib.win-amd64-cpython-310\hiredis copying hiredis\py.typed -> build\lib.win-amd64-cpython-310\hiredis running build_ext building 'hiredis.hiredis' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. … -
How can to remove auto generate Enum field schema in drf-spectacular
How to remove auto generate Enum field schema in drf-spectacular here my SPECTACULAR_SETTINGS: SPECTACULAR_SETTINGS = { 'TITLE': 'Python Base Code', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, 'SCHEMA_PATH_PREFIX_TRIM': True, 'SERVERS': [{'url': env('SWAGGER_SERVER')},], 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], 'COMPONENT_SPLIT_PATCH': False, } -
How to pass dynamic variable in anchor tag with dynamic URL using Django JavaScript and Html
I am working on Cuckoo Sandbox. I am trying to pass variable in anchor tag with dynamic URL but it doesn't work and by changing url path the sidebar suddenly disappears and didn't work. I am working on different files and variable is in JS file. Also, I want to call the variable in anchor tag to work properly and sidebar shouldn't disappear. JS FILE CODE: var id = $(this).data('taskId'); HTML FILE CODE: <li> <a href="{% url 'analysis/redirect_default' 45 %}"> <div class="parent-icon"><i class='bx bx-home'></i> </div> <div class="menu-title">Summary</div> </a> </li> I want to pass variable in replace of '45' and variable value is dynamic -
Saving Javascript changes using django
I am rendering element using javascript. How can I save itvto my website using django. I am a beginner in django can someone guide how to do this -
How can i convert following query in django rest framework
SELECT id,ewbno,ewbdate,gengstin,(select code from mt_business_partner where gstin=t00.gengstin limit 1) code, (select name from mt_business_partner where gstin=t00.gengstin limit 1) name from mt_ewb_master t00 where ewbno like ? order by id limit 50") i want to convert this and write it in django ORM -
Unsupported lookup 'category' for CharField or join on the field not permitted
models.py from django.db import models from django.urls import reverse class Category(models.Model): category_id = models.AutoField category_name = models.CharField(max_length=50, default="") desc = models.CharField(max_length=1000) slug = models.SlugField(max_length=20) image = models.ImageField(upload_to='onlinePizza/images', default="") def get_url(self): return reverse('category', args=[self.slug]) def __str__(self): return self.category_name class Product(models.Model): product_id = models.AutoField product= models.CharField(max_length=50) category = models.ForeignKey(Category, default='', null=True, on_delete=models.CASCADE) desc = models.CharField(max_length=1000) image = models.ImageField(upload_to='onlinePizza/image', default="") def __str__(self): return self.product This is my views.py file. I show error at bestseller = Product.objects.filter(product__category__icontains='BestSeller') views.py from django.shortcuts import render from . models import Category, Product, Deal from math import ceil def index(request): bestseller = Product.objects.filter(product__category__icontains='BestSeller') context = {'bestseller':bestseller} return render(request, 'onlinePizza/index.html', context) I want to Bestseller category product at index.html I use Django 4 and pyhton 3.9 -
Django queue reincarnated monitor Process-1:228 after sudden death
I've installed and configured Django-Q 1.0.2 (on Django 1.11.10 with Redis 1.0.1 and Python 3.6.9). This is my Cluster configuration: Q_CLUSTER = { 'bulk': 5, 'recycle': 500, 'compress': True, 'save_limit': 500, 'queue_limit': 500, 'label': 'Django Q', 'attempt_count': 1 } -
django makemessages can't translate all words
makemessages can't detect all translation words... I tried all but it didn't work. My command django-admin makemessages --all --ignore=venv # and python manage.py makemessages --all --ignore=venv My template {% load i18n %} {% trans 'тестовый какой-то текст' %} {% trans 'Республика Узбекистан, г.Ташкент, Шайхонтохурский район, улица Лайлитогон 1, 141300, Самаркандская область, Пайарикский район, улица Самарканд 52.' %} makemessages detected first text but not second... Pls help -
Properly rename column name using display decorator in Django admin.py panel
I'm trying to rename the IS STAFF to STAFF STATUS here: I'm just wondering if it's possible to rename it from admin.py & NOT use the verbose_name inside the model. I wrote this code in admin.py: @admin.register(User) class CustomUserAdmin(DefaultUserAdmin): list_display = [ 'username', 'RENAMED_EMAIL', 'first_name', 'last_name', 'RENAMED_STAFF', 'is_active', ] @admin.display(description="EMAIL ADDRESS", ordering='-email') def RENAMED_EMAIL(self, obj): return obj.email @admin.display( description="STAFF STATUS", boolean=True, ordering='-is_staff', ) def RENAMED_STAFF(self, obj): return obj.is_staff list_editable = ['is_staff', 'is_active'] The EMAIL ADDRESS was renamed successfully but as I used is_staff in list_editable, I get this error: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E122) The value of 'list_editable[0]' refers to 'is_staff', which is not contained in 'list_display'. Tried to use RENAMED_STAFF inside list_editable too, it results in another error: ERRORS: <class 'accounts.admin.CustomUserAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'RENAMED_STAFF', which is not a field of 'accounts.User'. What is the proper way to customize those column names? -
Django + uvicorn poor performance
I'm testing Django asgi performance using two very simple views. I'm running gunicorn and uvicorn in such a manner: gunicorn core.wsgi --workers=1 --threads=1 --access-logfile=- core.wsgi:application uvicorn --workers 1 core.asgi:application The views are as follows: def simple_sync_view(request): usernames = "Hello World" return JsonResponse({'message': usernames}) async def simple_async_view(request): usernames = "Hello World" return JsonResponse({'message': usernames}) Project has no middlewares enabled. When testing using : wrk -t10 -c100 -d10s http://127.0.0.1:8000/test/sync/ synchronous server is always several times faster: 10 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 37.42ms 7.87ms 158.35ms 98.88% Req/Sec 271.54 38.28 303.00 79.60% 26885 requests in 10.01s, 4.87MB read Requests/sec: 2685.95 Transfer/sec: 498.40KB comparing to uvicorn: 10 threads and 100 connections Thread Stats Avg Stdev Max +/- Stdev Latency 115.38ms 37.55ms 245.49ms 53.91% Req/Sec 88.65 41.14 200.00 74.63% 8638 requests in 10.02s, 1.40MB read Requests/sec: 862.49 Transfer/sec: 143.19KB regardless of type of view, sync or async. So I wonder, is the Django in asgi mode so slow or what ? -
How hard can it be? Django ImageField
After struggling for some time to find answer(not a single answer funcioned for me) i decided to ask a question- What are correct steps to Display Image uploaded via Django Admin, to my custom template (html page) in DJANGO 4? -
How to get proper json data from irregular json in phpmyadmin (Mysql)?
`a:1:{i:0;a:6:{s:19:"purchase_product_id";s:2:"44";s:16:"purchase_product";s:27:"Sumo Xtra Emulsion - Base 4";s:4:"type";s:17:"Exterior Emulsion";s:13:"product_range";s:1:"2";s:13:"price_per_qty";s:0:"";s:3:"qty";s:3:"200";}}` The above is the data stored in MySQL db. Here I want to extract this data into proper JSON and use this Django. -
Change URL of browsable API of django rest framework from 127.0.0.1:8000 to 127.0.0.1:8000/api
I followed the simple quickstart tutorial in the official documentation of django rest framework. https://www.django-rest-framework.org/tutorial/quickstart/ The tutorial works fine. The URL of the browsable API is at 127.0.0.1:8000. How do I change it to 127.0.0.1:8000/api? The code for urls.py; from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] I am using django v4, python v3.9 -
How to fill the remaining database fields at the server in django
I am new to django and I am creating API endpoints using django rest framework. I have created a post request so a user will fill the request body which is in json and that json will be added to the database table however the twist is that the user has to fill only a few fields and the remaining fields will be added at the server end. For eg. lets say that the database table has fields room_number, check_in, check_out, date, capacity. The user will only fill fields check_in, check_out, date and the remaining fields will be filled at the server end. So can someone please tell me how can I do it? -
iterate over forms in Django formset
I have a formset where I am trying to iterate over related_component so it shows dynamically all components that are related to this product. For now, I managed to count the number of components but it selects me in all forms always the first choice from the database. What I want is to show the components that are related only to this product and show all of them, not only the first component from the list so the user doesn't need to select it manually. Do I need to overwrite init method in the form or I can do it somehow in ProductDetailView? I'd appreciate any help. Here is what I have now: This is something I want to see: forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(required = False) number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units', 'total_price') CalculatorFormsetProduct = formset_factory(CalculatorFormProduct, extra=0) views.py class ProductDetailView(FormMixin, DetailView): template_name = 'hubble/ProductDetailView.html' model = Product form_class = CalculatorFormsetProduct def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) get_components = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) formset = CalculatorFormsetProduct(initial=[{ 'author': self.request.user.email, 'related_product': self.object, 'related_component': self.object, # what …