How to print post request data in django - django

In PHP when I send post request data from template form to controller I can use print_r($data) to print form send data for debugging purpose but in Django how can I print post request form data in view.py

If you get your form data like PHP you may use
from django.http import HttpResponse
return HttpResponse(request.POST.items())
And for more debuging follow this Link

Related

By Post request received data is None. Why it's possible

I have django app in it's views.py created for accepting, and saving objects from received data into database.
from .models import Hook
def hooktrack(request):
source=requests.POST.get("source")
b=Hook(dsourse=source).save()
Than I link this view to .urls.py
urlpatterns = [
path("hooktrack/",hooktrack),
]
My full url use http protockol not https
maybe it involved in my problem
I several times tested hooktrack view and it was accept and save received data.
curl -d "source=google" -X POST http://example.net/hooktrack/
After curling sent source=value accessible to query from dB.
from my.models import Hook
a=Hook.objects.all()
for item in a:
print(item.dsource)
...google
Than I linked my hooktrack view to production for accepting hooks from our business partner. After receiving them all of them saved to database but has None value
Updated
I inspected my Nginx logs and found that POST request and it is looking isn't as json
[05/Oct/2020:17:46:59 +0000] "POST /calltrackinghook/?dsource=google&dmedium=cpc&dcampaign=10393090041&dterm=+%D1%85%D0%BE%D0%BB%D0%BE%D0%B4%D0%B8%D0%BB%D1%8C%D0%BD%D0%B8%D0%BA%20+%D0%B1%D0%BE%D1%88_b&dcontent=gclid=CjwKCAjwiOv7BRBREiwAXHbv3O6RZTQ_CCIENfrX0FJqtKBFhPmhF6gZFjbewnG-P-UUnHQn_5n7ZhoCtmwQAvD_BwE&disposition=ANSWERED&virtual_number=8005337639&caller=9324034020&real_number=17612021180&uniqueid=1601920016.1303437&datetime=2020-10-05%2020:46:56&duration=0&recordlink=https%3A%2F%2Fcalltracking.ru%2FshareRecords%2F2020-10-05%2F1601920016.1303437.mp3&project_id=9892&source_id=&accountcode=&landing=https%3A%2F%2Fm.05.ru%2F&client_landing=&source_name=Google.Adwords&call_region=%D0%A5%D0%B0%D0%BD%D1%82%D1%8B-%D0%9C%D0%B0%D0%BD%D1%81%D0%B8%D0%B9%D1%81%D0%BA%D0%B8%D0%B9%20%D0%90%D0%9E&referrer=http%3A%2F%2Fwww.google.com%2F&cid
POST parameters available when you submit data in the application/x-www-form-urlencoded format (e.g., using a HTML form). So request 'Content-Type' must be application/x-www-form-urlencoded or multipart/form-data.
If data send as JSON, you can access your JSON data as follows:
import json
def hooktrack(request):
data = json.loads(request.body)
# Data is now a python dict, e.g.,
Maybe also interesting for you, csrf_exempt decorator.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def hooktrack(request):
source=requests.POST.get("source")
b=Hook(dsourse=source).save()
...

How to parse request in django

Hi i am making an webserver , In which I have to hit some request from html page and return the response. The URL which is generated using html is
http://192.168.2.253:8080/searchSMS/?KPImsgId=0&circle=&subId=&startDate=DD-MM-YYYY&endDate=DD-MM-YYYY&Username=ashish
but in the server side I am not able to see the request data. I am using
q = QueryDict(request.body) but it is showing <QueryDict: {}>
How to find the all the parameters coming in request.
In your case you send the data in url so access the data through request.GET as follow:
username = request.GET.get('Username')
start_date = request.GET.get('startDate')
# ... the same for all the other parameter after the `?` marque.
In fact there is a difference between request data, request.body, request.GET and request.POST:
If you are sending POST request to django function view or class based view: you access the request data in request.body or request.POST.
If you are sending POST request to Django REST Framework: you access the data in request.data. You may also find in Internet request.DATA that correct but it's deprecated in the newer version of DRF in favor of request.data.
If you send parameter in the url like in you case, you access the data form request.GET as explained above.

