Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CustomUser
I extended default User model as follow: class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length = 100, blank = False) last_name = models.CharField(max_length = 100, blank = False) ... USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'username','password'] Now when creating a new superuser the prompt for password is not hidden $ python manage.py createsuperuser Email address: user1@coolapp.com First name: John Last name: Smith Username: cool_username Password: fancy_p4$$w0rd Superuser created successfully. Is there any way it can be hidden? -
Create model for schema of csv file
I need to create model for schema which consists of name and columns. Users can build the data schema with any number of columns of any type. Each column also has its own name (which will be a column header in the CSV file), type and order (just a number to manage column order). The problem is that I have to create schema at one time with columns, but I don't know how to do this. My current models: SCHEMA_TYPE_CHOICE = ( ('Full Name', 'Full Name'), ('Job', 'Job'), ('Email', 'Email'), ('Company', 'Company'), ('Phone Number', 'Phone Number'), ('Address', 'Address'), ('Date', 'Date'), ) class Schema(models.Model): title = models.CharField(max_length=100, unique=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Column(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=100, choices=SCHEMA_TYPE_CHOICE, default='Full Name') order = models.PositiveIntegerField(default=1) schema = models.ForeignKey(Schema, on_delete=models.CASCADE, related_name='column_schema') def __str__(self): return self.name Form that I have to realize: enter image description here -
Best backend language for full stack development
What should I use - Node.js(Javascript) Or Django(Python) , If I want to become a full stack Developer? I'm a beginner in this. So please give suggestion regarding this. -
Django prefilled Admin Tabular Inline
My goal is that the first column of my tabular inline sheet is filled with data from another table. I've attached a screenshot where you can see that for tablename=game I want to insert the game number (eg. 1), the metric (e.g time), the player_names and the values (-> scores) per player. Number and metric applies to the hole game. Each game within Table=Game shall contain number metric player_1:name and score player_2:name and score ... and so on. The player names are stored in a table called players. Is there a way to pre-fill the first row of my tabular inline with my player_names. Otherwise i have to write it down for each game. Django admin panel_tabularInline I've created several models in models.py: class Game(models.Model): player_name = models.CharField(max_length=30) class Game (models.Model): NUMBER = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)) METRIC = ( ('Kills', 'Kills'), ('Time', 'Time'), ('Deaths', 'Deaths') ) number = models.BigIntegerField(default=1, choices=NUMBER) metric = models.CharField(max_length=30, choices=METRIC) class GameItem (models.Model): value = models.CharField(max_length=30) game = models.ForeignKey(Game, on_delete=models.CASCADE) def __str__(self): This is my admin.py file: from django.contrib import admin from .models import * class GameItemInline(admin.TabularInline): model = GameItem extra = 6 #I've got 6 … -
Get jwt token to pass it to unit test
I'm trying to retreive jwt access token to pass it to unit test but everytime I try to get it I receive 'not authorized' error. User is created in database with factory #factories.py class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = "test_user" password = "test123" date_of_birth = "2000-01-22" email = "tests@test.ru" role = "moderator" class AdFactory(factory.django.DjangoModelFactory): class Meta: model = Ad name = "test" author_id = factory.SubFactory(UserFactory) price = 100 description = "None" is_published = "FALSE" category = factory.SubFactory(CategoryFactory) image = None And I', trying to get jwt access token in fixtures.py # fixtures.py import pytest @pytest.fixture @pytest.mark.django_db def user_token_jwt(client): username = "test_user" password = "test123" response = client.post( "/user/token/", {"username": username, "password": password}, format="json" ) print(response.data) return response.data["access"] Finally, the test function itself. Please help me to understand how to retrieve a jwt access token in Django with such project architecture? @pytest.mark.django_db def test_create_ad(client, ad, user_token_jwt): # user_token_jwt = client.post( # "/user/token/", # {"username": "test_user", "password": "test123"}, # content_type="application/json" # ) expected_response = { 'id': ad.pk, 'name': 'test', 'author_id': ad.author_id_id, 'author': ad.username, 'price': 100, 'description': 'None', 'is_published': 'FALSE', 'category_id': ad.category_id, 'image': None } data = { "name": "test", "price": 100, "description": "None", "author_id": ad.author_id, "category": ad.category_id, } response … -
How to show value of Count Function on my template. Django
I would like to show the total number of employees registered in my database. Using the count function. My views.py: def home(request): return render(request, 'dashboard.html') def return_total_employees(request): return_total = Employees.objects.aggregate(total=Count('EmployeeCard'))[ 'total' ] return render(request, 'dashboard.html', {'return': return}) My template: <h1> {{ view.return_total_employees }} </h1> -
check for exact presence in a queryset django, jinja 2
in my case, I have a question to check if the exact string name of a model does exist in a query set. here is my code: views.py: if Despiking.objects.filter(user=request.user).exists(): filtered_projects = Despiking.objects.filter(user=request.user) context.update({ 'filtered_projects': filtered_projects.__str__(), }) template.html: {% if info.project_name in filtered_projects %} <!-- some HTML elements --> {% else %} <!-- other HTML elements --> {% endif %} in my code, there is no difference between "my project" and "project" as info.project_name model. because of that the "project" word exists in the query set when I have only the "my project" in it. so using {% if info.project_name in filtered_projects %} works the same (the condition of if will be True) because that "project" word exists in the query set because of the "my project". what can I do to check the exact string in it? -
Django context isn't passing information to template
I try to pass information to an html template from a view function. Every time I try to call the variable from the html template it doesn't show anything. Here is my configure_peplink.html: {% extends "base_generic.html" %} {% block content %} <h1>Configure Peplink</h1> <p>Configure a Peplink router from the web. This was designed by <em>Valorence LLC</em></p> {% if peplink %} <p>Serial Number: {{ peplink.serial_number }}</p> <p>IP Address: {{ peplink.ip_address }}</p> <p>Mac Address: {{ peplink.mac_address }}</p> <p>Name: {{ peplink.name }}</p> {% else %} <p>No Data Found Off Device</p> {% endif %} {% endblock %} Here is the view function configure_peplink: def configure_peplink(request, peplink): selected_peplink = PeplinkDevice.objects.get(serial_number=peplink) print(selected_peplink.ip_address) print(selected_peplink.serial_number) print(selected_peplink.mac_address) context = { 'peplink': selected_peplink } return render(request, 'configure_peplink.html', context=context) Here is the url line to call the view: re_path(r'^configurepeplink/(?P<peplink>.*)/$', views.configure_peplink, name='configurepeplink') I've tested to make sure that the context has data in it (as seen with the print statements). Even though the context variable has data and is getting past the if statement in the html template it still doesn't display any data. I have tried clearing my cache on the browser and restarting all my services (django, celery, redis-server). Here is a picture of the webpage: -
Django-widget-tweaks Email address can't be entered error
I'm using Django-widget-tweaks. I am getting an error that prevents me from entering my Email address. What is the solution? html {% extends 'app/base.html' %} {% load widget_tweaks %} {% block content %} <div class="card card-auto my-5 mx-auto"> <div class="card-body"> <h5 class="card-title tex-center">ログイン</h5> <form method="post" class="form-auth"> {% csrf_token %} <div class="form-label-group"> {% render_field form.login class='form-control' placeholder='Email' %} </div> <div class="form-label-group"> {% render_field form.password class='form-control' placeholder='Password' %} </div> <div class="buttton mx-auto"> <button class="btn btn-lg btn-primary btn-block mx-auto" type="submit">Login</button> </div> </form> </div> </div> {% endblock %} I can't enter my email address. -
django - overriding save method with super returns unique contraint error when creating object
Overriding save method with super returns unique contraint error when creating object. How to solve it? def save(self, *args, **kwargs): if self.pk is None: super(IntoDocumentProduct, self).save(*args, **kwargs) # some logic # more logic super(IntoDocumentProduct, self).save(*args, **kwargs) self.full_clean() Below is the error that appears in the console. It directs specifically to the save() method in the model. I don't know what is wrong with it. After all, I can't use self.save(), because there will be a recursive loop. Traceback (most recent call last): File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 81, in inner return func(*args, **kwds) ^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\src\wms\api\views.py", line 183, in post serializer.save() File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 212, in save self.instance = self.create(validated_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "W:\projects\foodgast\venv\Lib\site-packages\rest_framework\serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) AttributeError: 'str' object has no attribute 'get'
this is django rest_framework api I created this api for restourant. This is menu api . I want to save menu.json's data to my database, but I could not. Can you give any advice to save json data to my models. I got this error: File "C:\Users\OSMAN MERT\Desktop\menu\menu_core\api\models.py", line 36, in store_json_data meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) AttributeError: 'str' object has no attribute 'get' How can I solve it? I need your help? models.py from django.db import models import json # Create your models here. class Meal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) is_vegetarian = models.BooleanField(default=False) is_vegan = models.BooleanField(default=False) class Ingredient(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) groups = models.CharField(max_length=100) class Option(models.Model): id = models.AutoField(primary_key=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) name = models.CharField(max_length=100) quality = models.CharField(max_length=100) price = models.FloatField() per_amount = models.CharField(max_length=100) class MealIngredient(models.Model): id = models.AutoField(primary_key=True) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) path = r"C:\Users\OSMAN MERT\Desktop\menu\menu_core\menu.json" def store_json_data(json_data): for meal_data in json_data: meal, created = Meal.objects.get_or_create(name=meal_data.get('name', '')) if not created: meal.is_vegetarian = meal_data.get('is_vegetarian', False) meal.is_vegan = meal_data.get('is_vegan', False) meal.save() for ingredient_data in meal_data.get('ingredients', []): ingredient, _ = Ingredient.objects.get_or_create(name=ingredient_data.get('name', ''), meal=meal) for option_data in ingredient_data.get('options', []): option, _ = Option.objects.get_or_create(quality=option_data.get('quality', ''), ingredient=ingredient) option.price = option_data.get('price', 0) option.save() def load_json_file(path): … -
i cant run local server. What shoud me do?
Traceback (most recent call last): File "C:\Users\Zet\PycharmProjects\pythonProject1\web\manage.py", line 22, in main() File "C:\Users\Zet\PycharmProjects\pythonProject1\web\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Установил django, попробовал запустить локалный сервак, чтобы убедится, что это всё работает. IDE PYcharm. И если, что я новичок. Сразу говорю пытался устанавливать через pip3, удалял всё, и один раз сработало, но потом опять перестало работать. И виртуальное окружение скачивал. -
python-telegram-bot in django application
I’m trying to start python-telegram-bot in a web application with the django framework. To do this, I follow any example from the Telegram library and end up calling the method application.run_polling(). I know it’s not the best option because this blocks my web server, and I want to replace it with a better one, but I can’t find it. According to official documentation, there is a tip that indicates the following: When combining python-telegram-bot with other asyncio based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater. Keeping the event loop running and listening for a stop signal is then up to you. And then I find the following section: See also initialize(), start(), stop(), shutdown() telegram.ext.Updater.start_polling(), telegram.ext.Updater.stop(), run_webhook() I’ve tried to understand the methods in the list, but I can’t figure out how to run python-telegram-bot in the background and not affect my main server. Are there any links or documents that expand the information or detail the steps to follow in these cases? … -
How to return ordered objects from django CBV(ListView) when you click a button or link in the template
So I'm building an e-commerce store with Django(First project after learning). I need to click on Sort in the template, and have the CBV return an object that's ordered by either, price, or whatever field I specify in the request. This is what I have so far Template Sort by Lowest Price View class ClotheListView(ListView): model = Clothe paginate_by = 8 def get_filter_param(self): # Grab the absolute url and then retrieve the filter param filter_param = self.request.path.split("/")[-1] return filter_param def get_queryset(self): filter_param = self.get_filter_param() if(filter_param != ""): queryset = self.model.objects.filter(cloth_gender=filter_param) else: queryset = self.model.objects.all() return queryset return clothes_filtered_list.qs def get_ordering(self): ordering = self.request.GET.get('ordering', '-cloth_price') return ordering def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context Url.py urlpatterns = [ path('', views.ClotheListView.as_view(), name="clothe_list"), path('<slug:slug>', views.ClotheListView.as_view(), name="clothe_list_category"), path('<int:pk>/', views.ClotheDetailView.as_view(), name="clothe_detail") ] -
Django Form ChoiceField pass parameter for database query
I want to create a Django Form ChoiceField. The choices will be queried from an external database and should be filtered by a parameter {company_id}. How to pass this parameter? views.py if request.method == 'GET': company_id = 1 site_id = 3 return render(request, 'sites/new-column.html', { 'company_id': company_id, 'site_id': site_id, 'form_newcolumn': NewColumn(company_id), }) forms.py class NewColumn(forms.Form): def __init__(self, *args, **kwargs): company_id = kwargs.pop('company_id') super(NewColumn, self).__init__(args, kwargs) self.company_id = company_id # Add it as an instance variable engine = db.engine("Database") connection = engine.raw_connection() cursor = connection.cursor() cursor.execute(f"SELECT * FROM table WHERE id = '{company_id}' ; ") all_rows = cursor.fetchall() choices = forms.ChoiceField( choices=[(row[0], row[1]) for row in all_rows], help_text='Make your Choice' ) How to pass {company_id} to query only the necessary choices? -
7. Add number of expenses per category row in category list
I'm working in Django ORM, I have two classes and 2 forms. I want the values from the queryset from the ExpenseListView(ListView) class to be displayed in the CategoryListView(ListView) class, and then in the category_list.html form from django.contrib.admin import filters from django.db.models import Sum, Count, Max, Q from django.db.models.functions import ExtractYear, ExtractMonth from django.views.generic.list import ListView from . import models from .forms import ExpenseSearchForm from .models import Expense, Category from .reports import summary_per_category class ExpenseListView(ListView): model = Expense paginate_by = 20 # how may items per page def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() fromdate = form.cleaned_data.get('fromdate', '') todate = form.cleaned_data.get('todate', '') category = form.cleaned_data.get('category', '') order_by = form.cleaned_data.get('order_by', '') sort_descending = form.cleaned_data.get('sort_descending', '') filters = {} if name: filters['name__icontains'] = name if fromdate and todate: filters['date__range'] = [fromdate, todate] if category: filters['category__in'] = category queryset = queryset.filter(**filters) if order_by: if sort_descending: queryset = queryset.order_by(order_by).reverse() else: queryset = queryset.order_by(order_by) total_amount_spent = queryset.aggregate(Sum('amount')) total_summary_per_year_month = queryset.annotate(year=ExtractYear('date'), month=ExtractMonth('date')). \ values('year', 'month').annotate(sum=Sum('amount')).order_by('year', 'month') return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), total_amount_spent=total_amount_spent, total_summary_per_year_month=total_summary_per_year_month, **kwargs ) class CategoryListView(ListView): model = Category paginate_by = 5 How to download data from one … -
Django admin page is missing CSS
I am actually following a youtube tutorial for learning Django and admin site is not showing properly. The admin tab in the video looks like this: My admin tab however looks like this: An answer in stack overflow suggested to put DEBUG = True in settings.py file. But it is already set to that in my case. -
How do i rewrite my code with Routers? Django rest framework
I have this REST API: urlpatterns = [ path('admin/', admin.site.urls), path('users/', UserViewSet.as_view({'get': 'list', 'post': 'create', 'delete': 'delete'})), path('users/<uuid:pk>/video/', UserViewSet.as_view({'post': 'video'})) ] How can i rewrite this with routers? Default router with register method creates API different from current. Or, maybe, in this situation it would be more correct to use my code? -
uwsgi only sending stdout logs to GCP in Kubernetes Engine
I have a django application for which I want to send logs to GCP. Locally, everything works fine using django dev server and Cloud Logging for Python. I see the logs on my GCP dashboard with the right level, I can also see the json structured logs when I use them. It also works well when I'm using gunicorn in a local docker instead of the django dev server. However, as soon as I'm using uwsgi locally, I can't find any trace of my logs in the GCP dashboard. When I deploy my docker image in Kubernetes Engine, all the logs are only displayed as info and they are not json structured anymore. I noticed that the logger name is stdout in my log explorer. I'm supposing that somehow uwsgi don't use my python logging config and only logs to stdout that is automatically sent as info by some internal gcp process. Here's my uwsgi.ini: [uwsgi] chdir=xxx module=xxx http = 0.0.0.0:8080 vacuum = true enable-threads = true listen = 128 # socket-timeout, http-timeout and harakiri are in s socket-timeout = 180 http-timeout = 180 harakiri = 180 harakiri-verbose = true py-autoreload = false processes = 4 memory-report = false master … -
Django STATIC_URL with full domain breaks static assets locally
When working locally on a Django project that uses static files and the default static files backend, I am running into an issue when I want to get full absolute urls to the static files instead of only the path. My settings: DEBUG = True BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = ["django.contrib.staticfiles", ...] STATIC_ROOT = BASE_DIR / "static_root" STATIC_URL = "/static/" MEDIA_ROOT = BASE_DIR / "media_root" MEDIA_URL = "/media/" STATICFILES_DIRS = (BASE_DIR / "static",) STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) Everything works, the admin's CSS is loaded, images work, etc. But when I get the path of a file with this code: from django.contrib.staticfiles.storage import staticfiles_storage static_path = staticfiles_storage.url("path_to_folder/some_file.jpg") That result is a relative path: /static/path_to_folder/some_file.jpg. This is a problem when these urls are used from my external frontend: it now has to prepend the backend's base url to all static assets. But if I'd want to deploy the static assets to S3 for example, in production, then I should not prepend these paths with the domain of the backend. So what I tried to do was to change the STATIC_URL setting to http://localhost:8000/static/. That way the full url is passed to the frontend, but I could really easily change this … -
Django autogenerate/share URLS
This is more of a general question on what tools and how I should set something up... Background: I am a relative beginner and I made a website called wordlegolf which is very similar and popular to the original wordle game but it tracks your score and has a scoreboard page that shows everyone on the site's scores. What I need help with: I want to make it so you can create your own scoreboard or league so that not every person on the site goes to one scoreboard. So you can have a scoreboard with your friends or family. I want to make it so you can create a league and then share a unique URL to invite people to that league. I was looking into channels to do this but I think that is more than what I need. I'm going to have to adjust my database but I mostly just wanted a project or explanation on how to create unique autogenerated URLs and how to create objects in a database to match that URL. I haven't tried much, just been looking around on what to use and how to achieve my goal and getting more confused. also … -
Custom is_valid() Serializer Django
I need to write custom check if data in body of a request is_valid() Below is my serializer class class UserSerializer(serializers.ModelSerializer): uid = serializers.IntegerField() user_id = serializers.IntegerField() u_name = serializers.CharField(max_length=50) age = serializers.CharField(max_length=100) email = serializers.CharField(max_length=100) preferredtime = serializers.DateTimeField() car = TableEvs() pref_pay_mode = serializers.CharField(max_length=100) Next I need to check if json body in post request has matching data as defined in TableEvs Class : class TableEvs(models.Model): # uid = models.BigIntegerField() ev_uid = models.IntegerField() company = models.CharField(max_length=100) model = models.CharField(max_length=100) can someone confirm if its possible ? -
How to handle shopify admin API calls rate limit in django app
I have a shopify app that built in django app with some celery workers, each worker can send a lot of request to shopify and the types of request have several priority in my app, now I want to build a shared priority queue between workers for each store to handle shopify rate limit and priority: celery worker 1: import shopify import time # update more than 1000 of variants for variantId in variantIds: time.sleep(0.5) with shopify_session(store.domain, store.token): shopifyVariant = shopify.Variant.find(variantId) # here some cahnges on variant shopifyVariant.save() celery worker 2: import shopify import time # update store info for store in stores: time.sleep(0.5) with shopify_session(store.domain, store.token): shopInfo = shopify.Shop.current() # update shop info in app database web app: class TagList(APIView): @generate_shopify_session def get(self, request): try: data = ShopifyGraphQl().tags() except BaseException as err: return JsonResponse({"message": str(err), 'success': False}) return JsonResponse({"data": data, "success": True}) These are a few examples of api calls in my app that can be called in one second and shopify will response with 429 too many request status code What is the best architecture for implement queues and handle the shopify rate limit? -
Readiness and liveness probes for application with dependencies (DB, Celery, RabbitMQ)
Imagine there is a Django application. The application dependencies: DB, Celery (workers, beat), RabbitMQ (as a broker for Celery). If with liveness probe it is more or less clear (if the liveness probe did not pass, it restarts pod), then with readiness probe there is no full understanding. They write that readiness probes determine whether the container is ready to accept traffic. In this regard, the following questions arise: For the application configuration described above (with dependencies), what would a readiness probe look like? Will it be an endpoint that checks the availability to the database, RabbitMQ, the health of the Celery workers? If the readiness test is complex (checking the availability of the database, RabbitMQ, Celery workers), then what will Kubernetes do if, for example, RabbitMQ becomes unavailable? Because all containers work with the same RabbitMQ, it makes no sense to switch traffic to another pod. -
How to get return from celery task in Django to view?
I am processing a large file using celery task in my Django app. I have an APIView in which when it receives a POST, it will trigger the process. In the celery task, I create a model instance and save. How am I going to receive it back to the APIView so that I can serialize the instance. For simplicity. This would be my APIVIew. # views.py class RequestFile(APIView): def post(self, request): ... image = long_running_function.delay( request.user.id, request.data ) ... # how to get the return from the long_running_function? # return model serializer In my celery task. I am creating a model instance that I would like to de-serialize in my view. # models.py class Image(models.Model): name = models.CharField(max_length=50, blank=True) ... # tasks.py @shared_task def long_running_function(user, data): image = Image.objects.create() ... return image # can I return the model instance here? Is there a function where I can know when the function is done, and return the model instance or the key/id of the instance created?