Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query timestamp seems to behave differently
I would like to query som data from a postgres database where we store some values. However it seems that when I do this in Django with a python script that is called from views.py the data is shifted one hour. Example: Query from script file: sensorData = SensorDataAvgFirstTwoMonths.objects.filter(timestamp__gte='2019-11-06 07:50:00', timestamp__lte='2019-11-06 08:00:00', machine_id=4, type_id=25).order_by('timestamp'); print(sensorData) for d in sensorData: print(d.timestamp) print(d.value) This result in the following print: 1 Now, if I query data directly from the terminal then I have to shift one hour to get the same result (except for the fact that the quires are slightly different). 2 The time in the database is in UTC time. I would expect that I do not need to shift time one hour in the Django qury to get the same result. But I guess that the query in Django take some timezone into account but how can I get the same result when setting the date and time exactly the same in both cases? -
Django TestCase: can't see record updated in test db
I'm testing a function in my project. The function modifies some records in my test db. I'm interested to see if a specific record was updated. I call my method inside my test_function and after that looking for the record. It seems the record wasn't updated, but the function (with some logs) tells me it was! I created my TestCase class using both TestCase and TransactionTestCase, but none of them worked. I'm usign Django 2.2 class HostTestCase(TransactionTestCase): def setUp(self): task = Task.objects.create(name='do_backup', description="") for i in range(1, 17): if i in [4, 7, 9, 11, 12, 14, 15]: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server{}:4010".format(i) ) if i in [11, 14, 15]: host.last_seen_at = timezone.now() host.save() if i in [9, 12, 15]: task_assigned = Host_Task.objects.create(host=host, task=task, status="IDLE") elif i in [4, 7, 11, 14]: task_assigned = Host_Task.objects.create(host=host, task=task, status="WORKING_CREATION") else: if i != 16: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server{}:4010".format(i), get_backup=False ) if i in [8, 10, 13]: host.last_seen_at = timezone.now() host.save() if i in [3, 6, 10, 13]: task_assigned = Host_Task.objects.create(host=host, task=task, status="WORKING_CREATION") else: host = Host.objects.create( name="test_sbb{}".format(i), mac_address="asgsb{}".format(i), remote_address="mock-server:4010" ) host.last_seen_at = timezone.now() host.save() influx = InfluxDB(host) # create new db influx.create_database() write_mock_data(influx, i) def tearDown(self): for i in … -
ModuleNotFoundError: No module named 'Pillow'
i installed pillow from cmd : pip install pillow and after that i went to import it : from PIL import Image but i found an error : ModuleNotFoundError: No module named 'Pillow' please help !! -
Append FormActions Div by default to custom FormHelper
To keep my ModelForms DRY I have created a custom ModelForm with a FormHelper so I can append a Div with a Submit and a Cancel button to the layout. It also offers the possibility to add a custom layout. This works perfectly fine when I don't specify a custom layout, but when I do, every time I refresh the page it appends the buttons Div (this doesn't happen when there's no custom layout) This is the custom ModelForm: class ModelFormWithHelper(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) kwargs = self.get_helper_kwargs() helper_class = FormHelper(self) if 'custom_layout' in kwargs: self.helper.layout = kwargs['custom_layout'] self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-12' self.helper.field_class = 'col-md-12' self.helper.layout.append( Div( HTML('<br>'), FormActions( Submit('submit', 'Save'), HTML('<a class="btn btn-secondary" href="{{ request.META.HTTP_REFERRER }}">Cancel</a>') ), css_class='row justify-content-center', ), ) def get_helper_kwargs(self): kwargs = {} for attr, value in self.Meta.__dict__.items(): if attr.startswith('helper_'): new_attr = attr.split('_', 1)[1] kwargs[new_attr] = value return kwargs And this is the ModelForm: class CargoForm(ModelFormWithHelper): class Meta: model = Cargo exclude = [] helper_custom_layout = Layout( Div( 'name', 'order', css_class='col-6 offset-3', ), ) This is the form with no custom_layout after I refresh the page 3 times: And this is the form with a custom_layout after I refresh the page 3 … -
How to loop in template over serializer used as form
I need a CRUD-table and don't want to write out the field names (too many). I want use the serializer to make the forms in the first row and the already entered data in the rows below. Displaying the data works fine, even with choices and FK. The problem is that i cannot loop over the form-fields. In "template1.html" I checked "render_form" and the serializer. Ok, so far. PROBLEM: In "template2.hmtl" I try to loop and position each form (rendered REST serializer) in a column and get errors. How to loop correctly? ...rest of table is omitted... <tr> <form method="POST"> {% csrf_token %} <th> {% render_form serializer template_pack='rest_framework/inline'%} <input type="submit" value="Save"> </th> </form> </tr> ...rest of table is omitted... <tr> <form method="POST"> {% csrf_token %} {% for s in serializer %} <th> {% render_form s template_pack='rest_framework/inline'%} </th> {% endfor %} <th> <input type="submit" value="Save"> </th> </form> </tr> -
How to get the second to last most recent timestamped record in Django/Python?
I have a form from a model that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in the "time_in" DateTimeField and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp (time_out) then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. NOTE I reduced the amount of code in form_valid, hence the leave area part is not there. It was just a lot of filtering based on other fields and it didn't seem too relevant. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: … -
How to create a formset from form-instance in Python Django
I am trying to get a Django - Formset out of an instance of a form class. In my form class i add some fields in the init method because the form has to offer some flexibility. Therefore i can't pass the class as parameter to the formset_factory function. --forms.py class ConfigForm(forms.Form): def __init__(self, fields, fields_choices, *args, **kwargs): super(ConfigForm, self).__init__(*args, **kwargs) for field in fields: # instanciate Field from field data exec( f'self.fields["{field.name}"] =' f'forms.{field.field_type.field_type}(' f'required = {field.required},' f'disabled = {field.disabled},' f'label = "{field.label}",' f'initial = "{field.value}",' f'widget = {field.widget},' f'help_text = "{field.description}"' f')' ) # if field is a ChoiceField add choices to the field instance if 'ChoiceField' in field.field_type.field_type: self.fields[field.name].choices = [fields_choices[field.name]] --views.py ... form = forms.ConfigForm(active_fields, field_choices) formset = formset_factory(form, extra=1) ... But if i try to call formset_factory with an instance of ConfigForm, the following error occurs: Internal Server Error: /machines/testconfig/mw0-sap-001/ Traceback (most recent call last): File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\maximilianwiederer\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) … -
Column 'post_id' cannot be null
Column 'post_id' cannot be null I don't know why I can't bring post_id. If you try to add a comment, you might not be able to bring post_id. I can't solve it. Please help me. models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) serializers.py class CommentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) post = PostSerializer(read_only=True) class Meta: model = Comment fields = ( 'user', 'post', 'id', 'content', ) read_only_fields = ('created_at',) views.py # api/views.py class CommentView(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) -
Altering the username of the User model to use PhoneNumberField instead of CharField causes errors
I work on a project started from the cookiecutter-django, and I altered the username of the User model to use PhoneNumberField from django-phonenumber-field package instead of the ordinary models.CharField, and I got this error when I tried to issue manage.py makemigrations: Traceback (most recent call last): File "./manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/admin.py", line 10, in <module> from community_backend.users.forms import UserChangeForm, UserCreationForm File "/home/ahsh/Projects/xpay_stuff/communites_dj_backend/community_backend/users/forms.py", line 8, in <module> class UserChangeForm(forms.UserChangeForm): File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 256, in __new__ apply_limit_choices_to=False, File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/django/forms/models.py", line 172, in fields_for_model formfield = f.formfield(**kwargs) File "/home/ahsh/.local/share/virtualenvs/communities_dj_backend/lib/python3.7/site-packages/phonenumber_field/modelfields.py", line 106, in formfield return … -
List from Django to table in JavaScript
I have a list in Django and I would like transfer it to JavaScript table My template print latest_question_list in loop properly: {% if latest_question_list %} <ul> {% for row in latest_question_list %} <li>{{ row.mounth }}, {{ row.number1 }}, {{ row.number2 }}, {{ row.number3 }}, {{ row.number4 }}</li> {% endfor %} </ul> {% else %} <p>These list is empty.</p> {% endif %} But I would see it in JavaScript (in the same file) in this form: <script> var data_table = [600, 194, 345, 512, 200, 320, 328, 498, 267, 349, 287, 276]; [...] </script> -
How to use new "autocomplete_fields" option in Django <2.0 with overrided form?
I have form, which overrides the standard admin form and i want to use "autocomplete_fields" for brigadier field, which if ForeignKey -
ASGI Framework Lifespan error, continuing without Lifespan support
After creating a project with django, and auditing the code via chrome audit, it shows Does not use HTTP/2 for all of its resources 2 requests not served via HTTP/2 to fix this error I followed this tutorial https://medium.com/python-pandemonium/how-to-serve-http-2-using-python-5e5bbd1e7ff1 and when using the code specified for quart import ssl from quart import make_response, Quart, render_template, url_for app = Quart(__name__) @app.route('/') async def index(): result = await render_template('index.html') response = await make_response(result) response.push_promises.update([ url_for('static', filename='css/bootstrap.min.css'), url_for('static', filename='js/bootstrap.min.js'), url_for('static', filename='js/jquery.min.js'), ]) return response if __name__ == '__main__': ssl_context = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH, ) ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 ssl_context.set_ciphers('ECDHE+AESGCM') ssl_context.load_cert_chain( certfile='cert.pem', keyfile='key.pem', ) ssl_context.set_alpn_protocols(['h2', 'http/1.1']) app.run(host='localhost', port=5000, ssl=ssl_context) I get /home/avin/Documents/projects/portfolio/portfolio_env/lib/python3.6/site-packages/quart/app.py:1320: UserWarning: Additional arguments, ssl, are not yet supported "Additional arguments, {}, are not yet supported".format(','.join(kwargs.keys())), Running on https://localhost:5000 (CTRL + C to quit) [2019-11-06 18:30:18,586] ASGI Framework Lifespan error, continuing without Lifespan support and also I cant load the webpage via https://localhost:5000 -
Which frame work is easier django or flask
Which python web development framework should I go for (django or flask) considering i am a beginner level python developer and also new to web development -
api call from one server to another django
I'm pretty new with Django framework, I have two webservers that run in the same docker-compose the first on port 8008 and the second on 8000. I'm trying to make API's call from one to another. (they both runs Django). for some reason, after he pass the first call and try to make the second one to the second server. he trying to find the path on the first one. urls.py urlpatterns = [ . . . url(r'^badges/issuers/$', views.create_issuer, name='create issuer'), ] views.py def create_issuer(request): r = requests.get('http://127.0.0.1:8000/v2/users/romOowjnTkuoBXcb8dn_bQ', headers={"Authorization": "Token " + badgr_token}) #r = requests.get('http://api.ipstack.com/132.72.238.3?access_key=c3dcdadd83efb69cd9970cb811b2ad3f&format=1') return HttpResponse(r.content) I'm getting 404 : Using the URLconf defined in Lassi.urls, Django tried these URL patterns, in this order: . . . "The current URL, v2/users/romOowjnTkuoBXcb8dn_bQ, didn't match any of these." the logs from docker terminal : ins_1 | [06/Nov/2019 12:26:27] "GET /v2/users/romOowjnTkuoBXcb8dn_bQ HTTP/1.1" 404 5443 ins_1 | [06/Nov/2019 12:26:27] "GET /badges/issuers/ HTTP/1.1" 200 5443 and nothing from the second's log. I don't know why but he tries to get the path from the first server instead of doing regular get requests to second. I tried to make the call to the second with Postman and it's worked. Tnx!! -
Geeting value after submit and redirecting to certain page
Hi I am new in Django but know some stuff and still need your help. I want when a user submit a button after putting info in search area to redirect to another page and accept data for future use. What i did so far: in models.py from django.db import models from django.contrib import auth class Child(models.Model): name = models.CharField(max_length=150, blank=True) in forms.py from django import forms from .models import Child class ChildlForm(forms.ModelForm): class Meta: model = Child fields = ('name',) in views.py def garden(request): return render(request,'garden.html') def names(request): form = ChildForm() if request.method == "POST": form = ChildForm(request.POST) if form.is_valid(): form.save(commit=True) return garden(request) else: return 'test.html' return render(request,'garden.html',{'form':form}) 'test.html' is where the form is required to be filled by user. I want after the inform submitted the data is saved and then redirected to garden.html file. the test.html file <form action="." class="ticker_area"method="POST"> {{ form }} {% csrf_token %} <input class="form-control mr-sm-2" type="text"> <button class="ticker_button" type="submit">OK</button> </form> the form is search ready template posted by bootstrap. Could you please help to link successfully the files and get the data (name) to further use in garden.html ? So far when i put name i search area and submit the page goes … -
How to return data from django to nodeJs server?
I'm trying to send data from nodeJs server to django server for some processing, then return some json data. But when I make a request using this line of code, http.get("http://127.0.0.1:8000/test/", (message) => { console.log(message) }) then printing the message, a lot of data printed! How I can retrieve my data? this is the django code! from django.http import HttpResponse from django.core import serializers import json def prints(request): some_data_to_dump = { 'some_var_1': 'foo', 'some_var_2': 'bar', } data = json.dumps(some_data_to_dump) print("foidjfdi") return HttpResponse(data, content_type="application/json") -
How to use request_id while logging in asynchronous functions?
In asynchronous functions, every logger statement is getting their own request_id. import logging log = logging.getLogger('test_logger') def sync_fun(): log.info("test 1") log.info("test 2") log.info("test 3") @after_response.enable def async_fun(): log.info("test 1") log.info("test 2") log.info("test 3") output of sync_fun: [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 1 [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 2 [06/Nov/2019 10:42:00.234] [None] [130C6C47F1E24164AAC0440C719630] [INFO] Test 3 130C6C47F1E24164AAC0440C719630 is a request_id and its common for all logger statements. output of async_fun: [06/Nov/2019 10:42:00.234] [None] [AB352B8F2DF9459ABDD2FBF51EB05F] [INFO] Test 1 [06/Nov/2019 10:42:00.234] [None] [V9E9B6DF5F9C442195EA7C1379FBFA] [INFO] Test 2 [06/Nov/2019 10:42:00.234] [None] [DCA311A92724443C9AD7E951288917] [INFO] Test 3 async_fun is an asynchronous function and request ids are different for all logger statements. How do i get the same request_id for each logger statements in asynchronous function. -
django - upload page should be accessable after form submission only once. Directly entering the upload url should not work
i can upload a file after the form is submitted. The upload url should not be accesssable otherwise After the user logins, the upload url is ascessed directly. How to restrict this. This will create multiple entries of file upload for the same form views.py Data1 = request.POST["Data1"] Data2 = request.POST["Data2"] Data3 = request.POST["Data3"] return redirect(uploaddata)``` ```def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user #post.tar_gif = request.FILES['tar_gif'] post.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html')``` -
Location for app-wide utils file in a Django project
Given the nightmare of relative imports, where should I put a simple utils.py file in a Django project that has multiple apps (accessible within the models.py, admin.py, views.py all files of all app directories)? It seems like there still isn't a good answer for this in 2019, even though Django is by far the most popular framework of the language. Considering Python 2 will be sunset in January of 2020, please also provide an answer for Python 3. -
Problem with save OneToOne relation when user is register
I want to save User and also user details in additional date when user is register by rest api. When User is saved I want to save this additionality data to userDetails tabel with User ForeingKey. This should be by RegisterSerializer. Im using django-rest-auth. I have models: class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) is_partner = BooleanField(_('User is partner'), default=False) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) class UserDetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=100, blank=True) zip_code = models.CharField(max_length=20, blank=True) country = models.CharField(max_length=30, blank=True) def __str__(self): return self.user.username and serializers class UserDetailsSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = UserDetails fields = "__all__" class UserRegisterSerializer(RegisterSerializer): is_partner = serializers.BooleanField(default=False) address = serializers.CharField(max_length=200) city = serializers.CharField(max_length=100) zip_code = serializers.CharField(max_length=20) country = serializers.CharField(max_length=30) def get_cleaned_data(self): super(UserRegisterSerializer, self).get_cleaned_data() return { 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'name': self.validated_data.get('name', ''), 'address': self.validated_data.get('address', ''), 'city': self.validated_data.get('city', ''), 'zip_code': self.validated_data.get('zip_code', ''), 'country': self.validated_data.get('country', ''), } -
How to combine ListView and UpdateView
In my web application, I have a template with ListView that shows list of table records, that works fine. Now I want to allow user to update fields for each row of the table. One "easy" solution is to create an update page using UpdateView and put a link to it in each row. User can then click update, open update page ... But I am wondering if there is a way to update fields in the same table, without opening a new page. Hope my question is clear. thanks for your help -
celery start multiple workers and one beat as daemon crash
i try to start multiple workers with celery multi and celery beat simultaneously. I start the workers as daemon with this command: celery multi start 2 -A djangoproj -Q:1 longtaskqueue -Q:2 shorttaskqueue -c:1 1 -c:2 1 Now if i start the beat as daemon with: celery multi start -A djangoproj workerbeat1 --beat the workers crash with this error in the log file: [2019-11-06 13:00:51,641: WARNING/MainProcess] /usr/local/lib/python3.7/dist-packages/celery/fixups/django.py:202: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2019-11-06 13:01:16,722: ERROR/MainProcess] Control command error: OperationalError("\nCannot route message for exchange 'reply.celery.pidbox': Table empty or key no longer exists.\nProbably the key ('_kombu.binding.reply.celery.pidbox') has been removed from the Redis database.\n") Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/kombu/connection.py", line 439, in _reraise_as_library_errors yield File "/usr/local/lib/python3.7/dist-packages/kombu/connection.py", line 518, in _ensured return fun(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/kombu/messaging.py", line 203, in _publish mandatory=mandatory, immediate=immediate, File "/usr/local/lib/python3.7/dist-packages/kombu/transport/virtual/base.py", line 605, in basic_publish message, exchange, routing_key, **kwargs File "/usr/local/lib/python3.7/dist-packages/kombu/transport/virtual/exchange.py", line 70, in deliver for queue in _lookup(exchange, routing_key): File "/usr/local/lib/python3.7/dist-packages/kombu/transport/redis.py", line 877, in _lookup exchange, redis_key)) kombu.exceptions.InconsistencyError: Cannot route message for exchange 'reply.celery.pidbox': Table empty or key no longer exists. Probably the key ('_kombu.binding.reply.celery.pidbox') has been removed from the … -
Original exception text was: 'int' object has no attribute 'product'
When I am going to pass list objects in url I am getting this error Got AttributeError when attempting to get a value for field `product` on serializer `ProductForParameterSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'product'. ` class ProductParameter(models.Model): product_attribute = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_parameters') parameter = models.CharField(max_length=100, default='-') and serializers.py looks like this class ProductForParameterSerializer(serializers.ModelSerializer): name = serializers.CharField(source='product.name', max_length=255, read_only=True) product_desc = serializers.CharField(source='product.description', max_length=255, read_only=True) image = serializers.ImageField(source='product.image', read_only=True) price = serializers.DecimalField(source='product.price', max_digits=10, decimal_places=2, read_only=True) rating = serializers.CharField(source='product.rating', max_length=10, read_only=True) class Meta: model = ProductParameter fields = ('id', 'product', 'name', 'price', 'product_desc', 'image', 'rating') as you can see in the model there is Product ForeignKey. In this model there may be more than one product and from this table I should get product which its id is unique. I do not need duplicate products. and for this I am using this view class ProductForParameterView(generics.ListAPIView): serializer_class = ProductForParameterSerializer def get_queryset(self): query_params = self.request.query_params products = query_params.get('product', None) productParams = [] if products is not None: for product in products.split('|'): productParams.append(int(product)) if products is not None: queryset … -
Outer join produced by exclude filter slowing down query enormously
Alright, so we have a sports Season which belongs to a League which belongs to an Association. A season is made up of Matches. On the association page we want to display non-empty current seasons (with matches): class SeasonManager(models.Manager): def current(self): return self.get_queryset().filter(enddate__gte=date.today()).exclude(match=None) And then we defining Association.current_seasons as Season.objects.current().filter(league__association=self). Problem: the last exclude filter creates a massive outer join making the query run for about 15 seconds... I've changed to the following which runs as fast as you'd expect: class SeasonManager(models.Manager): def current(self): seasons = self.get_queryset().filter(enddate__gte=date.today()) return Season.objects.filter(id__in=[s.id for s in seasons if s.match_set.exists()]) I wonder if there's a better way to do it, especially prefetching the "existence" of a season match set, or rather running an intermediate query evaluating that existence. I've tried the following just in case that does the trick but it obviously doesn't: self.get_queryset().filter(enddate__gte=date.today()).exclude(match=None).prefetch_related('match_set__id') -
Cloudinary Image upload from django
I am trying to upload image/file to clodinary to get back the url using this code medical_file = request.FILES['medical_file'] out = cloudinary.uploader.upload(File.open(medical_file, "rb")) url = out['url'] medical_file_url = url And I am successfully getting the url as well(I have printed that on my console) But then I am getting this error of : cloudinary.api.Error: Empty file