Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get with query nested comments?
I am new to django. I'm trying to deal with queries on nested comments. There is a blog project with adding articles and adding comments to articles. For each comment, you can recursively add a comment, and so on. ├── blog_api │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├──── blog_api/api | ├── admin.py | ├── apps.py | ├── __init__.py | ├── migrations | │ └── __init__.py | ├── models.py | ├── permissions.py | ├── serializers.py | ├── tests.py | ├── urls.py | └── views.py └── manage.py I described the following models api/models.py from django.db import models class Article(models.Model): date_pub = models.DateTimeField(auto_now_add=True) title = models.CharField (max_length = 60, blank=True, default='') text = models.TextField(blank=True, default='') owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) class Meta: ordering = ['date_pub'] class Comment(models.Model): date_pub = models.DateTimeField(auto_now_add=True) text = models.TextField(blank=False) owner = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE) article = models.ForeignKey('Article', related_name='comments', on_delete=models.CASCADE) parent = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.PROTECT) class Meta: ordering = ['date_pub'] api/serializers.py from rest_framework import serializers from api.models import Article from api.models import Comment from django.contrib.auth.models import User class ArticleSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Article fields = ['id', 'title', 'text', 'owner', 'comments'] class UserSerializer(serializers.ModelSerializer): … -
Django - How to automatically change the value by selecting different options
I'm quite noob on jquery, so i'm wondering if there's any method to meet my needs. I've got a select box with different options and how to change the value automatically by clicking different values in the select box? enter image description here enter image description here Which means if i choose the value 1 in the first box, the second box value is 1, and it will turn to 2 automatically by select another option in the first box. How to meet my needs? -
How to send Text box data from frontend to backend in python & django web application
I have dropdown button on my html page, which has 4 option and out of four one is other, and when I select other a text box open. Now I want to send the data to backend from textbox for further operations. I am sharing dropdown button i.e. HTML code <html> <head> <script type="text/javascript"> function CheckColors(val){ var element=document.getElementById('color'); if(val=='pick a color'||val=='others') element.style.display='block'; else element.style.display='none'; } </script> </head> <body> <select name="color" onchange='CheckColors(this.value);'> <option>Choose a option</option> <option value="one">ONE</option> <option value="two">TWO</option> <option value="others">others</option> </select> <input type="text" name="color" id="color" style='display:none;'/> </body> </html> Now I want is that when put text is should go to the python script. also it should update after every letter user give. What I have to update in Vies.py and url.py. Thanks in advance. -
How to add user photo to JWT auth tokens in django?
Is it posible to have an image information added to jwt auth token like any other user data? If it s posible, someone please can you help with the solution I'll highly wholeheartedly appreciate it.. Here's how I added the other user data to the jwt token.. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @class method def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['occupation'] = user.profile.occupation token['biography'] = user.profile.biography I hope this helps, and please if you need any file to help better understand the situation, I'll definitely be glad to submit it.. Thanks In advance. -
Django DRF filtering fields in serializer
I'm new to Django DRF and I'm trying to write a more organized code since the one below lacks the correct approach. I have 2 API endpoints: /api/order/info - which shows all the order fields /api/order/status - which shows only one field At the moment I have two serializers and two views as follows: serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['order_id', 'data', 'status'] class OrderStatusSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['status'] views.py # /api/order/info - retrieves all fields class OrderInfo(generics.RetrieveAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer def get_object(self): try: return Order.objects.get(pk=self.request.data['uuid']) except Order.DoesNotExist: raise Http404 # /api/order/status - retrives just one field, the status class OrderStatus(generics.RetrieveAPIView): queryset = Order.objects.all() serializer_class = OrderStatusSerializer # a serializer just for this def get_object(self): try: return Order.objects.get(pk=self.request.data['uuid']) except Order.DoesNotExist: raise Http404 The problem: the code works as expected, but it is pretty clear that it is duplicate! I'm creating a new serializer for just filtering one field, but I strongly believe that DRF makes this easier in some way. Could you please suggest a better approach? Thanks -
Adding related model in separated page Django Admin
The problem is following: All fields are not displayed when I add model for related model using TabularInline but at another side I don't want to use StackedInline, cuz it seems to be not pretty. So, is it possible to use another page to add model for related model, that it automatically will be added to corresponding Partner. Maybe is it possible to use StackedInline for one reason and TabularInline to another, or something similar? Or override adding link? What exactly do I want Displaying: Adding: -
Webhook listener with csrf
I want to create a webhook listener for a third party app. But fot this i have to use @csrf_exempt . Without using the above my web app isn't allowing the third party app to send the webhook data. It blocks it and says forbidden. My question is if we do it without the csrf token can it cause a security vulnerability? What are the other ways to handle this securely. -
Regular expression to validate US phone numbers using Formik and Yup
I'm trying to validate us phone numbers inside my formik form using yep. I found some information on regex here on stackoverflow but it doesn't seem to be working. I basically need to be able to allow brackets, dashes and spaces aswell as the country code. The backend converts everything into something like this: (123) 123-1234 This is what i tried: validationSchema={Yup.object({ AdministratorCell: Yup.string() .matches(/([0-9]{3})[0-9]{3}-[0-9]{4}/, { message: "Invalid phone number", excludeEmptyString: false, }) })} I'm using https://github.com/google/libphonenumber in the backend for backend validation of those phone numbers which is why i need frontend validation to properly work or the form won't submit in some cases where users forget a number or format the number in a certain way. My issue is with what i tried so far is that i can only add the phone number with a certain formatting or it will not submit to the backend. -
Printing Django session data makes pytest tests fail, why?
I am creating a Django app and trying to write test with pytest. I have a weird issue when testing data stored in session. I have a standard view. def dev_my_view(request): if request.method == "POST": post_data = json.loads(request.body.decode("utf-8")) product_id = post_data["productid"] request.session["basket"] = {"id": product_id} response = JsonResponse({"id": f"product number {product_id}"}) return response This test passes as expected. # TEST PASSES OK def test_my_view_OK(self): the_session = self.get_session() self.set_session_cookies(the_session) url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content, {"id": "product number 99"}) self.assertEqual( the_session["basket"], {"id": "99"}, ) self.assertNotEqual( the_session["basket"], {"id": "Invalid value"}, ) But this test fails... # TEST KO def test_my_view_KO(self): the_session = self.get_session() self.set_session_cookies(the_session) print_session_in_tests(the_session) # Session is empty, ok url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) print_session_in_tests(the_session) # Session is empty, why ? self.assertEqual(response.status_code, 200) self.assertJSONEqual(response.content, {"id": "product number 99"}) # The following test fails. KeyError: 'basket' self.assertEqual( the_session["basket"], {"id": "99"}, ) self.assertNotEqual( the_session["basket"], {"id": "Invalid value"}, ) So it looks like the function print_session_in_tests is responsible for that ... Why ? def print_session_in_tests(my_session): print("----------// SESSION (test) //----------") try: for key, value in my_session.items(): print("{} >>> {}".format(key, value)) except: pass print("------- end of printing session ------") pass For information, … -
hmx and django: return HX-Trigger header with json data show error `SyntaxError: JSON.parse...`
I'm following the examples in https://htmx.org/headers/hx-trigger/ my view def my_view(request): res = render(request, 'index.html') res.headers["HX-Trigger"] = ... return res this code works res.headers["HX-Trigger"] = "showMessage" while below code will cause error SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data res.headers["HX-Trigger"] = {"showMessage": "Here Is A Message"} What should I do? -
Django template return POST array
I have an issue about returning data array in POST. I do not find a way to do it... Here the code, I remove not necessary part of the code : View def viewPro(request): if request.method == 'POST': if bool(request.FILES.get('file', False)) == True : ... if analyseType == 'r': ... elif analyseType == 'm': fc, dRect, ctrlRect = ExtractData(file, analyseType) context = { ... 'f' = True, 'fc' = fc, 'dRect': dRect, 'ctrlRect': ctrlRect, } return render(request, 'ctd.html', context) else: ... dRect = request.POST.get("dRect") ctrlRect = request.POST.get("ctrlRect") fc = request.POST.get("fc") UpdateData(fc, dRect, ctrlRect) img_out_path = executectd(..., fc, dRect, ctrlRect) context = { 'filename': img_out_path, } return render(request, 'result.html', context) else: ... (different forms) context = { 'f' = False ... } return render(request, 'ctd.html', context) Template {% if factors %} <br> <div class="card"> <div class="card-body p-5"> <div class="text-center mb-5"> <h2 class="h4 fw-bolder popup"> cf </h2> <h6 class="popup"> <img src="{% static 'assets/help.jfif' %}" onclick="showContextualHelp('cf')"> <span class="popuptext" id="cf"> Fill here the cf </span> </h6> <br> <div class="container"> <div class="row gx-5 justify-content-center"> <table> <thead> <tr> </tr> </thead> <tbody> {% for key, value_list in fc.items %} <tr> <th>{{ key }}</th> {% for value in value_list %} <td><input class="form-control" value="{{ value }}" {{ value }}></td> … -
Subscribe to google and outlook calendar through url causing problems
I'm working on a project using Django Rest Framework and icalendar. I've created an api which provides ics file for download. Users are provided with a url to the download api which they use to subscribe. However they are experiencing unexpected behaviour upon subscription. In case of google calendar it doesn't resync automatically at all. In one instance the calendar was subscribed successfully but there were no events being displayed on google calendar. Can anyone help confirm whether there is an issue with google calendar or am I missing something. for example not generating the file correctly views.py @action(detail=True, methods=['get'], permission_classes=[AllowAny], authentication_classes=[]) def download_file(self, request, *args, **kwargs): instance = self.get_object() ics_data = instance.ics_data file_name = "somefile" response = HttpResponse(ics_data.encode(), content_type='text/calendar') response['Content-Disposition'] = 'attachment; filename=%s.ics' % file_name return response sample url: https://api-mycompany.com/users/11184/calendar/download_file/ sample ics data: BEGIN:VCALENDAR VERSION:2.0 PRODID:-//my company calendar// BEGIN:VEVENT SUMMARY:This Event DTSTART;VALUE=DATE-TIME:20220321T054500Z DTEND;VALUE=DATE-TIME:20220321T070000Z DTSTAMP;VALUE=DATE-TIME:20220419T085236Z UID:113874 DESCRIPTION:Some Event LOCATION:My Studio END:VEVENT END:VCALENDAR -
"django_admin_log" violates foreign key constraint
We have an application that uses custom login Middleware. We authenticate users from the token. The problem is that when this user wants to change any entry in admin panel, it gives an IntegrityError. insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(567) is not present in table "auth_user". because this user is not in auth_user table, we set it to request.user only while authenticate with our external authentication system. how we can solve this issue? -
Optimal table design for ELO system
I'm trying to create elo system using django with postgresql. Below description is a system what I imagined. Elo table sorted by Date field. Table have two player's elo data field. When an new game created, calculated elo data will accumulated on table directly. This works when a game is newest. Elo Table Date | 2022-04-01 Player A | 1015.0 (Win) Player B | 985.0 Date | 2022-04-02 Player A | 1021.0 (Win) Player B | 979.0 <--------------------+ // new game created | // this data will be located at here ---+ Date | 2022-04-03 Player A | 1012.0 Player B | 988.0 (Win) However, when past game created, not familiar situation occured. First, calculate elo data with previous data for current game. Second, all elo data what following this game will be updated. Elo Table Date | 2022-04-01 Player A | 1015.0 (Win) Player B | 985.0 <-----------------------+ Date | 2022-04-03 | Player A | 1021.0 (Win) (this value will be | Player B | 979.0 re-calculated.) | | // past game created. | // this data will be located at here --------+ // all data after this will be updated. Date | 2022-04-02 Player A | 1002.0 Player … -
How to write custom authentication backend for one endpoint only (/metrics) in Django?
I have a custom middleware in Django to force all the requests to go through a login authentication (with few exceptions like api/token). This project allows users to authenticate either via a JWT token or a login in /admin/login and all unauthenticated users are redirected to /admin/login. for authentication. We deployed the project in Kubernetes and we want Prometheus to scrape /metrics endpoint but we don't want it to be exposed to unauthenticated users. Prometheus allows for authentication with username and password. The thing is that when a request is sent to /metrics, because of the middleware, the request is redirected to /admin/login. So I believe I need to write a custom authentication backend specifically designed for the metrics endpoint and place it before the other authentication methods. The request always goes through the middleware first so it will always be redirected to /admin/login and then will go through the authentication backend. What is the right way of doing this? middleware.py class LoginRequiredMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): assert hasattr(request, 'user') path = request.path_info.lstrip('/') if path == '' or path == '/': return self.get_response(request) url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if request.user.is_authenticated or url_is_exempt: # … -
Can post request to third party api using using requests library?
I am trying to post to some third party api with but I am getting this error. Why this occurs any suggestion ? I am using python2.7 and django 1.8 import requests requests.request("POST", api_endpoint, headers=headers, data=data) error: ConnectionError: HTTPSConnectionPool(host='..', port=443): Max retries exceeded with url: /api/v2/ (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fe72f81e390>: Failed to establish a new connection: [Errno 110] Connection timed out',)) -
How to pass all field names to when_any argument of django-lifecycle hook
I am using django-lifecycle to create a function in a model to be run when any input is changed. I'm doing this using the before_update hook, e.g. @hook("before_update", when_any=list_of_fields, has_changed=True) def do_something(self): do something here... I am trying to pass all of the field names to the when_any argument but struggling because the hook argument cannot use self to get this. For example doing: @hook("before_update", when_any=[f.name for f in self._meta.get_fields()], has_changed=True) def do_something(self): do something here... gives the NameError NameError: name 'self' is not defined. Is there a way to get all of the model field names in another way from within the model class? -
Django not rendering the images present in the 'images' folder inside the build folder after merging the react app
I have a React App with a Django rest framework backend. I ran the build command and merged the react app. The react app had an images folder inside the public folder that had some logos and photos that I used during the frontend development. Now after running the build and rendering the site from Django it is unable to render the images. The folder images is present inside the build folder that react gives. Below are my configurations and settings. template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'build'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] static and media files settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('account/', include("account.urls")), path('teacher/', include("teacher.urls")), path('search/', include("search.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # This is will cath the routes in the frontend and 404 errors urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] Please suggest to me what should I do -
DRF using prefetch_related
I have two classes Vessels and Components, each vessel has several components. I just want to fetch all vessels and all their related components in one query, I thought prefretch_related does that trick but in DRF in the api i am only receiving the vessels without their related components models.py class Vessel(models.Model): name = models.CharField(max_length=255, null=True, blank=True) imo = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name class Component(models.Model): vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') name = models.CharField(max_length=200, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) def __str__(self): return self.name serializers.py class VesselSerializer(serializers.ModelSerializer): class Meta: model = Vessel fields = '__all__' class ComponentSerializer(serializers.ModelSerializer): class Meta: model = Component fields = '__all__' the view : @api_view(['GET']) def getVessels(request): vessels = Vessel.objects.all().prefetch_related('vessel_components') vSerializer = VesselSerializer(vessels, many=True) return Response(vSerializer.data) the result i am getting : -
Problems with validators in django models
I want to create an edit page where the customer can edit the profile page. I have a problem with the validators and I don't know how to solve this. model.py class UserProfile(models.Model): CAT_G = ( ('W', 'W'), ('M', 'M'), ('do not want to mention', 'do not want to mention'), ) age = models.IntegerField(default=1, validators=[ MaxValueValidator(100), MinValueValidator(1)]) height = models.DecimalField(max_digits=3, validators=[MinValueValidator(Decimal('0.0'))], decimal_places=2) gender = models.CharField(max_length=27, blank=False, null= False, choices=CAT_G) view.py def edit_view(request): context={} if request.method == "POST": form = ProfileUpForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('/profPage') else: form = ProfileUpForm( initial={ "age":request.user.userprofile.age, "height":request.user.userprofile.height, "gender":request.user.userprofile.gender, } ) context['profE_form']= form return render(request, 'editPage.html', context) editPage.html {% for fieldProfile in profE_form %} <p> {{fieldProfile.label_tag}} {{fieldProfile}} </p> {% endfor %} The problem is that in the html page, the user can choose a negative number, even if I put that validators in my model. -
Imagefont truetype cannot open resource
Cannot open . ttf file from media folder But it's work Localserver But now the project hosting to pythonanywhere font = ImageFont.truetype("media/arial.ttf", size =16) I got a error this line so i try 3 ways to solve the problem This 3 ways font = ImageFont.truetype("arial.ttf", size =16) font = ImageFont.truetype("fullpath of the file/arial.ttf", size =16) font = ImageFont.truetype("settings.MEDIA_ROOT/arial.ttf", size =16) But it's work ImageFont.load_default() I want 3 different fonts arialbold, arialbt, arialblack, arial So it's work local machine If any package available to install the fonts Thanks to read the question 😊 -
Django query set to display particular field on webpage
I am trying to display the variants(field) that are related to the model RecordVariant on my webpage i have queryset on my view default how can i change my queryset or get queryset method to display variants that are related to particular record. class RecordVariant(models.Model): variants = models.ForeignKey(Variant_model, related_name = 'records', on_delete = models.CASCADE) class Variant(models.Model): name = models.CharField(max_length = 23, blank=True, null=True) class VariantListAPIView(RecordMixin, ListAPIView): lookup_url_kwarg = 'record_id' serializer_class = RecordVariantSerializer permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination filter_backends = (filters.OrderingFilter,) queryset = RecordVariant.objects.all() ordering = 'variants' ordering_param = 'ordering' ordering_fields = ( 'variants', ) def get_total_queryset(self): queryset = ( super() .get_queryset() .filter(record=self.record) ) -
display objects from inline model in DetailView
I have 2 models Product and Resource. Resource has to be a TabularInline model in my admin panel. I am struggling with filtering resource titles that are related only to this product. Since it is a ForeignKey I should use select_related but I am not sure how to use it in my case. For now, the loop in my HTML file gives me all sales files (from all products). models.py class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField('title', max_length=400, default='') slug = models.SlugField(unique=True, blank=True, max_length=600) class Resource(models.Model): id = models.AutoField(primary_key=True) type = models.CharField(max_length=32, choices=RESOURCE_TYPE, default='sales') title = models.CharField(max_length=400, blank=False, null=False, default='') related_files = models.FileField(upload_to='recources/', null=True, blank=True) publish = models.DateTimeField('Published on', default=timezone.now) resources = models.ForeignKey(Product, default='', on_delete=models.PROTECT, null=True, related_name='resources') admin.py class Resourceinline(admin.TabularInline): model = Resource class ProductAdmin(ImportExportModelAdmin): inlines = [ Resourceinline, ] resource_class = ProductResource admin.site.register(Product, ProductAdmin) views.py class ProductDetailView(DetailView): template_name = 'ProductDetailView.html' model = Product def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) resources_sales = Resource.objects.select_related('resources').filter(type='sales') # not sure what to put here context['resources_sales'] = resources_sales return context ProductDetailView.html {% for resource in resources_sales.all %} <p>{{resource.title}}</p> {% endfor %} Question Where am I making the mistake and how can I display resource objects that are related to type=sales and are related … -
How to update the value of a column in a foreign table in django
I have 2 tables, one of the tables is a foreign table to the other (foreign key). I want to decrease the value of the quantity column of items in the foreign table based on value of the quantity column of the parent table. Below is my code model.py from django.db import models # Create your models here. PAYMENT_METHOD = ( ('CASH', 'cash'), ('TRANSFER', 'transfer'), ) class ItemSold(models.Model): item_name = models.CharField(max_length=80) quantity = models.IntegerField() def __str__(self): return self.item_name class DailySales(models.Model): customername = models.CharField(max_length=100) itemsold = models.ForeignKey(ItemSold, related_name="soldItem", on_delete=models.CASCADE) quantity = models.IntegerField() rate = models.IntegerField() totalprice = models.IntegerField(default=0) datesold = models.DateTimeField(auto_now_add=True, auto_now=False) paymentmethod = models.CharField(max_length=40, choices=PAYMENT_METHOD, default=PAYMENT_METHOD[0][0]) havepaid = models.BooleanField(default=False) datepaid = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: verbose_name_plural = 'Daily Sales' def __str__(self): return self.customername def save(self, *args, **kwargs): self.totalprice = self.rate * self.quantity super(DailySales, self).save(*args, **kwargs) views.py class DailySalesListView(generics.GenericAPIView): serializer_class = DailySalesSerializer queryset = DailySales.objects.all() name = 'Daily Sales List' filter_backends = (DjangoFilterBackend,) filterset_fields = ('customername','havepaid', 'datesold', 'itemsold', 'datepaid') def get(self, request): sales = self.filter_queryset(self.get_queryset()) serializer = self.serializer_class(instance=sales, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) def post(self, request): data = request.data serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) I haven't tried anything yet, I don't know how to go … -
How to install a library and execute the code with a POST request? [Django]
I am trying to execute the python code which I am taking as user input and returning the output of the code but I want to use a library to find the time complexity of the program but it obviously gives module not found error when I try to execute the code with library in it. Here is my frontend which I created using react. Python code is running perfectly when I do not introduce any libraries. What I am doing is I am sending the code to django through REST Api and executing the code writing the output in a file and returning the output as shown below - My viewsets.py file - from rest_framework.viewsets import ModelViewSet from .models import Code from .serializers import CodeSerializer from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT import sys class CodeViewSet(ModelViewSet): queryset = Code.objects.all() serializer_class = CodeSerializer lookup_field = "id" @action(detail=True, methods=["HEAD", "GET", "POST"], url_path="runcode") def runcode(self, request, id=None): if request.method in ("GET", "HEAD"): return Response(status=HTTP_204_NO_CONTENT) else: code_data = self.get_object() try: orig_stdout = sys.stdout sys.stdout = open('file.txt', 'w') exec(code_data.code) sys.stdout.close() sys.stdout = orig_stdout output = open('file.txt', 'r').read() except Exception as e: sys.stdout.close() sys.stdout = orig_stdout output = e …