I installed recaptcha (work with django rest framework an angularjs) on my site but i don't now how obtain g-recaptcha-response can anyone show example
$scope.submit = function() {
$http.get('https://www.google.com/recaptcha/api/siteverify').success(function (data) {
$http.post(callbackUrl, $scope.callback).success(function (data) {
$scope.isFormActive = false;
}).error(function (data, status, headers, config) {
alert('Incorrect');
});
}).error(function (data, status, headers, config) {
alert('Incorrect');
});
};
i don't now how set parameters secret key and response for https://www.google.com/recaptcha/api/siteverify
Thanks
you can get g-recaptcha-response by calling "grecaptcha.getResponse()" this in your javascript
source: get_recaptcha_response
If you are working with Django REST framework (DRF) you might want to checkout these packages:
https://github.com/Maximilien-R/django-rest-framework-recaptcha
https://github.com/motius/django-rest-recaptcha
https://github.com/zueve/django-rest-captcha
The first two are implementing a DRF recaptcha serializer field, you can put it into your serializer and it has its own validators making a call to google verify URL. Last one (django-rest-captcha package) is implementing a serializer again with its own validators. All packages are on pypi so you can install them using pip.
Frontend integration according to documentation:
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
...
});
});
</script>
Below is an example code for BE using django-rest-framework-recaptcha package.
Serializer:
from rest_framework import serializers
from rest_framework_recaptcha.fields import ReCaptchaField
class ReCaptchaSerializer(serializers.Serializer):
recaptcha = ReCaptchaField()
View:
class VerifyTokenAPI(views.APIView):
allowed_methods = ["POST"]
def post(self, request, *args, **kwargs):
serializer = ReCaptchaSerializer(data=request.data)
if serializer.is_valid():
return Response({'success': True}, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Urls:
urlpatterns = [
...
path("/my/api/endpoint/", VerifyTokenAPI.as_view()),
]
Basic test call to BE:
data = {"recaptcha": "token"}
response = client.post("/my/api/endpoint/", data)
assert response.status_code == 200
Related
I'm trying to do an endpoint API. And for that, i'm using django.
My url in urls.py is :
path('tutorials/', tutorial_list_test.as_view()),
and my views.py is like
class tutorial_list_test(GuestOnlyView, FormView):
print("test");
#api_view(['GET', 'POST', 'DELETE'])
def tutorial_list(self):
request = self.request;
if request.method == 'POST':
alldata=request.POST
username = alldata.get("username", "0")
print("POST name: " + username)
return Response('The tutorial does not exist', status=status.HTTP_404_NOT_FOUND)
But when i'm doing a request, i have everytime the same error "Forbidden (CSRF cookie not set.): /accounts/tutorials/"
So I did some research, and I could see several proposed solutions.
The first was to use csrf_exempt but it's not working for me:
path('tutorials/', csrf_exempt(tutorial_list_test.as_view())),
And it's the same for all the methods I used. Even if I remove this line from my settings.py, nothing changes
# django.middleware.csrf.CsrfViewMiddleware',
To test, I use Postman, but even using my angular front end, it does the same.
const formData = new FormData()
formData.append('username', this.username_signup);
this.http.post('http://127.0.0.1:8000/accounts/tutorials/', formData)
.map((data: Response) => {
if (data !== null) {
console.log(JSON.stringify(data));
};
}).subscribe(response => console.log(response))
I would like to know if you have any idea how I can do this.
Because I need to be able to access my Models, so not using a class and directly making a def is not an option, even if it works.
(I tried, effectively my requests pass, if I remove the class and my route is only linked to my def tutorial_list).
Thank you.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
#api_view(['GET', 'POST', 'DELETE'])
def tutorial_list(self):
# code
I've followed everything mentioned in both documentation of Django rest-framework and Flutter http but still getting the error ..here is my code :
Django
Settings
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
View
#csrf_exempt
#permission_classes(["isAuthenticated"])
#api_view(['POST'])
def chanage_image(request):
data = {}
if request.method == "POST":
token = request.META['HTTP_AUTHORIZATION'][6:]
lang = request.META['HTTP_LANG']
image = request.data['image']
main_user = Token.objects.get(key=token).user
app_user = AppUser.objects.get(main_user=main_user)
format, imgstr = image.split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance.
app_user.image = data
app_user.save()
data = {"success": True, "details": AppUserSerializer(
app_user).data, "message": "Image changed" if lang == "en" else "تم تغيير الصورة"}
return Response(data, headers=get_headers())
URLS
path('chanage_image/', chanage_image,name="chanage_image"),
Flutter
Request
Map<String, dynamic> body = {
"image": base64Image,
};
Future<UserModel> changePlayerImage(Map<String, dynamic> body) async {
return await httpClient.post('api/user/change-image',
body: body,
headers: {'referer': 'https://www.l-dawri.com/'}).then((response) {
print(response.body);
return UserModel.fromJson(response.body);
});
}
but still in the end am always getting this error :
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms.
First you don't sent authorization token into header request while use from drf TokenAuthentication
Also into drf is better you use from class view api(like inheritance from APIView) replace def view's
I have the following requirement:
Send data to backend using fetch()
receive the data in a view and render another template ( route to a different view)
The following is my code snippet:
JS:
fetch("/addpost", {
method: "POST",
body: JSON.stringify({ value: selecteddict }),
headers: {
"Content-type": "application/json;",
},
})
.then((res) => {
return res.text();
})
.then((text) => {
console.log(text);
});
// the data is being sent successfully
Django View1:
#csrf_exempt
def addpost(request):
if request.method == 'POST':
song = json.loads(request.body.decode('utf-8'))['value']
print(song)
# I want to redirect to another view called createpost that renders a new page
return JsonResponse({'status':201})
return render(request, 'addpost.html')
Django createpost view:
def createpost(request):
return render(request, 'createpost.html')
The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost
Please suggest a solution to this.
Your addpost view returns as JsonResponse in case of a POST request. If you want to redirect somewhere you need to use redirect() instead of JsonResponse()
I have an API endpoint with Django Rest Framework to upload an image.
Can you spot what I'm doing incorrectly?
#models.py
class test(models.Model):
...
upload_path = 'upload/'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
...
#serializers.py
class TestSerializer(serializers.ModelSerializer):
image = serializers.ImageField(
max_length=None, use_url=True,
)
class Meta:
model = test
fields = ('id','name','image',...)
#views.py
#api_view(['GET', 'POST'])
def test_list(request, site_id, block_id):
....
if request.method == 'POST':
serializer = TestSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else :
return Response(status=status.HTTP_403_FORBIDDEN)
#js
function setimage() {
var $input = $("#js_teaser_img");
var fd = new FormData;
fd.append('image', $input.prop('files')[0]);
$.ajax({
url: '/api/....',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
}
result image: ["No file was submitted."] 0: "No file was submitted."
result
Django REST Framework upload image: "The submitted data was not a file"
+
var reader = new FileReader();
reader.onload = function(e) {
var img_local = e.target.result;
$('.js_img_src').attr('src', img_local);
$.post('/api/..../7/', {'image':img_local} , function( data ) {
console.log(data);
});
}
reader.readAsDataURL(file);
From the client side in order to send files, you should use "multipart/form-data" (jQuery sets contentType as "application/x-www-form-urlencoded" instead by default).
Read this question on SO: Sending multipart/formdata with jQuery.ajax
Regarding instead python and django rest framework, you should use MultiPartParser and/or FileUploadParser in your API view and the preferred method for fle upload should be "put", as you can see in the reference here: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser.
ps. if you use django rest framework, I strongly encourage you to use Angular instead of jQuery, since it offers an excellent integration for rest services... trust me is FAR BETTER! ;)
I have a ajax call in my django template file as:
$(document).ready(function () {
$("button#wdsubmit").click(function(){
$.ajax({
type: "post",
url: "/audit/addwd/",
data: $('form.wddetails').serialize(),
dataType: "json",
success: function(msg){
alert(msg);
alert('Added Successfully');
$("#newwd").modal('hide'); //hide popup
},
error: function(msg){
alert(msg.success);
}
});
});
});
Form:
class WDForm(ModelForm):
class Meta:
model = WDModel
fields = '__all__'
and view in django is :
def addwd(request):
if request.method == 'POST':
updated_request = request.POST.copy()
updated_request.update({'updated_by': request.user.username})
form = WDForm(updated_request)
if form.is_valid():
form.save()
response = simplejson.dumps({'success': True})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
else:
response = simplejson.dumps({'error': True})
return HttpResponse(response , content_type="application/json")
Whenever I make a Ajax call it always returns error even though I have sent Success(Means the form is valid and data is successfully pushed to database).
I also tried to send response={'success':True} doesn't work.
Please help me to solve this issue.
Environment Details:
Python verion: 3.4
Django :1.7
Windows OS 8
I doubt on this line " response = simplejson.dumps({'success': success})
"
you can try JsonResponse objects.
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})