Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JWT token not being sent in production (Django REST Framework & Next.js 14)
I'm facing an issue where JWT tokens are not being sent from the client to the server in my production environment. The project consists of a Django REST Framework backend and a Next.js frontend. Everything works fine in the development (127.0.0.1) environment, but in production, the JWT token stored in the cookies is not being sent back to the server. Project Setup: Backend (Django) Settings: Here are my relevant settings in settings.py: REST_AUTH = { 'JWT_AUTH_COOKIE': 'token', 'JWT_AUTH_REFRESH_COOKIE': 'refresh_token', 'JWT_AUTH_SECURE': True, # Enabled for production 'JWT_AUTH_HTTPONLY': True, 'JWT_AUTH_SAMESITE': 'None', } CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://vasa.liara.run', # My frontend domain ] Frontend (Next.js) Configuration: On the client side, I'm sending requests using fetch as follows: fetch("https://api-vasa.liara.run/auth/login", { method: "POST", credentials: "include", // Ensure cookies are sent headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }) }); Environment: Frontend URL: https://vasa.liara.run Backend URL: https://api-vasa.liara.run Browser: Chrome (latest version) HTTPS is enabled for both frontend and backend. Why aren't the cookies being sent in subsequent requests? What could be causing this issue, and how can I fix it? -
Django atomic transaction unit test failing (commits not being rolled back)
I have a Django project with the following two models: # models.py from django.db import models, transaction class Person(models.Model): name = models.TextField() surname = models.TextField() class EmployeeInfo(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) employee_id = models.TextField(null=True, blank=True) @transaction.atomic def provision_employee_id(self): """Make atomic to ensure that two employees being provisioned at the same time do not get the same employee number""" self.employee_id = new_employee_number() self.save() raise Exception("forcing an exception") # Always raise an exception (for testing only) Here is the unit test that is failing: # tests.py class PersonTestCase(TestCase): def test_employee_id_atomic(self): person1 = Person(name="John", surname="Doe") employee_info = EmployeeInfo(person=person1) self.assertIsNone(employee_info.employee_id) # No employee_id yet. with self.assertRaises(Exception) as context: cluster_updated = employee_info.provision_employee_id() self.assertIsNone(employee_info.employee_id) # This FAILS In other words, even though I have wrapped provision_employee_id() in an atomic transaction the save() is not rolled back when the subsequent exception is raised. Why? -
Every variable makes it to index.html except for one?
I'm doing a django project (I'm new to django). So far everything has been running smoothly except for one issue that I can't seem to figure out. Here's my get method for Django: class Index(TemplateView): template_name = 'project/index.html' def get(self, request): allBrands = InventoryItem.objects.values_list('brand', flat=True).distinct().order_by('totalReviews') allAgeGroups = InventoryItem.objects.values_list('ageGroup', flat=True).distinct() items = InventoryItem.objects.all() return render(request, self.template_name, { 'items': items, 'allBrands': allBrands, 'allAgeGroups': allAgeGroups, }) When I added 'allAgeGroups' I was running into the issue where for some reason the index.html was not receiving the information. The query works. When I print(allAgeGroups) in the get() function, I get nothing When I print(allAgeGroups) in the post() function, I get <QuerySet ['Adult', 'Youth']> (what I want) And I just realized I can remove everything from the render function, save the file, refresh the page, and everything still works??? What is happening? Thank you. -
Adding field to model raises `django.db.utils.OperationalError: no such column` during `makemigrations`
Every time I try python3 manage.py makemigrations after adding a new field to my model, I get an error: django.db.utils.OperationalError: no such column: network_user.following The database used in the project is sqlite3. This is what I had in models.py when I've already created users: class User(AbstractUser): pass And this what I wanted to get after adding a new field: class User(AbstractUser): following = models.CharField(default='', max_length=1000000) I've checked through a lot of posts on this problem. And the only solution I found was to delete the database and clear the migration files in Django project. This method works, but you lose all the data. -
Static files in Django
I am trying to create a Django project. I created the application under the name blog. In it I have created static and templates folders. static folder has CSS folder where CSS file. It is attached to an HTML template, but none of the CSS styles work when running the localhost.8000 server. Simple HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> </head> <body> <h1>Hello</h1> </body> </html> Simple CSS h1 { color: red; font-size: 35px; } Terminal 404 error with CSS file enter image description here -
Trying to set up the Development Environment using Django [closed]
I'm trying to create a web-driven database using PostgreSQL and Python. I've successfully created all the necessary tables in the database, but I'm having difficulty setting up the development environment in my terminal. trying to set it up in my termina python manage.py migrate Above is the code I ran but the error message [my response] (https://i.sstatic.net/D3ouVJ4E.png) -
how to resolve latency issue with django M2M and filter_horizontal in ModelAdmin panel?
I have used django ModelAdmin with M2M relationship and formfield filtering code as follows: But for superuser or any other login where the number of mailboxes are more than 1 lakh I have sliced the available after filtering. But loading the m2m field takes time and times out for superuser login: def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "mailboxes": if request.user.is_superuser: queryset = Mailbox.objects.all().only('id','email') kwargs["queryset"] = queryset field = super().formfield_for_manytomany(db_field, request, **kwargs) field.widget.choices.queryset = queryset[:300] # Limit visible options return field if request.user.groups.filter(name__in=['customers']).exists(): queryset = Mailbox.objects.only('id', 'email').filter( domain__customer__email=request.user.email ) kwargs["queryset"] = queryset field = super().formfield_for_manytomany(db_field, request, **kwargs) field.widget.choices.queryset = queryset[:500] # Limit visible options return field return super().formfield_for_manytomany(db_field, request, **kwargs) I want to use filter_horizontal only and not django auto_complete_light or any javascript.how can the latency be resolved. As you can see the queryset filtering is already done to get valid options and then sliced. -
Is there any way I can fix this serializer validation error?
I'm trying to create an Order in Django with an optional promo_code, but I'm getting a validation error: { "promo_code": { "code": [ "This field may not be blank." ] } } Here are my models: class PromoCode(models.Model): code = models.CharField(max_length=255, unique=True, db_index=True) class Order(models.Model): promo_code = models.ForeignKey( PromoCode, on_delete=models.SET_NULL, null=True, blank=True ) In my OrderSerializer, I define promo_code to allow null and set required=False: from rest_framework import serializers class PromoCodeSerializer(serializers.ModelSerializer): class Meta: model = PromoCode fields = ['code'] class OrderSerializer(serializers.ModelSerializer): promo_code = PromoCodeSerializer(allow_null=True, required=False) class Meta: model = Order fields = ['promo_code'] test_payload = { "items": [{"id": "bb6ccdd4-3218-4794-a16a-9327cdfec56f"}], "order_date": "2024-11-15", "promo_code": { "code": "" }, "shipping_info": { "shipping_address": "pursitie 7 F" }, "first_name": "Ebenezer", "last_name": "Ofori-Mensah", "email": "oforimensahebenezer07@gmail.com" } The issue is that when trying to create an order without providing a promo_code (like test_payload), I still get the validation error saying "This field may not be blank." for promo_code. I expected promo_code to be optional. -
Can StreamingHttpResponse blocks the gunicorn with gevents?
I am having Gunicorn with gevents with multiple workers in my system. I have to open few StreamingHttpResponse which uses sleep and timeout in client side as well. My doubt is can this block rest of the requests to the server and make the Django site crashe? -
Generating Email Accounts with My Deployed Website Domain Without Accessing the Domain Registrar
How can I create email accounts for my deployed website domain using aaPanel without accessing the domain registrar? I tried configuring Postfix and Devocot, and I installed DNS, a mail server, and Redis, but I encountered several errors along the way. Recap of What I Did: 1. Installed and configured Postfix and Dovecot. 2. Edited Postfix configuration to use virtual mailboxes. 3. Created a mapping file to associate test@example.dz with a directory. 4. Created the corresponding mailbox directory. 5. Updated Postfix and reloaded it to apply the changes. 6. Configured Dovecot to access the virtual mailboxes. 7. Tested the setup by sending an email to ensure it's working. -
Django is not importing models: Sublime text can't find django. Windows 11
I've been working through Python Crash Course e2, and got stuck on Ch.18. Having opened models.py, and entered the code, the error message is: ModuleNotFoundError: No module named 'django' I have spent some time working on this, without a solution. Could it be that PCCe2 is out of date, or is there a workaround solution? ChatGPT has said to make sure to activate the virtual environment, make sure Django is installed; verify the installation; check my Python environment and ensure it is activated; check for multiple Python installations; check the installation path; verify the installation path; check that "models.py" is in the app directory, and the app is listed in the installed apps, etc. I have tried all of these, and the text editor cannot seem to find the module django. But it is among the files. -
Why does Django keep redirecting to `/profile/dashboard/` instead of a custom URL even after changing the path?
I'm working on a Django project with separate apps for authentication (auth_app) and user dashboard (dashboard_app). After logging in successfully, I expect the user to be redirected to dashboard, but Django keeps redirecting to /dashboard/ instead of /profile/dashboard/ or any other URL I configure. Here's what I've done: URL Configuration: In dashboard_app/urls.py: from django.urls import path from .views import DashboardController app_name = 'dashboard_app' urlpatterns = [ path("dashboard/", DashboardController.as_view(), name='dashboard'), ] In project/urls.py, I have included the dashboard_app under the /profile/ path: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('auth_app.urls')), path('profile/', include('dashboard_app.urls')), ] Login Controller: After a successful login, I use reverse to redirect to the dashboard: from django.shortcuts import redirect from django.urls import reverse class LoginController(View): def post(self, request): # Authenticate the user ... return redirect(reverse('dashboard_app:dashboard')) The Problem: After logging in successfully, I am redirected to /dashboard/ instead of /profile/dashboard/ or any other custom path. Even if I try to change the URL in dashboard_app/urls.py: from django.urls import path from .views import DashboardController app_name = 'dashboard_app' urlpatterns = [ path('somewhere/', DashboardController.as_view(), name='dashboard'), ] however it keeps redirecting to /dashboard/ instead of profile/somewhere/. I don’t have any custom middlewares. I don’t use JavaScript; … -
Django & Cloudinary - Admin Panel Image Upload Returns Error "This res.cloudinary.com page can’t be found"
I have the following Teacher model: class Teacher(models.Model): ... # Image Field image = models.ImageField(upload_to='teacher_images/', blank=False, null=False) # Metadata ... class Meta: verbose_name = "Teacher" verbose_name_plural = "Teachers" ordering = ['name'] indexes = [ models.Index(fields=['email']), models.Index(fields=['department']), ] And in my settings.py: cloudinary.config( cloud_name = "dce5bvfok", api_key = "622363596588819", api_secret = "v9J64YEaRrGODOEUz_8P_0dpYb0", secure=True ) # Set default storage backend to Cloudinary DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' MEDIA_URL = 'https://res.cloudinary.com/dce5bvfok/image/upload/' Yet when I navigate to the admin panel to upload an image, the URL formats correctly. For example: https://res.cloudinary.com/dce5bvfok/image/upload/teacher_images/hsu2-min.JPG. However, I can't actually view the image as I receive this error when navigating to the generated URL: This res.cloudinary.com page can’t be found No webpage was found for the web address: https://res.cloudinary.com/dce5bvfok/image/upload/teacher_images/hsu2-min.JPG HTTP ERROR 404 Does anyone know why this is occurring and how to rectify it? -
Django-Filter not working with Pagination Getting object of type 'PostsFilter' has no len()
I'm trying to make Django-Filter work with Pagination--but it only works when I pass the 'posts' to Paginator--but when I try to pass the f--I get an error >>> object of type 'PostsFilter' has no len() Other than that everything works fine. Any suggestions on a workaround? Please see my views.py. views.py def posts(request): posts = Post.objects.all() f = PostsFilter(request.GET, queryset=Post.objects.all()) paginator = Paginator(posts, 50) page_number = request.GET.get("page") posts_qs = paginator.get_page(page_number) return render(request, 'posts/posts.html', { 'posts':posts_qs, 'filter':f, 'title':'Posts' }) -
How to maintain session between django and react between multiple requests?
I am trying set a variable vendor_data in my views to the request.session in django. class MyClass(APIview): def post(self, request, format=None): request.session['vendor_data'] = vendor_data # this is a dict Then I am trying to access this vendor_data key in another DRF view, like this: class AnotherClass(APIview): def post(self, request, format=None): vendor_data = request.session['vendor_data'] But I get keyError, missing key "vendor_data". More Context: The APIs are running on an EC2 with the port open. The APIs are being requested from a localhost react environment, from a PC. My django settings.py allows all host and ALLOWED_HOSTS = ['*'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3002', # react app port 'http://127.0.0.1:3002', 'http://10.0.90.2:8008', # dummy django app port 'http://127.0.0.1:8008', 'http://localhost:8008', ] SESSION_COOKIE_SECURE = False SESSION_COOKIE_AGE = 300 SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_COOKIE_SAMESITE = 'None' I am trying to register and autheticate a user via OTP. I am storing the user details in session until they verify the OTP. But I cannot verify the OTP because, of the keyerror I am receiving in the other view. -
How to annotate, filter then get ForeignKey field relations in Django (FilteredRelation or another method)?
I'm trying to annotate ForeignKey relations and then use new annotated field in loop From docs: >>> from django.db.models import FilteredRelation, Q >>> Restaurant.objects.annotate( ... pizzas_vegetarian=FilteredRelation( ... "pizzas", ... condition=Q(pizzas__vegetarian=True), ... ), ... ).filter(pizzas_vegetarian__name__icontains="mozzarella") That works. But if i do: >>> from django.db.models import FilteredRelation, Q >>> rests = Restaurant.objects.annotate( ... pizzas_vegetarian=FilteredRelation( ... "pizzas", ... condition=Q(pizzas__vegetarian=True), ... ) ... ) ... for rest in rests: print(rest.pizzas_vegetarian) I get AttributeError: "Restaurant object has no attribute 'pizzas_vegetarian'" I need access to that "pizzas_vegetarian" in separate code blocks. Is it possible with FilteredRelation? Wich method should i use to get it? -
How can I change CustomUser model fields in view and forms
I am building a scoring system and I want to register a score for those who are active on the website, for example, when someone leaves a comment, get 5 points, but I didn't succeed and I tried several methods. models.py class CustomUser(AbstractUser): activity_point = models.PositiveIntegerField(default=0) First method in views.py class NewsDetailView(generic.DetailView): model = News template_name = 'news/news_details.html' def get_context_data(self, **kwargs): context = super().get_context_data() if self.request.user.is_authenticated: context['comment_form'] = CommentForm() return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): news = self.get_object() form.instance.author = request.user form.instance.news = news self.request.user.activity_point += 5 # Here form.save() return redirect(reverse('news_detail', kwargs={ 'pk': news.uid })) Second method in views.py class CitizenNewsCreateView(mixins.LoginRequiredMixin, generic.CreateView): model = News template_name = 'news/news_create.html' form_class = CitizenReporterForm success_url = reverse_lazy('citizen_report_list') def get_queryset(self): # Here user = CustomUser.objects.filter(username=self.request.user.username) change_activity_point = user.activity_point + 5 return change_activity_point def form_valid(self, form): form.instance.author = self.request.user form.instance.active = False form.instance.citizen = True return super(CitizenNewsCreateView, self).form_valid(form) I expect its change the activity point to 5. -
Parameters to FilterView from template redirect
I've read through all similar Q&As but can't figure out how to achieve what I'm wanting. My base.html has a dropdown menu based on academic years: <div class="dropdown"> <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> <svg class="bi pe-none me-2" width="16" height="16"><use xlink:href="#archive"/></svg> <strong>Select Year</strong> </a> <ul class="dropdown-menu dropdown-menu-dark text-small shadow"> {% for year in years %} <li><a class="dropdown-item"href="{% url 'administration.home_selected' year %}">{{year}}</a></li> {% endfor %} </ul> </div> administration.home_selected is a function based view and receives the parameter of year to show the desired data relating to that academic year: url.py path( "home_selected/<int:year>", views.home_selected, name="administration.home_selected", ), How do I replicate the same functionality when a navigation tabs within the home_selected.html is selected and relates a FilterView: path( "learners/<int:year>", views.FilteredLearnerListView.as_view(), name="administration.learners", ), The view is currently coded to show only current year data but I'd like to be able to do the same as I have with the function based view to show the correct data depending on the year selected from the base.html views.py class FilteredLearnerListView(SingleTableMixin, FilterView): table_class = LearnerTable model = Learner context_object_name = "learner_list" current = AcademicYear.objects.filter(is_current=True).get() contracts_list = Contract.objects.filter(academic_year=current).values_list( "id", flat=True ) contracts_list = list(contracts_list) contracts = Contract.objects.filter(academic_year=current).values() groups = Group.objects.filter(contractId__in=contracts_list) queryset = Learner.objects.filter(groupId__in=groups) template_name = … -
Django - Custom Error Templates not rendering
I have some custom templates in my django app. But these are not being rendered and instead displays the basic template: 500 Internal Server Error Exception inside application. Daphne This is my setup: Views.py (app level: main): def custom_500(request): return render(request,'main/500.html', status=500) templates (app level: main with path: templates->main->500html) 500.html custom template file urls.py (project level) from main.views import custom_400, custom_500 from django.conf.urls import handler500, handler400 handler500 = 'main.views.custom_500' settings (folder) staging.py: DEBUG = False ALLOWED_HOSTS = ['domainname.com' ] SECURE_SSL_REDIRECT = True I also have a base.py in my setting folder, but cannot see anything I should report on there. I tried to list all the checks I have tried: In heroku app shell: print(settings.ALLOWED_HOSTS) # returned the domain name print(settings.DEBUG) # returned false print(os.getenv('DJANGO_SETTINGS_MODULE')) # mysite.settings.staging print(settings.CSRF_COOKIE_SECURE) # true (just in case I would the app would be treated as non prod) print(settings.SECURE_SSL_REDIRECT) # true (just in case I would the app would be treated as non prod) and finally: >>> from django.shortcuts import render >>> from django.test import RequestFactory >>> request = RequestFactory().get('/') >>> render(request,'main/500.html', status=500) #returned: <HttpResponse status_code=500, "text/html; charset=utf-8"> I am running out of idea, and I am sure its probably something simple. I am hoping … -
Why do migrations run faster under `./manage.py test` compared with `./manage.py migrate`?
Why do migrations run faster under ./manage.py test compared with ./manage.py migrate? I'm not running an in memory database for unit tests or anything like that. Both the proper app and the unit test db use the same mysql docker container. I am using the NoseTestRunner. This came up because I am trying use the Pytest runner but I found that it was much slower. I know that ./manage.py test is in fact running the migrations, there are no shortcuts like that. I have not technically verified that all cases run the same number of migrations. I'm guessing some database optimization is being applied, like removing constraints or something. I have these two dependencies installed. django-nose==1.4.7 Django==3.2.25 -
Is there are any way to add 2 models as auth-user-model?
i have created 2 apps user and a vendor. This is the error i am facing. " AttributeError at /users/admin/login/ Manager isn't available; 'auth.User' has been swapped for 'vendors.Vendor' Request Method: POST Request URL: http://127.0.0.1:8000/users/admin/login/ Django Version: 5.1.3 Exception Type: AttributeError Exception Value: Manager isn't available; 'auth.User' has been swapped for 'vendors.Vendor'" Can i add both the Vendor and user ? -
Write a datetime to the database using model.DateTimeField() in Python Django, the UTC timezone is not correctly displayed in the database
settings.py TIME_ZONE = "Asia/Taipei" USE_I18N = True USE_TZ = True models.py from django.db import models class ApiLog(models.Model): endpoint = models.CharField(max_length=255) method = models.CharField(max_length=10) request_body = models.TextField() response_body = models.TextField() timestamp = models.DateTimeField() class Meta: db_table = 'api_log' managed = False # 若資料表為手動建立,將 managed 設為 False def __str__(self): return f"{self.method} {self.endpoint} at {self.timestamp}" views.py def simple_api(request): endpoint = request.path method = request.method request_body = request.body.decode('utf-8') if request.body else "" if method == 'GET': response_data = {'message': 'This is a GET request'} elif method == 'POST': try: data = json.loads(request.body) response_data = {'message': 'Data received', 'data': data} except json.JSONDecodeError: response_data = {'error': 'Invalid JSON format'} else: response_data = {'error': 'Method not allowed'} response_body = json.dumps(response_data) # def UTC+8 tz = pytz.timezone('Asia/Taipei') # get utc+8 time current_utc_plus_8_time = timezone.now().astimezone(tz) print("Current UTC+8 Time:", current_utc_plus_8_time) # record ApiLog ApiLog.objects.create( endpoint=endpoint, method=method, request_body=request_body, response_body=response_body, timestamp=current_utc_plus_8_time ) return JsonResponse(response_data) Based on this design, I expect the recorded timestamp in the database to be in the format “yyyy-MM-DD HH:mm:ss.ssssss+08:00.” However, when querying directly with a SELECT statement in the database, the result is converted to UTC+0. I’ve tried several methods to resolve this issue. For example: In Java, using mybatis mapper @Mapper public interface ApiLogMapper { @Insert("INSERT INTO … -
Importing module within the celery task
I wonder whether there could be difference between the following code snippets from some_module.sub_module import some_function @app.task(soft_time_limit=16, time_limit=18) def call_function(): some_function() and @app.task(soft_time_limit=16, time_limit=18) def call_function(): from some_module.sub_module import some_function some_function() I'm using celery with Django and there are around 16 celery processes. Is there some difference between th abovementioned pieces of the code? I feel like there can be some difference. What if inside some_module.sub_module module there is a variable? Will all workers share it? Or absolutely everything is separated? Thank you. -
Multiple forms that are different in a view Django
I was wondering if there was a way to have multiple different forms in a single view and to press a single submit button for the information to be stored. I have the following forms, the first one is my general form that should be created first: class GeneralForm(forms.ModelForm): name = forms.CharField(max_length=50) TYPE_CHOICES = ( ("C","C"), ("E","E") ) STATUS_CHOICES = ( ("A", "A"), ("F", "F"), ) type=forms.ChoiceField(choices=STATUS_CHOICES) number=forms.CharField(max_length=50) TURN_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3") ) turn = forms.ChoiceField(choices=TURN_CHOICES) class Meta: model = models.General fields=["name","type","number","turn"] The second one needs an instance of the first one and so does the third: class TypeOneForm(forms.ModelForm): num_chairs=forms.IntegerField() num_instalations = forms.IntegerField() total = forms.IntegerField() num_programs = forms.IntegerField() class Meta: model = models.TypeOne fields=["num_chairs","num_instalations","total","billetes_cien"] class TypeTwoForm(forms.ModelForm): num_available_seats=forms.IntegerField() num_available_instalations = forms.IntegerField() total = forms.IntegerField() num_new_programs = forms.IntegerField() class Meta: model = models.TypeTwo fields=["num_available_seats", "num_available_instalations","total","num_programs" ] These are my models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class General(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) name = models.CharField(max_length=100) TYPE_CHOICES = { "C": "C", "E": "E", } type = models.CharField(max_length=10, choices=TYPE_CHOICES) STATUS_CHOICES = { "A": "A", "F": "F", } status = models.CharField(max_length=10, choices=STATUS_CHOICES) number … -
MemoryError inside celery, but no error outside
I'm using Django 5.1.3 and Celery 5.4.0. I have one task. If I run it without Celery, then everything is OK. If I run it with the help of Celery, I get MemoryError. What is the reason for this? Can I tune somehow Celery to avoid this error? It would be good if the behavior was consistent. Thank you.