EncodeError at (POST Method ) in django python. Post respose 500 - python

I have my python class below. My question is what this error actually means EncodeError at /api/v1/jobs/apply/
> is not JSON serializable. What is it trying to point based on my code below ? can anyone give an idea? . The new_email is at below also.
def new_application(self, data):
try:
def new_application(self, data):
try:
html = render_to_string("email_templates/new_application.tpl",data)
name = "testt"
data["subject"] = "test"
if env == "localhost":
msg = EmailMessage(data["subject"], html, name, dev_emails)
msg.content_subtype = "html" # Main content is now text/html
msg.attach_file(data["resume"])
msg.send()
else:
msg = EmailMessage(data["subject"], html, name, [data["company_email"]])
msg.content_subtype = "html" # Main content is now text/html
msg.attach_file(data["resume"])
msg.send()
except Exception as e:
print(str(e))
error
EncodeError at /api/v1/jobs/apply/
<bound method Email.new_application of <v1.lib.emails.Email object at 0x7f6cbe44e908>> is not JSON serializable
Code
class ApplyJob(APIView):
def email(self, data):
email_ins = Email()
c_task.delay(email_ins.new_application, data)
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,IsApplicant)
def post(self, request, format=None):
data = request.data
job_applicant_ser = JobApplicantSerializer(data=data)
applicant = get_applicant_ins(request)
if applicant.profile_completeness <= 60:
return Response("You have not complete filling up your profile yet. Please complete it atleast 80% and above percentage..", status=status.HTTP_400_BAD_REQUEST)
if not applicant.resume:
return Response("Sorry, Please upload your resume.", status=status.HTTP_400_BAD_REQUEST)
job = data.get("job" , None)
cover_letter = data.get("cover_letter", None)
if not cover_letter or cover_letter == "":
return Response("Sorry, please fill your cover letter.", status=status.HTTP_400_BAD_REQUEST)
apply_job_checker_ins = JobApplicant.objects.filter(job=job,applicant=applicant).count()
if apply_job_checker_ins > 0:
return Response("Sorry but you cant apply to this company, it appears that you have already applied.", status=status.HTTP_400_BAD_REQUEST)
if job:
job = JobModel.objects.get(pk=job)
else:
return Response("Sorry but there is a problem with the application, please refresh page.", status=status.HTTP_400_BAD_REQUEST)
if job_applicant_ser.is_valid(raise_exception=True):
job_applicants = job_applicant_ser.save(applicant=applicant,job=job)
data = {}
data["job"] = job_applicants.job.title
data["account_url"] = APP_URL+"/account/job_applicants"
data["email"] = job_applicants.job.company.user.email
data["resume"] = STATIC_ROOT+"/uploads/resume/"+str(job_applicants.applicant.resume)
data["company_email"] = job_applicants.job.company.user.email
self.email(data)
return Response("You have applied to the jo
b. Please make sure your line is always open.", status=status.HTTP_200_OK)

Related

My function call the return before the rest of the code

So I am trying to loop through the list of classes see if there is a match or not
if there is a match return a Response and say there is a match
otherwise register the student
I am using django and django-restframework
Here is my code
#api_view(['POST'])
#permission_classes([IsAuthenticated,])
def createOrderForOnlineClasses(request):
user = request.user
data = request.data
Class = OnlineClass.objects.get(id= data["classId"])
orderCred = {
'pin' : 'SOME_PIN',
'amount' : int(Class.totalPrice),
'callback' : 'http://localhost:3000/verify/',
}
for i in user.userprofile.onlineClass.all():
if i.id == Class.id:
return Response({"details": "Already registered"}, status=status.HTTP_400_BAD_REQUEST)
try:
response = requests.post("https://panel.aqayepardakht.ir/api/create", data=orderCred)
if response.status_code == 200 and not response.text.replace('-',"").isdigit():
# url ='https://panel.aqayepardakht.ir/startpay/'+response.text
registeredClass = RegisterStudentForOnlineClass.objects.create(
user=user,
totalPrice = int(Class.totalPrice),
transId = response.text,
onlineClassName= Class
)
serializer = RegisterForClassSerializer(registeredClass , many=False)
print(serializer.data)
return Response(serializer.data)
else:
return Response({"details": "Error"} , status= status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({"details": f"{e}"})
return Response({"details":f"{Class}"}, status=status.HTTP_400_BAD_REQUEST)
So the problem is the function call the
return Response({"details":f"{Class}"}, status=status.HTTP_400_BAD_REQUEST)
first and the rest wont work
Thank you :)
So I Have found the answer the thing is all you have to do is first check if the
len(user.userporfile.onlineClass.all()) == 0
If it is do the rest
else run the for loop

'dict' object has no attribute '_committed' can anyone explain why this error occurs

I am sending files from the frontend and I want to save file location in database I am using DRF.
Currently, I am trying to save only one file but i am getting error
"'dict' object has no attribute '_committed'"
Can Anyone please give me some suggestions on what should I do?
Request Body I am getting for on file:-
{'id': "Please provide Site Contact person's Name", 'service': {'id': 3, 'service_name': 'Site
Survey', 'cost_per_kw': 1, 'min_size': 101, 'upto_size': 10000, 'tat': 5, 'creation_date':
None}, 'question': 3, 'creation_date': None, 'real_estate': 0, 'answer': 'VIkrant Patil',
'attachement': [{'name': 'Vikrant Patil - Offer Letter (1).pdf', 'size': 172518, 'url':
'blob:http://localhost:8000/cad9de5d-a12b-41a2-90f7-38deff67fd0f', '_file': {}}], 'project':
189}
My view.py logic for saving only one file:-
class ServiceProjectAnswerViewSet(viewsets.ModelViewSet):
model = ServiceProjectAnswer
serializer_class = ServiceProjectAnswerSerializer
# parser_classes = (MultiPartParser, FormParser)
def create(self, request, *args, **kwargs):
print(request.data)
instance = None
answers = request.data.copy()
data = {}
attachements = answers['attachement']
print(attachements[0])
data['answer'] = answers['answer']
data['project'] = answers['project']
data['question'] = answers['question']
serializer = self.get_serializer(data=data)
if serializer.is_valid(raise_exception=True):
try:
instance = serializer.save()
# for attachement in attachements:
AnswerAttachments.objects.create(
answer = instance,
# attachement = attachement
attachement = attachements[0]
)
except Exception as e:
print(e)
return Response(str(e), status=400)
return Response(serializer.data, status=201)
My view.py logic for saving only multiple files :-
In my responce when I a sending multiple files I am sending list of Objects every object has values which i want that is why I have use for loop to iterate.
def create(self, request, *args, **kwargs):
instance = None
print(request.data)
answers = request.data.copy()
for answer in answers:
data = {}
attachements = answer['attachement']
print(attachements,"attachement")
data['answer'] = answer['answer']
data['project'] = answer['project']
data['question'] = answer['question']
print(data,"data")
serializer = self.get_serializer(data=data)
if serializer.is_valid(raise_exception=True):
try:
instance=serializer.save()
for attachement in attachements:
print(attachement)
# attach = {}
# attach['name'] = attachement['name']
# attach['size'] = attachement['size']
# attach['url'] = attachement['url']
print(type(attachement))
AnswerAttachments.objects.create(
answer=instance,
attachement=attachement
)
except Exception as e:
print(e)
return Response(str(e), status=400)
else:
return Response({'message': ('Failed to save answers')}, status=400)
return Response('Answers are saved successfully!!', status=200)
Try something like this,
const formData = new FormData();
formData.append('file', file);
const requestOptions = {
method: "POST",
body:formData
};
Means,try to send body of request in multiform instead of application/json.

How do I structure my view for sending an api get request in Django?

I am sending a get request in my view and then using the response to fill my database and I need some confirmation on the following:
should i make an api call inside of a view?
what should that view response be?
if i have done it wrong then what would be the right way to send get requests in Django?
my_app/views.py
class api(APIView):
template_name = 'payment/api.html'
def get(self, request):
#I SEND THE GET REQUEST HERE
config = configparser.ConfigParser()
config.read('config.ini')
r = requests.get(config['DEFAULT']['api'])
response = r.json()
#HERE I FILTER THE RESPONSE AND PUT IN A DB
for item in response:
if 'Covered Recipient Physician' in item.values():
person, _ = models.Person.objects.get_or_create(
profile_id = int(item['physician_profile_id']),
first_name = item['physician_first_name'].lower(),
last_name = item['physician_last_name'].lower()
)
address, _ = models.Address.objects.get_or_create(
business_street =
item['recipient_primary_business_street_address_line1'].lower(),
city = item['recipient_city'].lower(),
state = item['recipient_state'].lower(),
country = item['recipient_country'].lower()
)
business, _ = models.Business.objects.get_or_create(
business = item['submitting_applicable_manufacturer_or_applicable_gpo_name'].lower(),
)
business_address_link = models.Business_address_link.objects.create(
business = business,
address = address
)
business_address_link.save()
payment = models.Payment.objects.create(
record_id = int(item['record_id']),
amount = float(item['total_amount_of_payment_usdollars']),
date = item['date_of_payment'],
number_of_payments = int(item['number_of_payments_included_in_total_amount']),
payment_form = item['form_of_payment_or_transfer_of_value'],
nature_of_payment = item['nature_of_payment_or_transfer_of_value']
)
payment.save()
person_payment_information = models.Person_payment_information.objects.create(
person = person,
business_address_link = business_address_link,
payment = payment
)
person_payment_information.save()
Try to use this function for GET request -
#require_http_methods(['GET'])
def get_persons(request):
try:
data = list(Message.objects.all.values())
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})
Once you get the response and send it to template.html, you can display it in any way you want.
If you want to add information to the DB you better use POST request, for example -
#require_http_methods(['POST'])
def add_person(request):
try:
data = json.loads(request.body)
new_person = Person(**data)
new_person.save()
return render(request=request, template_name='template.html', context={"data": data})
except Exception as e:
return render(request=request, template_name='template.html', context={"error": e})

