whenever i run the server at localhost i got this error
cant figure out what the issue is
here is the code of the request
#api_view(['GET','POST'])
def ProductView(request,id):
# status = get_object_or_404(id=request.POST.get('id', ''))
stat = get_object_or_404(Product,id=id)
serializer =ProductSerializer
# serializer = serializers.statusSerializer(stat,many=True)
nice=stat.name
# nice = str(stat.total)
print(nice)
# return Response(json.loads(reade r(nice)))
return Response(json.loads(nice))
this the error
JSONDecodeError at /pro/product/5/
Expecting value: line 1 column 1 (char 0)
As you are using DRF, then you can take the advantage of using its own seralization. So you can try like this:
#api_view(['GET','POST'])
def ProductView(request,id):
if request.method == "GET":
stat = get_object_or_404(Product,id=id)
serializer = ProductSerializer(stat)
return Response(serializer.data)
else:
data = JSONParser().parse(request)
serializer = ProductSerializer(data=data)
if serializer.is_valid():
serailizer.save() # Save data if you need or ommit it.
return Response(serializer.data)
else:
return Response({'error': True})
Related
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
I am trying to create a online class and want to loop through the list of the classes to see if he/she been registered or not
problem is if the list be empty it will return an error
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' : 'somepin',
'amount' : int(Class.totalPrice),
'callback' : 'http://localhost:3000/verify/',
}
for i in user.userprofile.onlineClass.all():
if i == Class:
return Response({"details": "allready registered"}, status=status.HTTP_400_BAD_REQUEST)
else:
try:
response = requests.post("URL_TO_SOMEWHERE", data=orderCred)
if response.status_code == 200 and not response.text.replace('-',"").isdigit():
registeredClass = RegisterStudentForOnlineClass.objects.create(
user=user,
totalPrice = int(Class.totalPrice),
transId = response.text,
onlineClassName= Class
)
serializer = RegisterForClassSerializer(registeredClass , many=False)
return Response(serializer.data)
else:
return Response({"details": ""} , status= status.HTTP_400_BAD_REQUEST)
except Exception as e:
return Response({"details": e})
here is the returned error
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
Thank you :)
when you call for i in user.userprofile.onlineClass.all() and it is empty it will simply pass the loop. Your problem is actually that you just need a default response for the scenario that user.userprofile.onlineClass.all() is empty.
Simply put a default expected response after the for loop
When I try to send pk2 or any other argument, it raises an AssertionError.
What I mean is this that the url
path('grade/<str:pk>/', IndividualGrade.as_view(), name="get-grade")
doesn't throw an error while the one below causes an error:
path('grade/<str:pk2>/', IndividualGrade.as_view(), name="get-grade")
My view is fairly simple as below:
class IndividualGrade(generics.RetrieveUpdateDestroyAPIView):
''' PUT/GET/DELETE grade/{grade:pk}/ '''
queryset = Grade.objects.all()
serializer_class = GradeSerializer
def put(self, request, *args, **kwargs):
try:
g1 = Grade.objects.get(grade=kwargs["pk"])
serializer = GradeSerializer(g1, data=request.data)
flag = 0
except Grade.DoesNotExist: # Create a new grade if a grade doesn't exist
g1 = Grade.objects.get(grade=kwargs["pk"])
serializer = GradeSerializer(g1, data=request.data)
flag = 1
if serializer.is_valid():
# call update/create here
else:
return Response(serializer.errors)
return Response(serializer.data, status=status.HTTP_200_OK)
I realized pk2 in the url works if I write my own get function (tried in another view), but I don't know how to fix this without writing my own get. While this have been discussed here. But I am still not sure how to fix it without writing my own get.
you need to add
lookup_field = 'pk2'
when you are using something else than pk, which is inbuilt for lookup . when you want something else in the url you need to mention that.
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)
I am writing an app in django rest-framework:
My views.py:
class tagList(generics.ListCreateAPIView,APIView):
model = tags
serializer_class = getAllTagsDetailSerializer
def get_queryset(self):
print "q1"
print self.request.QUERY_PARAMS.get('tag', None)
print self.request.user
print "q1"
if tags.objects.filter(tag='burger')!= None:
return tags.objects.filter(tag='burger')
else:
content = {'please move along': 'nothing to see here'}
return Response(content, status=status.HTTP_404_NOT_FOUND)
I want to return error status code if query returns None.
But the problem if i try to set Response it throws error:
Exception Type: TypeError
Exception Value:
object of type 'Response' has no len()
Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/paginator.py in _get_count, line 53
Else if query result is Not None it is working.
How can i set status code on Django rest-framework.
The method is expected to return a QuerySet, not a Response object, my bet is that you should throw an Exception, either an APIException or an Http404.
Anyway your handling seems odd, I think you should just return the QuerySet and the framework will handle if the result is empty or not. The method should look like this:
def get_queryset(self):
return tags.objects.filter(tag='burger')
Can you try this
model = tags # Model name
serializer_class = getAllTagsDetailSerializer # Call serializer
def get_queryset(self):
key = self.request.QUERY_PARAMS.get('appKey', None)
getTagName = self.request.QUERY_PARAMS.get('tagName')
keyData = app.objects.filter(appKey=key).exists()
try:
if keyData == True:
return tags.objects.filter(tag=getTagName)
else:
raise exceptions.PermissionDenied
except app.DoesNotExist:
pass
I think it will work....