HTTP post request in Django

I am trying to do the following:
1) A payment solution is supposed to send an HTTP Post to my site
2) I would like to read the contents of the request(xml) and update my records to reflect the payment
I am trying this for the first time. When I create a URL path, and send a post to that address I get the csrf error.
Is there a way using Django wherein I can accept a post and don't have to return a response.
Thanks
Tanmay
Your view should return an http response, otherwise you will get an error. However, Django does not mind if that response does not contain any content. Your view can be as simple as:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def my_view(request):
# do something with request.POST
return HttpResponse("")
Since it is a third party that is submitting the post request, and not a user submitting a form on your site, you can mark the view as exempt from CSRF protection using the csrf_exempt decorator, as above.
Note that anyone could submit a post request to your url, so you should have some way of checking that the response is genuine. Your payment solution should be able to advise a suitable way to do this.

Getting PATCH request parameter in Django

Is it possible to retrieve the request parameters of a HTTP PATCH request in Django? request.method == 'PATCH' is recognised, but I struggle to retrieve the request payload. I've tried request.REQUEST.items(), but this didn't contain any data. I know I could use Django-tastypie, but in this case, I would like to avoid it (and I supposed tastypie is using some Django methods to retrieve this data anyway).
I'm using Django 1.5.1.
You can use a QueryDict class manually. This is class implemented in django and processing all text data received through http request.
Link on the docs:
https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.QueryDict
And here is an example of usage:
from django.http import QueryDict
def home_view(request):
if request.method == 'PATCH':
data = QueryDict(request.body)
print data['your_field']
As #asitm9 mentioned, using request.data works for POST, PUT and PATCH and is recommended.
Just try to use MultiPartParser when the CONTENT_TYPE is "multipart/form-data;",else QueryDict.
if request.META.get('CONTENT_TYPE', '').startswith('multipart'):
from django.http.multipartparser import MultiPartParser
query_dict, multi_value_dict = MultiPartParser(request.META, request,
request.upload_handlers).parse()
else:
from django.http import QueryDict
query_dict = QueryDict(request.body)
raw_post_data did the trick (I used it before, but forgot it existed)

satchmo password_reset html format mail

Ive been requested by a client that his satchmo store should send an html formatted mail when resetting his password.
Aparently satchmo or django's contrib.auth.views.password_reset sends only raw email.
How do I modify this in order to be able to send html formatted mails?
Thank you!
I haven't used Satchmo, but this should get you started.
First of all, subclass the PasswordResetForm, and override the save method to send an html email instead of a plain text email.
from django.contrib.auth.forms import PasswordResetForm
class HTMLPasswordResetForm(PasswordResetForm):
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator, from_email=None, request=None):
"""
Generates a one-use only link for resetting password and sends to the user
"""
# Left as an exercise to the reader
You can use the existing PasswordResetForm as a guide. You need replace the send_mail call at the end with code to send html emails. The docs about sending html emails should help.
Once you've written your form, you need to include the form in the url pattern for password_reset. As I said, I don't have any experience of Satchmo, but looking at the source code, I think you want to update satchmo_store.accounts.urls, by changing the password_reset_dict.
# You need to import your form, or define it in this module
from myapp.forms import HTMLPasswordResetForm
#Dictionary for authentication views
password_reset_dict = {
'template_name': 'registration/password_reset_form.html',
# You might want the change the email template to .html
'email_template_name': 'registration/password_reset.txt',
'password_reset_form': HTMLPasswordResetForm,
}
# the "from email" in password reset is problematic... it is hard coded as None
urlpatterns += patterns('django.contrib.auth.views',
(r'^password_reset/$', 'password_reset', password_reset_dict, 'auth_password_reset'),
...