Display a confirmation message on template from backend(python/Django)

Hi I have JSONResponseMixin View, the main function of this view is to change the status to confirmed once the user click confirms in the GUI. I want to display a pop-up stating that it's confirmed. How can I do that from the django views.py?
The following is my view
class ConfirmView(JSONResponseMixin, View):
def post(self, request, *args, **kwargs):
status = 'error'
msg = "this is from me"
post_body = json.loads(self.request.body)
fab_value = post_body['fab']
mast_value = post_body['mast']
comment = post_body.get('comment')
try:
object = Forecast.objects.get(fab=fab_value, mast=mast_value, type='XC')
except ObjectDoesNotExist:
object = []
else:
if object.status == 'notified(created)' or 'notified(updated)':
object.status = 'confirmed'
object.comment = second_po_comment
object.confirm = self.request.user
object.modified_by =User.objects.get(username=self.request.user.username)
object.save()
return self.render_json_response(dict(status=status, msg=msg))

HTTP POST with XML data does not work in Django-Piston

I have implemented API with django piston in which its take data from sms/mms . For MMS case i have to post XML data with image and others . Here is my code snippet on handlers.py
def create(self, request,*args,**kwagrs):
try:
file_type = None
raw_data = request.raw_post_data
data = serializers.deserialize("xml", raw_data)
try:
parser = Parse(data.stream.getvalue())
message = parser.get_message()
action_id = parser.get_action_id()
except Exception,e:
return HttpResponse(Response({'sender':parser.get_sender(),'error_description':str(e)}).get_error_response(), mimetype='text/xml')
if action_id in ['o','m','vt','vh','yritys']:
return self.post_message(request,parser)
elif action_id == 'poista' or action_id == 'lopeta':
return self.expired_message(request,parser)
elif action_id == 'tiedot':
return self.get_contact_info(request,parser)
except Exception,e:
ad_id = None
return HttpResponse(Response({'sender':parser.get_sender(),'error_description':str(e)}).get_error_response(), mimetype='text/xml')
when I am posting xml data with CURL its working , but when i use Firefox, httprequester its throwing me "BAD REQUEST"
Check this:
I get a 400 Bad Request error while using django-piston
Create middleware as:
class ContentTypeMiddleware(object):
def process_request(self, request):
if 'charset=UTF-8' in request.META['CONTENT_TYPE']:
request.META['CONTENT_TYPE'] = request.META['CONTENT_TYPE'].replace('; charset=UTF-8','')
return None
Add it in settings:
MIDDLEWARE_CLASSES = (
'app.middleware.ContentTypeMiddleware',
)
Try hurl.it for API testing. Check your post data. Set your header info if required.

Categories

Resources