Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django html regulate input value based on the select option
Here the scenario is that in the html select, there are two options "cube" or "cylinder". and there are three input fields: length, width, and height. what I am looking for is that when user select "cylinder" option from the dropdown menue, there must require user to input the same value for length and width input fields. if not, when click submitting form, there should be an alert to advise users to make sure both length and width value being the same. what is the easiest way to do such work? -
Simple Django Form with Ajax Submission Not Updating Model
I'm trying to write a simple form using Ajax. After multiple attempts, I keep getting "POST /app/emails/ HTTP/1.1" 200 13950 in Terminal, but the model doesn't update (even when I look in the shell). I really would like the abilityt to submit the form within the modal, and update the image behind it. However if that's not possible I can settle for an alternative. Really stuck here, would love any advice! emails.html <div class="modal fade" id="addEmailModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-sm"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Add New Email</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="POST" id='add-email'> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close </button> <button class="btn btn-primary" type="submit">Add</button> </div> </form> </div> </div> </div> Javascript $("#add-email").submit(function (e) { e.preventDefault(); alert('working'); $.ajax({ type: 'POST', url: "{% url 'add-emailname' %}", data: { email_name = $(this).email_name, cadence = $(this).cadence }, success: function (response) { alert("Email name successfully added!") $("#add-email").trigger('reset'); //clear the form }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) } views.py def emails(request): context = { 'emails': UserEmail.objects.all(), 'form': EmailCreateForm() } return render(request, 'app/emails.html', context) def addEmailName(request): … -
How to send values from Django views function to Django forms class during runtime?
My Django Template: {% extends 'main/base.html' %} {%block title%}Delete List{%endblock%} {%block content%} <form method="post" action="/delete/"> {%csrf_token%} {{form}} <button type="sumbit" name="Delete List">Delete List</button> </form> {%endblock%} my function inside view: def delete(response): if response.method=="POST": form1 = DeleteList(response.POST) print(f"delete button pressed: {form1.is_valid()}")#just checking if form1.is_valid(): "" print("valid form: {}".format(form1.cleaned_data))#just checking return HttpResponseRedirect("/display") else: #form1 = DeleteList(10) -- iam trying to make this style work...and use a integer value from my database to set maxVaue of a field #Example: form1 = DeleteList(name="test",data2="somedata"...) -- i want this style to work cause I would pass more values to my forms class in future form1 = DeleteList() return render(response,"main/deleteList.html",{"form":form1}) my django forms class: class DeleteList(forms.Form): #i was trying to make this __init__ work but seems to be buggy """def __init__(self,maxValue:int, *args, **kwargs): super(DeleteList, self).__init__(*args, **kwargs) self.fields['id'] = forms.IntegerField(label="Enter id",min_value=1,max_value=maxValue) id = forms.IntegerField()""" #below one is just static, iam trying to replace this with the above commented block of code id=forms.IntegerField(label="Enter id",min_value=1,max_value=10) #-- only this seems to work Now if do form1 = DeleteList(<int value here>) and receive it on __init__ of forms class, I am able to get the values into form and set my IntegerField's max_value, it only seems to work when the form loads the … -
Inventory project. How to total the value of same name objects in queryset in Django
I have multiple breweries with multiple beers. Some are the same. I need to give a company itemized total. This code iterates over the queryset, finds duplicate names, totals the quantity and then adds it to a dictionary. If no duplicate it goes straight to the dictionary. I'm new to Python and Django so the code is elementary and clunky. Please advise me on more elegant and concise methods to solve this problem. Thanks! def index_inventory(request): keg_totals = {} keg_data = Kegs.objects.all() counter = 0 for keg in keg_data: counter2 = counter + 1 while counter2 <= (len(keg_data)) -1: if (keg_data[counter].beer) == (keg_data[counter2].beer): (keg_data[counter2].quantity) =(keg_data[counter2].quantity)+ (keg_data[counter].quantity) counter2 += 1 else: keg_totals[keg.beer] = keg.quantity counter2 += 1 counter += 1 context = { 'keg_totals' : keg_totals, } return render(request, 'inventory/index_inventory.html', context) -
Django validate 2 forms based on each other
I am trying to build an update screen for a project where a user can hide images from their listing as well as adding more images (images are stored as objects in their own right). I therefore have an a form containing an imagefield to upload new images and a separate formset containing checkboxes for each of the existing images. A validation requirement for the site is that each listing must have at least 4 images displayed with it, thus I need a way of validating both the formset (to check how many pictures are checked) and the imagefield (to check how many images have been added) to ensure that these combine to reach at least 4. I have these checks able to work independently (i.e. 4 images uploaded or 4 images selected) but I was wondering if there was a way of combining the validation criteria into 1 clean (meaning I can either call combined_form.is_valid() in my view or alternatively have this integrated into an existing form's form.is_valid() call), or another way of checking this and raising an error if it fails? Sorry if I have completely butchered this explanation, I'm new here and technical terminology isn't my strong … -
How to set up Django for Fastpanel
I used .htaccess Options +ExecCGI AddHandler wsgi-script .py RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /wsgi.py/$1 [QSA,PT,L] for HestiaCP and wsgi.py import os import sys sys.path.append('PATH_TO_PROJECT') sys.path.append('PATH_TO_PACKAGES_PYTHON') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() and it worked but doesn't work in Fastpanel. How to be? -
Nginx Not Serving Image Files
I have set up a django website that would be served by Nginx, everything was working perfectly not until images stopped showing recently. I tried inspecting the possible cause of this strange development using curl and then realized that the Content-Type is not recognized as Content-Type: image/jpeg returns a Content-Type: text/html; charset=utf-8 This behavior looks strange as I have included mime.types in my nginx.conf file. Below is an example response from curl command user@server:~$ curl -I https://domain.name/media/upload/image.jpg HTTP/1.1 200 OK Server: nginx/1.18.0 (Ubuntu) Date: Sun, 29 May 2022 00:45:53 GMT Content-Type: text/html; charset=utf-8 Content-Length: 11392 Connection: keep-alive X-Frame-Options: DENY Vary: Cookie X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Set-Cookie: csrftoken=T9Z3jrp4dzOAINxo6JzOUyjIGwGYHoc37TZaYsIOmHHyrQUw30vI6ETIAcy66Wnr; expires=Sun, 28 May 2023 00:45:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax Note: I am serving this website with gunicorn -
Django QuerySet calculate sum of values according to a another attribute
I need some help for the creation of 2 queryset . Calculates the total of amounts of the objects considering the user as a common attribute. Given a specific user, calculate considering the categories, ordering the result in "in" and "out". This is the information that already exists in my db (we can suppose that that's the serialized information of all the objects of my only Model: [ { "money": "-51.13", "type": "out", "category": "savings", "user": "jane-doe" }, { "money": "2500", "type": "in", "category": "salary", "user": "foo-bar" }, { "money": "-150.72", "type": "out", "category": "cellphone", "user": "foo-bar" }, { "money": "-560.00", "type": "out", "category": "rent", "user": "jane-doe" }, This should be the output, queryset 1: This consider all the data in the database. [ { "user": "jane-doe", "total_in": "0", "total_out": "-611.13" }, { "user": "foo-bar", "total_in": "2500", "total_out": "-150.72" } ] This should be the output, queryset 2: This must consider de information of a specific user. The next information is just an example of the expected output { "in": { "salary": "1600.51", "savings": "550.50" }, "out": { "groceries": "-41.23", "rent": "-1286.68", "transfer": "-605.15" } } -
Django: Translating words in URLs
I am trying to translate URLs in Django but I am a bit confused when looking at the documentation as well as other posts regarding the same topic. I want to translate: /abourh-su to /about-us. The current code I have tried only let me do: /en/abourh-su Main urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from app import views urlpatterns = [ path('', include('start.urls')), ] urlpatterns += i18n_patterns( path(_('abourh-su/'), views.about, name='about'), ) I have tried adding {% trans " " %} to the different url files but it doesn't work that way as it does with templates. Anyone that knows how to do this? Thanks! -
How to get the username in django admin.py file
I trying to get the username in django admin.py file. I am working on a project purely modification of admin site. I dont have view.py and form.py file in it. I am trying to print the username in the shell so that I can do the necessary action based upon the user group type. Like, user = User.objects.get(username="demostaff") print('is_staff', user.is_staff) print('is_superuser', user.is_superuser) Could you please suggest how to get the username object. -
Django: filter groups in admin panel
I‘m pretty new to Django and I try to customize the admin panel. I want that some other staff members can only assign a specific list of groups. The reason is I manage some other apps with the same project and I don’t want them to manage groups of other apps. What is the best way to realize that? Greets Daniel -
Recover data from a Django Form
It's my first time doing a Django Form challenge. The challenge for now is just from a HTML Template get the last_name information and store into DB from views. So I have a scenario below: models.py: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) an HTML template, I will put below only the form part: <form action="{% url 'store' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label for="last_name" class="col-sm-2 col-form-label">Last Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="last_name" placeholder="Last Name"> </div> </div> <div class="form-group row"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary">Send Last Name</button> </div> </div> </form> And the views.py itself... I created a InsertLastName ModelForm to store the data from the form, but didn't work. For some reason, when I tryed to call form.cleaned_data I reveived an error about the is_valid() verification. Seens like that I'm not getting the information from label. class InsertLastName(forms.ModelForm): class Meta: model = Person fields = ['last_name'] exclude = ['first_name'] def index(request): persons = Person.objects.all() context = {'persons': persons} return render(request, '/index.html', context) def store(request): form = InsertLastName(request.POST or None) print(form.cleaned_data['original_url']) return HttpResponse("Storing a new Last Name object into storage") What is the correct way to get the information from last_name label in my form? … -
How to create a new database for each user in a database using django and mongodb?
I'm creating a web app for my school to help manage and store student documents. I'm creating the app in such a way that each student in the school gets their own database to store documents (absent notes, doctor notes, etc.). I am creating this database webapp using Django and MongoDB. I'm having a hard time figuring out how to link MongoDB and Django in such a way that I can have an infinite number of databases. Ideally, I'd like to have it so that each student gets their own database filled with their own set of documents. I was just wondering how (or if it's even possible) to create an infinite number of databases and link it to Django from MongoDB? If so, how would I set up my settings.py file and my models.py file? As of now, I have used Pymongo as a simple way to create many databases on the original MongoDB server, but haven't found an "ORM" for MongoDB that works for Django and allows me to create many databases. If MongoDB doesn't work, could I try using something else like PostgreSQL? -
MIGRATION in mongoDB not processing, error concerning 'e'
-fit |_ bin |_ gadsonF | |__pycache | |_.. | - __init__.py, asgi.py, settings.py, urls.py, wsgi.py | |_rican | |_ migrations | |_ __init__.py | |_ admin.pu | |_ apps.py | |_ models.py | |_ tests.py | |_ views.py | manage.py | |_ lib |_ .gitignore |_ pyvenv.cfg |_ gadfitAA (webfiles ) ''' Traceback (most recent call last): File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 22, in <module> main() File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 11, in main from django.core.management import execute_from_command_line File "/home/cameronnc/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 52 except ImportError,e: ^ SyntaxError: invalid syntax I created a basic django app above is my file structure I have several models below: from django.db import models from django.db.models import Model class GadsonA(models.Model): """Alyssa Gadson of Puerto Rico""" Alyssa = { "race":"Caucasian", "llc":"Alyssa Gadson LLC", "height":[163, 1.63, "5ft 4 in"], "weight":[110, 130], "hair_color":"Brown", "DOB":"25 November 1989", "eye_color":"Dark Brown", "ethnicity":"Latin/Hispanic", "figure_size":"34D-25-42", "show_size":9, "home_town":"Miami, Flordia, United Stated of America", "gender":"female", "zodiac":"Sagittarius", "hobbiesInterest":['Traveling', 'Shopping', 'Selfie Lover', 'Dog Lover', 'Internet Surfing'], 'philosophy':['self help', 'spirituality', 'fitness', 'working out', 'teaching', 'blogging and acadamia'], "clothingBrands":{"Calvin Klein", "LOUIS VUITTON", "Tommy Hilfiger", "Levi Strauss & Co"}, "gadgets":["Smartphone", "DSLR Camera", "Smart Watch", "DJI Mavic Drone"], "dress_size":"38(EU)", "netWorth":200000, "profession":('fitness trainer', 'model', 'philosopher', 'teacher', 'intellectual', 'model', 'actress', 'buisness woman', 'blogger') } AmealPlan = [] … -
Fetching data from models using OneToOneField in Django
well my college is making us go learn a framework and make a website with it in a month, and it's really killing me, because of that I couldn't really get a good understanding of the Django framework as I am making progress while watching YouTube vids and reading docs. Anyways my models are all messed up which made the job even harder, and whenever I solve a problem another one arises, but the deadline is close and making any changes to the models will cost me a great deal of time. This time my problem is about fetching data. The concerned models are the following: The User class for authentication class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True,null=False) username = models.CharField(max_length=50) email = models.EmailField(unique=True) nom = models.CharField(max_length=255) prenom = models.CharField(max_length=255) usertype = models.CharField(choices=types,max_length=20,default="user") date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) student_data = models.OneToOneField(Etudiant, on_delete=models.CASCADE,blank=True, null=True,related_name='Etudiant_access') Prof_data = models.OneToOneField(Prof, on_delete=models.CASCADE,blank=True, null=True) objects=UserManager() def __str__(self): return self.prenom + " " + self.nom USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] The Students(Etudiant) class for managing the students: class Etudiant(models.Model): filiere = models.ForeignKey(Filiere, on_delete=models.DO_NOTHING) classe = models.ForeignKey(Classe,null=True, on_delete=models.DO_NOTHING) notes = models.ManyToManyField(note,blank=True, null=True) The class Classe (LMAO) for managing … -
How to create Tests for Class Based views in Django
This question might be a little too simple idk. I am very new to testing. I recently made a Django project using all Class-Based views. While I am pretty familiar with Django I am not very familiar with the class-based views so decided to use them in my recent project. I am learning Testing and implemented pytest in one of my FastAPI projects recently. I would say writing tests were easier than I expected or maybe my application was too simple. While there are thousands of pytest courses or testing courses in general available online. I have not seen any focusing on Django class-based views. I am asking this because in class-based views there is a lot of inheritance of prebuilt methods and Views. Will I be able to create tests for class-based views if I go through a good pytest course or do you suggest any particular resource that is specific to the class-based views? I am asking because I want to present this project in an interview and that company seems to care a lot about testing. Here is the Github repo of the project I want to implement tests on: https://github.com/sumitdadwal/django-bookstore-project Also, this is the course I … -
django database path : no unsupported opperand type
In the django settings.py, the database is by default : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } But when i do in python a={'a':'a'/'b'}, i get the error TypeError: unsupported operand type(s) for /: 'str' and 'str'. How come the error doesnt show up in django? I would like to define a different path for my database, in a subfolder so as django automatically create the subfolder and the sqlite database...how can i do that? thank you -
Redirect specific view based on a field django
I need to redirect after login to a specific view according to the "Profesor" field, if this is False, redirect to "vistaAlumno", if True, redirect to "vistaProfesor". views.py def profesor(user): return (user.profesor) @login_required @user_passes_test(profesor) def vistaProfesor(request): rut= request.user.rut_user notas = Nota.objects.select_related('id_asignatura','rut_alumno').filter(rut_profesor=rut) observaciones = Observacion.objects.filter(rut_profesor=rut) return render(request, 'core/vistaProfesor.html', {'notas': notas, 'observaciones': observaciones}) @login_required def vistaAlumno(request): if request.user.profesor == False: rut= request.user.rut_user notas = Nota.objects.select_related('id_asignatura').select_related('rut_profesor').filter(rut_alumno=rut) asistencias = Asistencia.objects.filter(rut_alumno=rut) #Necesito unir la tabla observacion con profesor, lo cual ya hace, pero luego quiero unir la tabla profesor con asignatura y mostrar el nombre en el vistaAlumno.html observaciones = Observacion.objects.select_related('rut_profesor').filter(rut_alumno=rut) curso = Alumno.objects.filter(rut_alumno=rut).values_list('id_curso') horarios = Horario.objects.select_related('rut_profesor','id_asignatura','id_sala').filter(id_curso__in=curso) return render(request, 'core/vistaAlumno.html', {'notas': notas, 'asistencias': asistencias, 'observaciones': observaciones, 'horarios': horarios}) else: vistaProfesor(request) models.py class User(AbstractUser): profesor = models.BooleanField(default=False) rut_user = models.IntegerField(null=True) settings.py LOGIN_REDIRECT_URL = '/vistaAlumno' -
django like button not showing up
I been trying to implement a like button to my django blog but it dosent show up. Anyone got any ideas why the like button wont show up on my blogposts? would really appreciate if someone could help me on this one. newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: … -
Add foreign key to one-to-one model (Extended User Model)
My porpouse is allow users from Client model to login. I extended User model with one-to-one relationship as Django Documentation says. Client model: class Client(models.Model): name = models.CharField(max_length=45) surname = models.CharField(max_length=45) address = models.CharField(max_length=45) email = models.EmailField(max_length=50, blank=False, null=False, default='example@example.com') Extended User: from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=True) class Meta: managed = True db_table = 'extended_user' On Client table (mysql) I have rows. When I use python manage.py migrate terminal shows me django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint'). If I don't write ForeignKey line it don't have error, but I need this ForeignKey. What is wrong here? I tried different parameters on ForeignKey line but nothing. -
Field.__init__() got an unexpected keyword argument 'max_lenght'
I am trying to create an app that would accept an input. views.py: from django.views import generic from .models import GitHubInput class DetailView(generic.DetailView): model = GitHubInput models.py: from django.db import models class GitHubInput(models.Model): body = models.CharField(max_lenght=500) def __str__(self): return f"(self.body)" I get the following error: class GitHubInput(models.Model): File "/Users/swantewit/Dev/tryDjango/git_hub_repo/git_hub/models.py", line 4, in GitHubInput body = models.CharField(max_lenght=500) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 1097, in __init__ super().__init__(*args, **kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' Couldn't find anything in the documentation that would help me. Perhaps I am using a too old tutorial? https://www.youtube.com/watch?v=fblkFtsNg6E 1:10 -
Django database query: how to get multiple objects by id?
i want to get a filtered object with several id's that i will specify TestQuestionBlok.objects.filter() How to write this filter? -
How to send formData from React Native to Django REST using axios
I have a form that is sent as JSON currently. I need to switch it over to using a FormData object since i need to add a file to the request. Django Rest ModelViewSet: class BusinessProfileViewSet(MixedPermissionModelViewSet): """ API endpoint that allows business profiles to be viewed, created, or edited. """ queryset = BusinessProfile.objects.all().order_by('-created_on') serializer_class = BusinessProfileSerializer permission_classes_by_action = { 'list': [IsOwnerOrStaff], 'create': [AllowAny], 'update': [IsOwnerOrStaff], 'retrieve': [IsOwnerOrStaff], 'partial_update': [IsOwnerOrStaff], 'destroy': [IsAdminUser] } paginator = None parser_classes = (MultiPartParser, FormParser,) React-Native: const createFormData = (businessTypes, input) => { const phone = formatPhoneNumForSubmission(input.phone); const typeId = convertBusinessTypeToID(businessTypes); const formData = new FormData(); formData.append("name", input.name); formData.append("type", typeId); formData.append("email", input.email); formData.append("phone", phone); formData.append("street_address", input.street_address); formData.append("city", input.city); formData.append("state", input.state); formData.append("zip_code", input.zip_code); return formData; }; const handleSubmit = () => { const formData = createFormData(businessTypes, newInput); dispatch(createBusiness(formData)); } }; Redux dispatch using axios: export const createBusiness = createAsyncThunk( "business/createBusiness", async (body, { rejectWithValue }) => { try { const response = await axiosInstance.post("/api/businesses/", body); return response.data; } catch (err) { console.log(err.response.data); return rejectWithValue(err.response.data); } } ); Output of console.log(formData): Form data: FormData { "_parts": Array [ Array [ "name", "Dqwd", ], Array [ "type", 1, ], Array [ "email", "qwd@dw.co", ], Array [ "phone", "+115598983333", ], … -
how to customize the response of a api from retrieve function in mixin
I'm a beginner to Django, i have written a class-based API view with mixin. the functionality is simple i.e fetch the data of the given id.Im pasting the code below. class GenericAPi(generics.GenericAPIView,mixins.ListModelMixin,mixins.RetrieveModelMixin): serializer_class=ArticleSerializer queryset=Article.objects.all() lookup_field="id" def get(self,request,id): if id: data=self.retrieve(request) return Response({"data":data.data,"status":data.status_code}) else: return self.list(request) this is the response I'm getting {"id":5,"title":"loream","author":"me"} then I navigate to the retrieve function in the mixin, to make some changes in the response. def retrieve(self, request, *args, **kwargs): print('Retrieving') instance = self.get_object() serializer = self.get_serializer(instance) return Response({"result":serializer.data}) and then I make a call to API, but still, I'm getting the same response. How to customize the response in the retrieve function itself. I need response like this. {"result":{"id":5,"title":"loream","author":"ipsum"}} -
How can I check the health status of my dockerized celery / django app?
I am running a dockerized django app using the following dockerfile: services: web: build: context: . dockerfile: Dockerfile.prod command: gunicorn PriceOptimization.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles networks: - dbnet ports: - "8000:8000" environment: aws_access_key_id: ${aws_access_key_id} redis: restart: always image: redis:latest networks: - dbnet ports: - "6379:6379" celery: restart: always build: context: . command: celery -A PriceOptimization worker -l info volumes: - ./PriceOptimization:/PriceOptimization depends_on: - web - redis networks: - dbnet environment: access_key_id: ${access_key_id} nginx: build: ./nginx ports: - "80:80" volumes: - static_volume:/home/app/web/staticfiles depends_on: - web networks: - dbnet database: image: "postgres" # use latest official postgres version restart: unless-stopped env_file: - ./database.env # configure postgres networks: - dbnet ports: - "5432:5432" volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: static_volume: media_volume: I have added celery.py to my app, and I am building / running the docker container as follows: docker-compose -f $HOME/PriceOpt/PriceOptimization/docker-compose.prod.yml up -d --build Running the application in my development environment lets me check at the command line that the celery app is correctly connected, etc. Is there a way that I can test to see if my celery app is initiated properly at the end of the build process?