How to hide POST request on view in django? - python

I have one view which has POST and GET request. For POST request data comes from other URL. I don't use this view to POST the data. However, I have a GET request for the same view which retrieves data from the model and displays it. Now, when I open (GET request) this view it correctly shows the data. But in addition it shows text area for a POST request as well. I want to hide POST request on my view.
Code:
#api_view(['POST','GET',])
def TestView(request):
if request.method == 'POST':
data = json.loads(request.body.decode('utf-8'))
customers_instance = Customers.objects.create(firstname=data[0]["value"],
lastname=data[1]["value"],
dob=data[2]["value"],
emailaddress=data[3]["value"],
address1=data[4]["value"],
address2=data[5]["value"],
city=data[6]["value"],
state=data[7]["value"],
postalcode=data[8]["value"])
return HttpResponse('Data has been received by API')
if request.method == 'GET':
qs= Customers.objects.values('emailaddress','customer_id')
serializer_class = CustomersKeySerializer
return Response(serializer_class(many=True).to_representation(qs))

Jay,
I think you should use two different views since you are dealing with two different URL's: one for GET and one for POST request.
#api_view(['GET',])
def TestGetView(request):
if request.method == 'GET':
qs= Customers.objects.values('emailaddress','customer_id')
serializer_class = CustomersKeySerializer
return Response(serializer_class(many=True).to_representation(qs))
#api_view(['POST',])
def TestPostView(request):
if request.method == 'POST':
data = json.loads(request.body.decode('utf-8'))
customers_instance = Customers.objects.create(firstname=data[0]["value"],
lastname=data[1]["value"],
dob=data[2]["value"],
emailaddress=data[3]["value"],
address1=data[4]["value"],
address2=data[5]["value"],
city=data[6]["value"],
state=data[7]["value"],
postalcode=data[8]["value"])
return HttpResponse('Data has been received by API')

Related

Creating new model in Django with POST data from Python requests

I'm trying to take information from a POST request made from Python requests and add them to my model:
def message(request):
if request.method == 'POST':
form = InputInfoForm(request.POST)
#form models make validation easy
if form.is_valid():
InputInfo.name = request.POST.get('name')
InputInfo.conversation_id = request.POST.get('conversation_id')
InputInfo.message_body = request.POST.get('message_body')
return HttpResponse(status=200)
return HttpResponse(status=200)
Here's the request
post_data = {'name': 'charles', 'conversation_id': '3', 'message_body': 'Ada Challenge'}
r = requests.post('http://127.0.0.1:8000/message/', data=post_data)
I am not sure if I am handling the requests right in the view
As mentioned in comments that InputInfoForm is a ModelForm. So you can call form.save method after calling form.is_valid method.
if form.is_valid():
form.save() # This method will handle data saving part, no need to assign explicitly

Getting Previous URL in Django Form

So i'm trying to build something, so that users would be able to report something on site. Here's the model,
class Report(models.Model):
reporting_url = models.URLField()
message = models.TextField()
Here's the view,
def report(request):
url_report = ???
if request.method == 'POST':
form = ReportForm(request.POST or None)
if form.is_valid():
new_form = form.save(commit=False)
new_form.reporting_url = url_report
new_form.save()
I can't use something like,
url_report = request.get_full_path()
since I need to create/edit several views & repeat things in that case.
When I'm using something like,
url_report = request.META.get('HTTP_REFERER')
it's returning the URL of same page from where the from is written. I'm using something like,
Report
to reach the Report form from several different apps/html_pages.
How can I get the URL of previous page from where user has pressed the "Report" button?
Please help me with this code!
You could store the referer in the session whenever the Report button is pressed:
def report(request):
if request.method == 'GET':
request.session['report_url'] = request.META.get('HTTP_REFERER')
# ...
if request.method == 'POST':
form = ReportForm(request.POST or None)
if form.is_valid():
new_form = form.save(commit=False)
new_form.reporting_url = request.session.get('report_url')
new_form.save()
You have to persist this referer beyond one request-response cycle. The session is the designated way to do that. Another option would be to render that url as a hidden form field, but that can be easily tampered with.

Python Django - Access Response Headers In View

