I am trying to implement url callbacks. And trying to test it. But seems like it is not working. I have been following this article for callbacks implementation.
I have defined two urls in urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^agent205', 'agent205.views.test'),
url(r'^agent206', 'agent205.views.test2'),
)
and their views in views.py
__author__ = 'rai'
from django.shortcuts import HttpResponse, render_to_response, render
from django.http.request import HttpRequest
import urllib, urllib2, json
from django.contrib.auth.decorators import login_required
import json
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json')
#csrf_exempt
def test2(request):
return HttpResponse(json.dumps(request.body), content_type='application/json')
Then I test from postman like
I am getting HTTP 200 OK response instead of getting 202 Accepted. What should I do for callback to work? Or am I missing something
If your issue is to return a 202 HTTP status code instead of the default 200, you could try to use the status parameter as follows:
#csrf_exempt
def test(request):
data = {'foo': 'bar', 'hello': 'world'}
print request.body
return HttpResponse(json.dumps(data), content_type='application/json', status=202)
Related
For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening?
urls.py
from . import views
urlpatterns = [
path('',views.index, name='index'),
path('proceedaction/<str:pk>/',views.ProceedAction.as_view(),name='proceedaction'),
path('uploadct/<str:pk>/',views.UploadCT.as_view(),name='uploadct'),
]
views.py
from django.shortcuts import render,redirect
from django.views import View
from .models import CreatePatient,PatientRecord,FileData
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .filters import RecordFilter
from django.http import HttpResponse
import json
# Create your views here.
def index(request):
return render(request,'index.html')
class UploadCT(View,LoginRequiredMixin):
def get(self,request,pk):
records = PatientRecord.objects.filter(id=pk)
context={
'record' : records,
}
return render(request,'ct_upload.html',context=context)
def post(self,request):
dbdata = FileData()
return redirect('index')
I had not specified method=POST in the corresponding HTML file. Solved this issue by doing that.
I am trying to add numbers with a REST API created with Django Rest Framework. What I am trying to perform is that I make a GET call to the API and provide data in the form of JSON. The API then sends me sum of the numbers in JSON format.
This is the function based api view I have written to add the numbers.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.http import HttpResponse, JsonResponse
from rest_framework.response import Response
import json
# Create your views here.
#api_view(['GET', 'POST'])
def api_add(request):
sum = 0
response_dict = {}
if request.method == 'GET':
data = JSONParser().parse(request)
for key in data:
sum += data[key]
response_dict = {"sum": sum}
elif request.method == 'POST':
# Do nothing
data = JSONParser().parse(request)
for key in data:
sum += data[key]
response_dict = {"sum": sum}
return JsonResponse(json.loads(json.dumps(response_dict)), safe=False, status=status.HTTP_201_CREATED)
The urls.py has the following.
from django.urls import path
import Prediction.views as views
urlpatterns = [
path('add/', views.api_add, name = 'api_add')
]
The urls.py is linked to main .urls.py as below:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('Prediction.urls')),
]
So basically my url is http://127.0.0.1:8000/api/add/.
I can make GET calls to the above API from Postman. Postman is able to perform both the GET and POST requests and is able to get a response back in JSON format.
However if I try to do the same in browser I get an error as below.
How do I make the GET request from the browser with the JSON. Any help much appreciated
In Django REST Framework, I'm trying to add an API root to a views.py that has class based views.
Error:
$ http http://127.0.0.1:8000/api/
Error - django.urls.exceptions.NoReverseMatch: Reverse for 'SnippetListView' not found. 'SnippetList' is not a valid view function or pattern name.
backend/views.py
from backend.models import *
from backend.serializers import *
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'snippets': reverse('SnippetList')
# 'snippets': reverse('SnippetListView')
# 'snippets': reverse('snippet-list')
# 'snippets': reverse('snippet_list')
})
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
backend/urls.py
from backend import views
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('', views.api_root),
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
Docs:
https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-highlighted-snippets
You need to name the view url in order to use the reverse.
#urls.py
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
#views.py
'snippets': reverse('snippet-list', request=request, format=format)
The tutorial did not originally give names to the urls of the class based views.
I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.
I need to get the userid of user logged in to my django site. I am using Django 1.3.1.
Template
$.get(http://www.tomjoyapp.com/pinTag/, { URL: document.URL},
function(data){
alert("Data Loaded: " + data.responseText);
});
view
import os
from django.template.loader import get_template
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, RequestContext
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def pinTag(request):
user=request.user.id
return HttpResponse(str(user))
I need to get the userid as response if he is logged in to my django app.
I am getting the status as 200 OK. But No response.