Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unexpected keyword argument 'timeout' on Celery/Redis run on Django
I'm trying to set a environment on AWS (identical to another env I have that runs Celery perfectly) but I'm having this issue when I run celery -A core worker --loglevel=INFO [2022-08-03 12:59:06,633: CRITICAL/MainProcess] Unrecoverable error: TypeError("wrapped_func() got an unexpected keyword argument 'timeout'") I've already tried to upgrade and downgrade celery/redis/kumbu versions and nothing works. I oppened a python shell on this EC2 and tested the Redis connection and its working redis_client = redis.Redis(host=settings.REDIS_URL, port=6379) redis_client.set('key', 'value', nx=True, ex=5) I don't know what am I missing here.. My versions are celery==5.2.7 Django==3.1 django-celery-beat==2.3.0 kombu==5.2.4 redis==4.3.4 pip==22.1.2 setuptools==58.0.0 -
django - track data in formset which haven't been changed
I've created UpdateView with formset. The point is one of field in each formset should be filled after post. this field is calculated in function based on values from main form and some from formset but only when user clicks specific button in template. The user doesn't have to change anything in formset. It's not allowed. I've got code as folows: class DocUpdateView(UpdateView): model = Doc form_class = NewDocForm template_name = 'addatts.html' def get_success_url(self): return reverse('doc_detail', kwargs={'pk': self.object.doc_pk}) def get_context_data(self, **kwargs): context = super(DocUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = NewDocForm(self.request.POST, instance=self.object) context['formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['form'] = NewDocForm(instance=self.object) context['formset'] = MyModelFormSet(instance=self.object) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = MyModelFormSet(self.request.POST, instance=self.object) print(f'formset valid: {formset.is_valid()}') if form.is_valid() and formset.is_valid(): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save(commit=False) self.object.save() instances = formset.save(commit=False) print(instances) if 'sub_butt_1' in self.request.POST: for instance in instances: # here I wanted do logic with calculations instance.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form,formset=formset)) Howewer every time I print 'intances' there is only emply list. What am Idoing wrong? -
Redis SADD multiple workers
I am using Redis server version 7.0.0 with Django-Redis. I have multiple workers in production and plan to use Django Redis's get_redis_connection.sadd to add values to a Set() in Redis. When multiple workers do that in Production, will data be lost due to two workers executing simultaneously? I read that Redis's I/O is single-threaded before version 6.0; since I am using 7.0 (I/O multi-threaded), can concurrency issues/race conditions exist? -
Access Django ModelChoiceField form field value inside __init__
I would like to make the certain field in my formset read-only once the value has been chosen. Kind of like this: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields["my_field"].value is not None: self.fields["my_field"].disabled == True Except ModelChoiceField object doesn't have an arguement value and I am not even sure __init__ it is the right place to try access value of a formmset form's field. -
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