Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to Compare two tables Column (Table1 - Balance_sheet, Table2- Account_list) (Column-split,column-account) and get the similar data in django
class Balance_Sheet(models.Model): #name of the table # date = models.DateField() # Name of the column # transaction_type = models.CharField(max_length=100,blank=False) # num = models.IntegerField() name = models.CharField(max_length=100,blank=True) # description = models.CharField(max_length=100,blank=True) split = models.CharField(max_length=100,blank=False) # class Meta: # abstract : True class Account_List(models.Model): account = models.CharField(max_length=100,blank=True,null=True) type = models.CharField(max_length=100,blank=True, null=True) split =models.ForeignKey(Balance_Sheet,null=False, default=True,on_delete=models.CASCADE) def str(self): return 'Account : {0} Type : {1} '.format(self.account,self.type) def DisplayUVL(request): # Excel page changes Ven_list = Balance_Sheet.objects.filter(account_list__isnull=True).values_list('split', flat=True) print("SQL Query:",Ven_list.query) context = { 'items': Ven_list # 'header': 'Vendor List' } return render(request, 'services2.html', context) -
how to convert and save String to float field without rounding it in Django
I have a value of the string that is like 30.72044543304425 and am saving it to a FloatField as a float. example my_string = "30.72044543304425" object = something.objects.get(id=123) object.myFloatField = float(my_string ) object.save() but the result is 30.7204454330443 As you see the number has been rounded ..how to avoid this? -
Azure Batch OutputFiles upload from all compute nodes
I have a mpi-based task, where each thread writes files on 'working-directory' for each compute node on Azure-Batch. The task is configured to upload result (files) to my storage account. But only the files on the master node are uploaded to storage. I want to know, how can I make all the nodes to upload files to my storage account ? Is there any intermediate way to copy the files on to the files from the slave nodes to the master node and upload to storage account ? -
Can I use the current logged in user in models.py?
What I have: The default django User model with an attached Profile model that, amongst others, contains a ForeignKey to an Office model. So every user in my application is tied to a specific office. And in each office there are several Shifts. models.py: class Profile(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.RESTRICT) class Office(models.Model): id = models.AutoField(primary_key=True) short_name = models.CharField(max_length=3, default='FRA', null=True, unique=True) long_name = models.CharField(max_length=10, default='Frankfurt', null=True, unique=True) class Shift(models.Model): id = models.AutoField(primary_key=True) office = models.ForeignKey(Office, on_delete=models.RESTRICT) short_name = models.CharField(max_length=5, default="") long_name = models.CharField(max_length=20, default="") What I am trying to do: Now, in my CreateView I want to limit the available choices in the "shift" field to the ones attached to the office of the current logged in user. I thought about using the limit_choices_to option of ForeignKey, but I can't get my head around how to access the user information within a model? Something like class Shift(models.Model): id = models.AutoField(primary_key=True) office = models.ForeignKey(Office, on_delete=models.RESTRICT, limit_choices_to={'office': ???}) short_name = models.CharField(max_length=5, default="") long_name = models.CharField(max_length=20, default="") -
Error with Next.js getStaticPaths or getStaticProps in docker build process
I'm trying to launch my first devPortfolio site with Next.js and django. Basically, I have getStaticPaths or getStaticProps in my pages/__ files with such export const getStaticPaths = async () => { // prefetch the routes const res = await fetch("http://backend:8000/api/project/projects"); const project = await res.json(); const paths = projects.data.map((project) => ({ params: { slug: project.slug, }, })); return { paths, fallback: "blocking", }; }; and this works when I 'npm run build' in my local system but when I 'docker compose build' it throws an error #0 15.46 > Build error occurred #0 15.46 FetchError: request to http://backend:8000/api/blog/posts failed, reason: getaddrinfo EAI_AGAIN backend #0 15.46 at ClientRequest.<anonymous> (/frontend/node_modules/next/dist/compiled/node-fetch/index.js:1:64142) #0 15.46 at ClientRequest.emit (node:events:527:28) #0 15.46 at Socket.socketErrorListener (node:_http_client:454:9) #0 15.46 at Socket.emit (node:events:527:28) #0 15.46 at emitErrorNT (node:internal/streams/destroy:157:8) #0 15.46 at emitErrorCloseNT (node:internal/streams/destroy:122:3) #0 15.46 at processTicksAndRejections (node:internal/process/task_queues:83:21) { #0 15.46 type: 'system', #0 15.46 errno: 'EAI_AGAIN', #0 15.46 code: 'EAI_AGAIN' #0 15.46 } I'm assuming that during the build process, it has to fetch data from my django backend but I have no idea how, since running it as usual 'py manage.py runserver' would only be in my local desktop network, NOT accessible for docker. HOW can I … -
Django Rest Framework: Unit testing SyntaxError: invalid syntax [closed]
I want to implement a Unit test using APITestCase for the application API's. I've tried to do testing but I'm not sure whether I'm on the right track. It is giving me error: ERROR: myapp.tests (unittest.loader._FailedTest) ImportError: Failed to import test module: myapp.tests Traceback (most recent call last): File "/usr/lib/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name import(name) File "/home/naveen.p@ah.zymrinc.com/Desktop/drf/otb/myapp/tests.py", line 14 User.objects.create(email:"naveen@example.com",name:"Naveen",contact_number:"9090909098",gender:"0",address:"jaipur",state:"Rajasthan",city:"Jaipur",country:"India",pincode:"302016",dob:"07-07-1920",password:"123456",password2:"123456") ^ SyntaxError: invalid syntax Ran 1 test in 0.000s FAILED (errors=1) models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, … -
Django model inheritance - creating child objects based on parent instance
I am using Django 4.0 I have the following models: class Parent(models.Model): # fields ommitted for the sake of brevity pass class Child(Parent): child_only_field = models.CharField(max_length=64) code p = Parent.objects.create(**fields_dict) c1 = Child.objects.create(child_only_field='Hello 123', p) # Obviously won't work # c2 = ... Is there a way to create child objects from an instance of a parent (without manually "unpacking" the fields of the parent)? -
Confirmation button on save button like delete already has
I want to modify Django admin interface. There is delete button already has a confirmation page. But I want to add this confirmation to save or change buttons. Actually not exactly the same delete button. I want to change default admin buttons like this JS or I want to add JS to admin buttons. <input type="submit" onclick="linkSubmit('http://www.google.com')" value="Submit"> <p id="demo"></p> <script> function linkSubmit(link) { let text = "Press a button!\nEither OK or Cancel."; if (confirm(text) == true) { window.location.href = link; } else { } document.getElementById("demo").innerHTML = text; } </script> -
How replace webpack on Esbuild?
I have a project on React and Django. And we using Webpack. I read that Esbuild is really faster that Webpack. Which way do I need to go to make the right substitution? What clarifying questions should I ask to solve this kind of problem? Thanks! -
Cannot Render in Template from Django Database
i cannot render information in my template from django database. i want to get Slider Image With Text but it's not rendering on my template. Views.Py def slider(request): Slider_item = Slider.objects.get() context = { 'SS' : Slider_item } return render(request, 'base.html', context=context) base.html <p>{{ SS.Slider_Ttitle }} </p> models.py class Slider(models.Model): Slider_Image = models.ImageField(upload_to='static/images/sliders/', default='') Slider_Ttitle = models.CharField(max_length=50, default='Slider Text') def __str__(self): return self.Slider_Ttitle class Meta: managed = True verbose_name = 'სლაიდერი' verbose_name_plural = 'სლაიდერები' -
Recommend way and maximum byte size for requests in a data-intensive Django application
I am working on an application that handles datasets with varyiing sizes. For POST requests I do a check on the attached .csv-File for byte size like and if its over 10mb, I return a BAD_REQUEST response: MAX_FILESIZE_BYTES = 10485760 # 10mb csvFile = request.data["file"] if(csvFile.size > MAX_FILESIZE_BYTES): raise Exception("File size over "+str(MAX_FILESIZE_BYTES)) except Exception as e: return Response("Uploaded File bigger than maximum filesize", status=BAD_REQUEST, exception=True) Is this the recommend way of handling files too big? And is 10mb a reasonable size, or could my application handle much bigger sizes? I use rest_framework, atomic transactions with postgresql and I dont expect to have more much than 50 users at the same time. -
I want to remove case insensitivity in search functionality jquery
const query = $(this).val(); console.log(query); $('.wilipedia-item').each(function () { let title = $(this).find('.wilipedia-item__title h5').text().toLowerCase(); let description = $(this).find('.wilipedia-item__desc').text().toLowerCase(); if (title.includes(query) || description.includes(query)) { title = title.replace(query, '<span class="highlight">' + query + '</span>'); description = description.replace(query, '<span class="highlight">' + query + '</span>'); $(this).find('h5').html(title); $(this).find('.wilipedia-item__desc').html(description); } $(this).toggle($(this).find('h5, .wilipedia-item__desc').text().includes(query)) }); }); I have this code I applied search functionality on title and description but its like I have to convert it in small or capital letter then it works but I want to remove case insensitivity using index of but i am confused how to do that? Is there any one can help me -
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