I am working on a web application which works with entities that all have their unique IDs.
I have a submit form for users to create these entities and this form is in several steps (i.e. view 1 redirects to view 2, etc... until the end of the submission process).
The first view will create the ID of the entity after form submission and I then need to use the ID of the instance created in the other views.
I do not want to pass this ID as a URL parameter to the other views as these will be POST and that means that users could easily manipulate these and create records in models for several IDs. I have managed to pass this ID to several views using the session parameters (request.session) but this is not ideal as this is permanent for the session. Current code below:
def view1(request):
if request.method == 'POST':
form = xxx_creation_form(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
... object creation ...
)
request.session['xxx_id'] = xxx_entry.id
return HttpResponseRedirect(reverse('form_2'))
else:
form = xxx_creation_form()
return render(request, 'xxx_form.html', {'form': form})
def view2(request):
xxx_id = request.session['property_id']
if xxx_id == 'SET_BACK_BLANK':
return render(request, 'no_xxx_id.html')
if request.method == 'POST':
form = xxx_form2(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
id = xxx_id, #use the id created in step 1
... rest of object creation ...
)
request.session['xxx_id'] = 'SET_BACK_BLANK' #to avoid the misuse during other user interactions.
return HttpResponseRedirect(reverse('thanks'))
else:
form = xxx_form2()
return render(request, 'xxx_form2.html', {'form': form})
Ideally, I would like to pass this ID parameter in the headers of the response as this will avoid having the ID as a session parameter. So I have amended the code to the below:
def view1(request):
if request.method == 'POST':
form = xxx_creation_form(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
... object creation ...
)
response = HttpResponseRedirect(reverse('form_2'))
response['xxx_id'] = xxx_entry.id
return response
else:
form = xxx_creation_form()
return render(request, 'xxx_form.html', {'form': form})
def view2(request):
xxx_id = HttpResponseRedirect(request).__getitem__('xxx_id')
if request.method == 'POST':
form = xxx_form2(request.POST)
if form.is_valid():
cleaned_form_data = form.cleaned_data
xxx_entry = Model.objects.create(
id = xxx_id, #use the id created in step 1
... rest of object creation ...
)
return HttpResponseRedirect(reverse('thanks'))
else:
form = xxx_form2()
return render(request, 'xxx_form2.html', {'form': form})
However the above does not work and the error message seems to indicate that there is no 'xxx_id' in the response header.
It would be great if anyone could let me know how to access a response's header in a view as it seems that we cannot amend the request's headers.
Thanks.
What you're asking doesn't really make sense. The response is what is sent from Django to the browser, it is not what the browser sends to Django. That's a completely separate request; in the case of a redirect, your response is simply an instruction to the browser to make that request to a new URL.
The correct thing to do is to use the session, as you are doing. If you are worried about the value being persisted, then pop it out of the session when you use it:
xxx_id = request.session.pop('property_id')

Switch view - Django

when I try to render a page does not work, here's a quick example, what I do is to send data from a form from the html with a button,
and then redirect it to another page.
The data arrive correctly and I've checked from the server.
views.py
def index(request):
context={}
if request.method == 'POST': # If the form has been submitted...
form=list(dict(request.POST)['data[]'])
return render(request,'bala/pdf.html',{'form':form})
else:
return render(request,'bala/index.html',context)

Django - best practice for getting ID from querystring into edit view

I'm wondering what the acceptable best practice is for pulling an id from a url for use in the edit view. Most example code I see uses slugs, which I don't need to deal with because SEO is not a concern.
Say I have something like:
def article_edit(request):
if request.method == 'POST': # If the form has been submitted...
#a = get_object_or_404(Article, **?XXX?**)
#a = Article.objects.get(pk=**?XXX?**)
form = ArticleForm(request.POST, instance=a) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
return redirect('/articles/') # Redirect after POST
else:
form = ArticleForm() # An unbound form
return render(request, 'article_form.html', {'form': form})
Where I have commented out two possible options for populating a with an Article object based on the ID submitted in the POST. The ?XXX? indicates that I'm not sure how to reference the passed in id.
Any input on those two options, as well as alternative options are appreciated.
Passed in id should go in the url itself, like:
url(r'^articles/(?P<id>\d+)/edit/$', 'views.article_edit', name = 'article_edit'),
Then, in the view you can reference it from the view argument id:
def article_edit(request, id):
if request.method == 'POST': # If the form has been submitted...
article = get_object_or_404(Article, pk=id)
Also, take a look at Writing a simple form chapter of django "polls" tutorial - the same approach is used.
Hope that helps.
try this:
urls.py :
url(r'^articles/(?P<article_id>\d+)/edit/$', 'views.article_edit', name = 'article'),
views.py:
def article_edit(request, id):
if request.method == 'POST':
article = get_object_or_404(Article,id=article_id)

Categories

Resources