Read request.POST with json data (Django) - python

I'm new on "Django".
I want read json data in "django" view. These data send from http://www.payplug.fr to my website into request.post. Here are my urls.py :
from credits.views import retour_ipn
urlpatterns = patterns('',
('^c/retour_ipn/$', retour_ipn),
)
And credits.views :
#csrf_exempt
def retour_ipn(request):
from base64 import b64decode, b64encode
header = request.META['HTTP_PAYPLUG_SIGNATURE']
signature = b64decode(header)
body = request.raw_post_data
data = json.loads(body)
print data
return HttpResponseRedirect('/')
After, signature will be analyses for save data in "django" models.

Related

when I export posts from django I get <django_quill.fields.FieldQuill object at 0x7f0746389840>?

I'm working on Django blog and I want to export posts and I made it work but I have a problem when exporting text because I used Quill - rich text editor and Django Import Export
body = QuillField()
And when I export posts in excel, I got this <django_quill.fields.FieldQuill object at 0x7f0746389840>.
excel is looking like this,
image
This is resources.py
from import_export import resources
from .models import Post
class PostResource(resources.ModelResource):
class Meta:
model = Post
This is views.py
def export_data(request):
if request.method == 'POST':
# Get selected option from form
file_format = request.POST['file-format']
post_resource = PostResource()
dataset = post_resource.export()
if file_format == 'CSV':
response = HttpResponse(dataset.csv, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="exported_data.csv"'
return response
elif file_format == 'JSON':
response = HttpResponse(dataset.json, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="exported_data.json"'
return response
elif file_format == 'XLS (Excel)':
response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="exported_data.xls"'
return response
return render(request, 'dashboard/export.html')
Any idea how to get the text in this body column?
Thanks in advance!
You have to get the content from the quill object Post.body.html or Post.body.html
Try something like this
from import_export import resources
from import_export.fields import Field
from .models import Post
class PostResource(resources.ModelResource):
body = Field()
class Meta:
model = Post
def dehydrate_body(self,post):
body_content = post.body.html
return body_content
See docs : https://django-import-export.readthedocs.io/en/stable/getting_started.html#advanced-data-manipulation-on-export
and Django Quill Editor Display Saved Field

Django Views not getting POST Data from api call

I am not using django rest frame work
but in normal views.py I have a simple views
#views.py
def api_post_operations(request):
pdb.set_trace()
if request.POST:
print(request.POST["name"])
print(request.POST["address"])
now I call it
import requests
url = "http://localhost:8000/api_post_operations"
payload = {"name":"raj", "address": "asasass" }
rees = requests.post(url, data=payload, headers={})
it is comming
(Pdb) request.POST
<QueryDict: {}>
Any reason why it is comming {} balnk
request.body also comming blank

Djoser user activation email POST example

I am using the Django rest framework and Djoser for Authentication and User Registration.
When a new user registers, Djoser sends an activation email with a link that does a GET request. In order to activate, I need to extract the uid and token from the activation URL and make a POST request for Djoser to be able to activate the user.
My environment is Python 3 and Django 1.11, Djoser 1.0.1.
What I would like to do is to handle the get request in Django, extract the uid and token, and then make a POST request. I have extracted the uid and token and would like to make a POST (within this GET request).
I do not know how to make this POST request in the background.
My URL is like this:
http://127.0.0.1:8000/auth/users/activate/MQ/4qu-584cc6772dd62a3757ee
When I click on this in an email it does a GET request.
I handle this in a Django view.
The view needs to make a POST request like this:
http://127.0.0.1:8000/auth/users/activate/
data= [(‘uid’=‘MQ’), (‘token’=‘4qu-584cc6772dd62a3757ee’),]
My view to handle GET is:
from rest_framework.views import APIView
from rest_framework.response import Response
import os.path, urllib
class UserActivationView(APIView):
def get (self, request):
urlpathrelative=request.get_full_path()
ABSOLUTE_ROOT= request.build_absolute_uri('/')[:-1].strip("/")
spliturl=os.path.split(urlpathrelative)
relpath=os.path.split(spliturl[0])
uid=spliturl[0]
uid=os.path.split(uid)[1]
token=spliturl[1]
postpath=ABSOLUTE_ROOT+relpath[0]+'/'
post_data = [('uid', uid), ('token', token),]
result = urllib.request.urlopen(postpath, urllib.parse.urlencode(post_data).encode("utf-8"))
content = result.read()
return Response(content)
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
import requests
class UserActivationView(APIView):
def get (self, request, uid, token):
protocol = 'https://' if request.is_secure() else 'http://'
web_url = protocol + request.get_host()
post_url = web_url + "/auth/users/activate/"
post_data = {'uid': uid, 'token': token}
result = requests.post(post_url, data = post_data)
content = result.text
return Response(content)
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^auth/users/activate/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', UserActivationView.as_view()),
]

Django: send json response from view to a specific template

The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), as a part of response. Also, the json response contains model and pk attribute, I want to remove them and send only the fields json attribute.
When I try as follows :
def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return HttpResponse (serializers.serialize('json', personal_detail_json), content_type='application/json');
I get json in a new page.
And when I try as follows :
def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/output.html", {'personal_detail': personal_detail})
I have to access the data via {{ personal_detail }} in my html, and not from response.
Also, the json response is as follows :
[
{
model: "buglockerApp.personal_details",
pk: "001",
fields: {
name: "Rajiv Gupta",
email: "rajiv#247-inc.com",
doj: "2016-06-22",
dob: "2016-06-22",
address: "Bangalore",
contact: "9909999999"
}
}
]
I don't want the model and pk to be sent as the response. Only fields should be sent as a part of response to webFiles/output.html file.
Thanks in advance!!
you can do the following in python2.7
import json
from django.http import JsonResponse
def view_personal_details (request):
personal_detail = serializers.serialize('json', personal_details.objects.all())
output = [d['fields'] for d in json.loads(personal_detail)]
# return render (request, "webFiles/output.html", {'personal_detail': output})
# for ajax response
return JsonResponse({'personal_detail': output})
or you can read the following for more clarification
https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-of-natural-keys
https://github.com/django/django/blob/master/django/core/serializers/base.py#L53
The default serializers always add the model and pk so that the data can be deserialized back into objects. Either you can write a custom serializer or can simply remove the unwanted data.
personal_details = [pd['fields'] for pd in personal_details]
This should give you a new list of dicts with personal details

get Json data from request with Django

I'm trying to develop a very simple script in Django, I'd collect a Json data from the request and then store all data in the database.
I developed one python script that I'm using to send the Json data to the Django view, but I'm doing something wrong and I can't understand what, because every time that I run it,I've got "Malformed data!".
Can someone helps me? what am I doing wrong?
Sender.py
import json
import urllib2
data = {
'ids': ["milan", "rome","florence"]
}
req = urllib2.Request('http://127.0.0.1:8000/value/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Django view.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
from models import *
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def value(request):
try:
data = json.loads(request.body)
label = data['label']
url = data ['url']
print label, url
except:
return HttpResponse("Malformed data!")
return HttpResponse("Got json data")
Your dictionary "data" in sender.py contains only one value with key "ids" but in view.py you are trying to access keys "label" and "url" in this parsed dictionary.

Categories