Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
type and select multiple items
models.py: class Category(models.Model): slug = models.CharField(max_length=300) def __str__(self): return self.slug class News(models.Model): category = models.ManyToManyField(Category, default='cryptocurrency',related_name='category') forms.py: class NewsForm(forms.ModelForm): class Meta: model = News fields = ('title', 'header_image', 'body', 'category') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control'}), 'body' : forms.Textarea(attrs={'class':'form-control'}), 'category' : forms.SelectMultiple(attrs={'class':'form-control'}), } from django.contrib import admin from .models import News,Category from easy_select2 import select2_modelform class NewsAdmin(admin.ModelAdmin): form = select2_modelform(News, attrs={'width':'250px'}) admin.site.register(News, NewsAdmin) admin.site.register(Category) There are many cases and it is very difficult to find a specific case among all these cases. I wanted to know how to make the desired field so that it can be typed and selected like the following: In the admin panel, like the image above. I want it to be the same in the template, but it is displayed as follows: -
External url in Django template
I got receipt url from stripe like: "receipt_url": "https://pay.stripe.com/receipts/acct_1FpzDdEHHOJvKiFZ/ch_1IsB5REHHOJvKiFZGxagDBoQ/rcpt_JVBS4giqfp3YUoHcqzjQAwMHWq",. I added to template as: <div class="status-message">{{ transID.receipt_email }}<br/><a href="{{ transID.receipt_url }}" target="_blank">Find your Receipt here:</a></div> When i click on the link i'm redirected to the same page. view storing fields from stripe: transID = stripe.PaymentIntent.retrieve(session.payment_intent) context = { 'customer': customer, 'transID': transID, } Is there a way when clicking on the link to redirected to the stripe's receipt_url? Many thanks. -
How to start Zendesk chat after receiving a coin base webhook?
I hope you all are well. Currently, I'm working on a website where I'm selling game items like gold and characters. I'm receiving payment through Coinbase. I want to send a message in Zendesk chatbox from the user who paid, after successful payment on Coinbase. Tech I'm using Django for backend HTML, CSS and JS for front-end Things I've done so far I've managed to receive money in my Coinbase account and Coinbase redirects to my website after successful payment. I'm doing all this by the following code. def buy_osrs(request): obj = Setting.objects.first() osrs_price = getattr(obj, "osrs_price") osrs_fee = getattr(obj, "osrs_fee") form = OSRSForm() site = get_current_site(request).domain payment_success = f"https://{site}/payment/" if request.method == "POST": form = OSRSForm(request.POST) if form.is_valid(): form.save() total = float(form.cleaned_data.get("osrs_numbers")) * osrs_price + osrs_fee charge_info = { "name": "My Website", "description": "My Website Description", "local_price": {"amount": total, "currency": "USD"}, "pricing_type": "fixed_price", "metadata": {"rsn": form.cleaned_data.get("rsn"), "email": form.cleaned_data.get("email")}, "redirect_url": payment_success, } charge = client.charge.create(**charge_info) return redirect(charge.get("hosted_url")) context = { "form": form, "osrs_price": osrs_price, "osrs_fee": osrs_fee, } return render(request, "main/buy_osrs.html", context) I've managed to set up and receive webhooks, which change my database according to the response it gets from Coinbase. @csrf_exempt def coinbase_webhook(request): if request.method == "POST": # event … -
Django form two input box went into one but it should be separate due to option value box
You can see pictures of that purpose and term label there is a missing purpose input box and it got a term input box. I want to have a purpose input box appear. The option value should show a list of options pick from model.py before I add loan_purpose with list of option the input box was there till I added loan_purpose update with makemigrations then it missing inputbox. model.py from django.db import models from django.contrib.auth.models import User Loan_Purpose = ( ("car","Car"), ("home","Home Renovation"), ("travel","Travel"), ("wedding","Wedding"), ("education","Education"), ("boat","Boat"), ("medical","Medical"), ("business","Business"), ("other","Other"), ) class Loan(models.Model): id = models.AutoField(primary_key=True) purpose = models.CharField(choices=Loan_Purpose, max_length=30) term = models.DecimalField(max_digits=5, decimal_places=2) amount = models.DecimalField(max_digits=10, decimal_places=2) interest = models.DecimalField(max_digits=5, decimal_places=2) class Meta: db_table = 'loan' create.html <body> <div class="main_content"> <div class="info"> {% if submitted %} <p class="success"> Your venue was submitted successfully. Thank you. 11 </p> 12 {% else %} <form method="POST" class="post-form" action="{% url "loan" %}"> {% csrf_token %} {{ form.as_table }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> </div> </body> {% endif %} {% endblock %} </body> view.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import LoanForm from .models import Loan def home(response): return render(response, "lend/home.html", {}) def loan(request): submitted … -
403 Permission 'aiplatform.endpoints.predict' denied on resource '//aiplatform.googleapis.com/projects/... (or it may not exist)
I am getting below when executed predict on endpoint: 403 Permission 'aiplatform.endpoints.predict' denied on resource '//aiplatform.googleapis.com/projects/23377928208/locations/us-central1/endpoints/7952107896727142400' (or it may not exist). Please let me know the resolution. Regards, Amar -
How to check if a requested user has a specific custom permission in Django Rest Framework?
I want to check with a boolean answer of True/False if a requested user has a permission defined in permissions.py. More in particular, I want to check if the requested user has the permission of IsDriver. Is somehow possible? class ExampleViewSet(viewsets.ModelViewSet): permission_classes = [IsChargingStationOwner |IsDriver | IsReadOnlyStations] serializer_class = ExampleSerializer def get_queryset(self): # get the request user requested_user = self.request.user if requested_user.is_anonymous : print('1') elif requested_user .... : print('2') My question has to do with the elif statement. -
Shadows built-in name 'format' in class-based-views, Django rest_framework
I am getting the error Shadows built-in name 'format' in my def post is there a reason for this to happen because I am using the free Pycharm and not professional? from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response Create your views here. class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) -
Setup Django With Apache+Supervisor
I have always worked with C panel setup Django app but now i have purchased one code and the developer of that code is saying you cant do that normally . I have used many features in that such as Django celery and channels.So, it will be done with Apache+supervisor only. So can i get any docs or terminal commands that i will have to use to get it working on my server.I also want to setup many domains using that code so can i get any bash code available that will do it automatically. -
How to Use Dynamic variable for Django forms textinput value?
I am working on project1 cs50w wiki, I have created a form in forms.py. it is textinput and I am trying to pass dynamic value for thistext input "{{ pagetitle }}". but it prints "{{ pagetitle }}" as it is in the textinput when rendered. this all works if I am using HTML forms but when I try Django forms I can not figure out how to pass variable to the display. forms.py from django import forms class newTitle(forms.Form): q = forms.CharField(label='New Page Title', max_length=100, widget=forms.TextInput( attrs={ 'id': 'titleCheck', 'class': 'search', 'type': 'text', 'placeholder': 'Type Topic Title Here...', 'onblur': 'blurFunction()', 'value': '{{ pagetitle }}' })) views.py def new_topic(request): newTitle_form = newTitle() context = { "newTitle_form": newTitle_form, } return render(request, "encyclopedia/CreateNewPage2.html", context) def new_topic_t(request, entry): newTitle_form = newTitle() return render(request, "encyclopedia/CreateNewPage2.html", { "newTitle_form": newTitle_form, "pagetitle": entry.capitalize() }) def myCheckFunction(request): searchPage = request.GET.get('q','') if(util.get_entry(searchPage) is not None): messages.info(request, 'The Page '+ searchPage + ' Already Exists, Do You Want To Change It Or Edit It!') return HttpResponseRedirect(reverse("new_topic_t", kwargs={'entry': searchPage})) else: return HttpResponseRedirect(reverse("new_topic_t", kwargs={'entry': searchPage})) createNewPage2.html {% csrf_token %} <div class="form-group" style="margin-right: 20%"> <form id="newTitle" action="{% url 'check' %}" method="GET"> {% block newTitle %} {{ newTitle_form }} {% endblock %} </form> </div> <script> … -
django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured
I am facing problem testing my User model Which is defined as AUTH_USER_MODEL = "accounts.User" and the accounts.models that is the code import os from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UnicodeUsernameValidator from django.core.validators import MinLengthValidator from django.db import models from django.utils.translation import gettext_lazy as _ class Avatar(models.Model): photo = models.ImageField(upload_to="avatars") def __str__(self): return os.path.basename(self.photo.name) class User(AbstractUser): username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[UnicodeUsernameValidator(), MinLengthValidator(3)], error_messages={"unique": _("A user with that username already exists."),}, ) avatar = models.ForeignKey( "Avatar", null=True, blank=True, on_delete=models.PROTECT ) is_guest = models.BooleanField(default=False) class Meta: ordering = ["-id"] When I am testing this in test_models.py using $ python -m pytest with following code in the file from django.conf import settings def test_custom_user_model(): assert settings.AUTH_USER_MODEL == "accounts.User" These are the errors on terminal $ python -m pytest ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.1, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 rootdir: C:\ProjectCode\Main-Project\Django-REST-Framework-React-BoilerPlate plugins: cov-2.11.1, django-4.2.0 collected 1 item accounts\tests\test_models.py F [100%] =============================================================================== FAILURES =============================================================================== ________________________________________________________________________ test_custom_user_model ________________________________________________________________________ def test_custom_user_model(): > assert settings.AUTH_USER_MODEL == "accounts.User" accounts\tests\test_models.py:5: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How do I use Geolocation in python
I first started using geopy but it seems that the location is not precise. So I encountered this API https://w3c.github.io/geolocation-api/#example-1-a-one-shot-position-request but problem is that it works only with javascript, and I am working on Django Project. I tried using Beautiful soup to load javascript web page with this content but its not loading <!DOCTYPE html> <html> <body> <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Try It</button> <p id="demo"></p> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); //console.log(navigator.geolocation.getCurrentPosition) } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { //console.log(position) x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script> </body> </html> I tried using js2py but that too isn't supporting I just need to have precise current position in longitude and latitude of the device and use it in my django project. Anyone please help. -
How to store HTML content in databse in Django [closed]
I'm using DJango to save some html designs in my db. For example But I'm not able to use it like a html content Here is my Model file Model.py -
Override save model Django save method with return
I have this function, I want to make it a method of a Message model class. def save_message_to_db(message, message_id): mex = Message( message_id=message_id, subject=message.subject, sender=message.sender.address, has_attachments=message.has_attachments, sent_date=message.sent, received_date=message.received ) mex.save() return mex I've tried various ways, but still get errors. I need to return, expecially the id of the object saved. -
How to connect RabbitMQ into a Django project without Celery?
What do I need to setup in the Django Project to connect RabbitMQ with my application? I don't want to use celery. I will work with the pika library. -
Django App running until login attempt 'Truncated or oversized response headers received from daemon process'
Just promoted my django app to test env from dev. On this host there is php app which is also served by apache. We had to create Virtual Host config for both apps. Both apps are up and reachable. But I have problem with my django app. I reach the login/start/index page in browser, but after login attempt i get **500 Internal Server Error** In httpd logs i can see: [Tue May 18 09:41:21.366459 2021] [wsgi:error] [pid 94832] [client 10.111.12.135:56920] Truncated or oversized response headers received from daemon process 'xxxxx.srv.pl.net': /opt/xip/itP/api/api/wsgi.py, referer: https://xxxxx.srv.pl.net:8443/accounts/login/ wsgi.py: #!/opt/xip/itP/venv/bin/python import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cftapi.settings') sys.path.append('/opt/xip/itP/api/') application = get_wsgi_application() ssl.conf: LoadModule wsgi_module /etc/httpd/modules/mod_wsgi.so WSGIPythonHome /opt/xip/itPassed/venv WSGIApplicationGroup %{GLOBAL} <VirtualHost 10.111.21.5:8443> ServerAdmin xxxxx.@net.com DocumentRoot "/opt/xip/itP/api" #Alias /itP "/opt/xip/itP/api" ServerName xxxxx.srv.pl.net:8443 WSGIScriptAlias / /opt/xip/itP/api/api/wsgi.py WSGIDaemonProcess xxxxx.srv.pl.net python-home=/opt/xip/itP/venv python-path=/opt/xip/itP/api header-buffer-size=80000 WSGIProcessGroup xxxxx.srv.pl.net Alias /static/ /opt/xip/itP/api/static/ <Directory /opt/xip/itP/api/static> Require all granted </Directory> <Directory /opt/xip/itP/api/api> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /opt/xip/itP/api/*/> Require all granted </Directory> ErrorLog logs/ssl_error_log TransferLog logs/ssl_access_log LogLevel warn any ideas? App works until i try to login. all WSGIApplicationGroup %{GLOBAL} and header-buffer-size didn't work for me. -
How to implement several widgets to one field (Django)?
I was wondering is there any way i can use several widgets in one form field? I wanna use forms.TextInput(attrs={'class': 'form-control'} and forms.PasswordInput in one field. I've been reading about multiwidgets but I am quite new to django and I am not sure I can comprehend it yet. So are there maybe easier ways to implement 2 widgets at once? Thank you in advance! -
Displaying data from database vs displaying json data from end point in django
I'm familiar with django, now I'm learning django rest framework. Django framework converts database object to Json object. So the json datas can we easily used by the trusted website(CORS).Now my doubt is, I have viewed some tutorial about django rest framework, in that tutorials they are using their own serialized json data and displaying it in browser using react framework...so what is the difference between display data from end point vs displaying directly it from database and rendering it in html in own project -
Elasticsearch Mapping for array
I have the following document for which I need to do mapping for elasticsearch "table_1": { "title": "Spine Imaging Guidelines", "rows": [ "Procedure Codes Associated with Spine Imaging \n3", "SP-1: General Guidelines \n5", "SP-2: Imaging Techniques \n15", "SP-3: Neck (Cervical Spine) Pain Without/With Neurological \nFeatures (Including Stenosis) and Trauma \n24", "SP-4: Upper Back (Thoracic Spine) Pain Without/With Neurological \nFeatures (Including Stenosis) and Trauma \n28", "SP-5: Low Back (Lumbar Spine) Pain/Coccydynia without \nNeurological Features \n31", "SP-6: Lower Extremity Pain with Neurological Features \n(Radiculopathy, Radiculitis, or Plexopathy and Neuropathy) With or \nWithout Low Back (Lumbar Spine) Pain \n35", "SP-7: Myelopathy \n39", "SP-8: Lumbar Spine Spondylolysis/Spondylolisthesis \n42", "SP-9: Lumbar Spinal Stenosis \n45", "SP-10: Sacro-Iliac (SI) Joint Pain, Inflammatory \nSpondylitis/Sacroiliitis and Fibromyalgia \n47", "SP-11: Pathological Spinal Compression Fractures \n50", "SP-12: Spinal Pain in Cancer Patients \n52", "SP-13: Spinal Canal/Cord Disorders (e.g. Syringomyelia) \n53", "SP-14: Spinal Deformities (e.g. Scoliosis/Kyphosis) \n55", "SP-15: Post-Operative Spinal Disorders \n58", "SP-16: Other Imaging Studies and Procedures Related to the Spine \nImaging Guidelines \n61", "SP-17: Nuclear Medicine \n65" ], "meta": { "page_no": 2, "page_text": "Spine Imaging \nGuidelines\n Procedure Codes Associated with Spine Imaging\n 3 SP-1: General Guidelines\n 5 SP-2: Imaging Techniques\n 15 SP-3: Neck (Cervical Spine) Pain Without/With Neurological \nFeatures (Including … -
When I'm running the server in VScode it is showing this error
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'C:\Users\abcd\Desktop\PythonDjango\mysite\polls\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to create a virtualenv with fish shell on Mac OS?
I am trying to create a virtual environment for a django project. I already installed it with pip3. When I try to create the environment through : ❰C❙~/meltingpot(git:main)❱✔≻ virtualevn meltingpot I get this error fish: Unknown command virtualevn Can somebody please show me how can I create virtualenv successfully -
inheritance another class attributes in model class
While creating database, we have to write some attributes in every tables like (status, registerd_by, registered_dt). So is there any way in django that I create a separete class for these fields and inherit this class in another classes. For example, Creating a common class, class Common(models.Model): registerd_by = models.CharField(max_length = 10) status = models.CharField(max_length = 1) registered_dt = models.CharField(max_length = 10) class Users(models.Model): username = models.CharField(max_length = 10) password = models.CharField(max_length = 10) name = models.CharField(max_length = 200) class Patients(models.Model): name = models.CharField(max_length = 200) age = models.CharField(max_length = 3) gender = models.CharField(max_length = 1) dob = models.CharField(max_length = 10) How to inherit the Common class in these two classes such that the attributes of the Common classes will also become member of these two classes. In this way, I don't have to write the repeating fields in all my classes. -
how to acces key of dictionaries where keys are dyanamic
print(mydict.keys()) dict_keys(['style', '7 colors', '3 sizes']) dict_keys(['style', '6 colors', '4 sizes']) dict_keys(['style', '2 colors', '2 sizes']) needed o/p: I want to acces key '7 colors' and '3 sizes' like print(mydict['7 colors']) but for every loop 7,6,2 may changes,its dynamic so. how to acces thses key values. any one please help me. thanks in advance. -
Hi everyone!! Please help me. I wanna write code in Python using Django library
I have a model with boolean fields(service_1, service2..servicen) and decimal fields(price_1,price_2.. price_n) and also total_price, all of this in same model. I want if user click service_1 and it became True, price_1 append in to total price, if service is empty price didnt append in total price.Please advice me best way how i can do it. p/s sorry for my English, i didnt practice a lot.enter image description here -
How do i get the auto increment from my primary key to my foreign key the moment i create a new question
I have two tables called questions and modelanswer class Questions(models.Model): question_id = models.AutoField(primary_key=True) question = models.TextField() class Meta: db_table = "QUESTIONS" class Answer(models.Model): question_id = models.ForeignKey( Questions, on_delete=models.CASCADE, db_column="question_id" ) answer_id= models.AutoField(primary_key=True) model_ans = models.TextField() class Meta: db_table = 'MODEL' @require_http_methods(["POST"]) @login_required def create_question(request): req = json.loads(request.body) question = req["question"] answer = req["answer"] models.Questions.objects.get_or_create( question=question, ) for answers in answer: models.Answer.objects.create( #question_id=(the auto increment of the new question id from question table after question is created) question_id=models.Questions.objects.get(pk=question_no) model_ans=guided_answers["model_ans"], ) return success({"res": True}) A new question id will be incremented after a new question is created, and what i would like to do is get the new question_id that was just created and pass it to the foreign key in my answers table,however i do not know how to do it, i tried using the question_id=models.Questions.objects.get(pk=question_no) to get it but it gives me a keyerror,is there another way to do it? -
Handling a success and failure response Django
user is sending an api request to crate order along with information in request body and after saving the data i am returning the order_id and access_token to the user.I have used few authentications also with using model.full_clean().Now i am stuck on the part to return success and failure status code and message along with the order_id and access_token. @api_view(['POST']) def orderdetails(request): try: ACCESS_KEY_ID = request.META.get('HTTP_ACCESS_KEY_ID') ACCESS_KEY_SECRET = request.META.get('HTTP_ACCESS_KEY_SECRET') applications = Applications.objects.all() id=0 for e in applications: if(e.ACCESS_KEY_ID==ACCESS_KEY_ID and e.ACCESS_KEY_SECRET==ACCESS_KEY_SECRET ): id = e.id+id print(id) break else: return Response({"Message":"Enter Valid Credentials"}) except ValueError: return Response({"ACCESS":"DENIED"}) if request.method == 'POST': data=request.data print(data) orders = Orders(applications=Applications.objects.get(id=id), purpose_code = data['purpose_code'], amount=data['amount'], currency=data['currency'], note=data['note'], payer_name=data['payer_name'], payer_email=data['payer_email'], payer_phone_country_code=data['payer_phone_country_code'], payer_phone_number=data['payer_phone_number'], payee_name=data['payee_name'], payee_email=data['payee_email'], payee_phone_country_code=data['payee_phone_country_code'], payee_phone_number=data['payee_phone_number'], payee_pan = data['payee_pan'], payee_bank_account_holder_name=data['payee_bank_account_holder_name'], payee_bank_account_number=data['payee_bank_account_number'], payee_bank_account_ifsc=data['payee_bank_account_ifsc'], payee_bank_account_type=data['payee_bank_account_type'], payee_bank_account_beneficiary_identifier=data['payee_bank_account_beneficiary_identifier'], payment_collection_webhook_url=data['payment_collection_webhook_url'], payment_transfer_webhook_url=data['payment_transfer_webhook_url'], payment_gateway_code = data['payment_gateway_code'], isActive=data['isActive'] ) try: orders.full_clean() except ValidationError: return Response({"Error message":"invalid request body"}) else: orders.save() serializer = OrderSerializer(orders) order_id = serializer.data['id'] access_token = serializer.data['access_token'] return Response({"orderId":order_id,"accessToken":access_token}) required Success and failure response in the format bellow : Success response (201/202) along with order_id and access_token Failure response (422) along with message: "error message content"