django piston Circular reference detected while emitting response when using model - django

Am facing a problem with configuring piston for django, every time I specify the model name it runs I get the below error
RuntimeError at /en/vehicle/api/car.json
Circular reference detected while emitting response
Request Method: GET
Request URL: http://127.0.0.1:8000/en/vehicle/api/car.json
Django Version: 1.4.1
Exception Type: RuntimeError
Exception Value:
Circular reference detected while emitting response
Exception Location: /Users/mo/Projects/pythonic/gar-env/lib/python2.7/site-packages/piston/emitters.py in _any, line 109
Python Executable: /Users/mo/Projects/pythonic/gar-env/bin/python
Below is my handelrs.py
from piston.handler import BaseHandler
from piston.utils import rc, throttle, translate_mime
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from models import (ModelLookUpI18n as ModelLookup, Image)
from forms import CarForm, ModelLookUpForm, ModelLookUpI18nForm
from django.http import HttpResponse
import logging, json, os
from piston.utils import validate
from django.conf import settings
from django.utils.translation import ugettext as _
class CarHandler(BaseHandler):
"""
CarHandler
"""
allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
model = Car
fields = ('id', 'model', 'description', 'primary_image', 'color', 'mileage', 'view_count', 'asking_price')
def read(self, request):
params = dict()
params.update({'status' : self.model.STATUS_ACTIVE})
return self.model.objects.filter(**params).order_by('created_at')
in the url.py here is my code
from django.conf.urls import *
from handlers import CarHandler
from piston.resource import Resource
car_resource = Resource(CarHandler)
# API URL schema
urlpatterns += patterns('',
# car API
url(r'^api/car\.(?P<emitter_format>.+)', car_resource, name='vehicle-api-car'),
)
The error is coming at run time, I cannot find a solution to the problem. I tried to remove model and fields attribute from CarHandler class that would make it work. I tired to use get_model and load at run time but again, I would get the same runtime error.
Please advise?

Is 'model' a foreign key reference? Is it possible Piston is including 'model' in the output, which itself may have a reference back to the Car model it was included in?

Related

DRF: AttributeError: type object 'Plan' has no attribute 'get_extra_actions' [duplicate]

Trying a simple request:
urls.py
from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from django.http import HttpResponse
from rest_framework.urlpatterns import format_suffix_patterns
from .public_views import NavigationBar
router = routers.DefaultRouter()
router.register(r'navbar', NavigationBar, basename="NavigationBar")
urlpatterns = [
path('', include(router.urls))
]
urlpatterns = format_suffix_patterns(urlpatterns)
public_views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import api_view, throttle_classes
from . view_utils import *
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
class NavigationBar(APIView):
"""
obtain up to date navigation bar (or side menu navigation) hierarchy.
"""
permission_classes = ([AllowAny])
def get(self, request, format=None):
"""
get user addresses
"""
return Response("this is a good response")
def get_extra_actions(cls):
return []
When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error:
AttributeError at /v1/navbar
type object 'NavigationBar' has no attribute 'get_extra_actions'
Request Method: GET
Request URL: http://web/v1/navbar
Django Version: 2.1
Exception Type: AttributeError
Exception Value:
type object 'NavigationBar' has no attribute 'get_extra_actions'
Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.6.8
Python Path:
['.',
'',
'/usr/local/lib/python36.zip',
'/usr/local/lib/python3.6',
'/usr/local/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/site-packages']
Server time: Tue, 2 Jul 2019 17:12:27 +0000
I would appreciate any pointers. Also, I fail to understand why the error message includes a Request URL: http://web/v1/navbar indication when web is not part of the URL I'm using. Where is web coming from??? I just use /v1/navbar/ to hit the endpoint.
There are two things wrong here. First, routers are for viewsets, not simple views. Secondly, with a class based view you need to call it via its as_view() method in the urlconf. So get rid of that router stuff and just do:
urlpatterns = [
path(r'navbar', NavigationBar.as_view(), name="NavigationBar")
]
Note, now you're not using a router, you don't need that get_extra_actions method at all.

Django Rest Framework: Can't get over strange error

Trying a simple request:
urls.py
from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from django.http import HttpResponse
from rest_framework.urlpatterns import format_suffix_patterns
from .public_views import NavigationBar
router = routers.DefaultRouter()
router.register(r'navbar', NavigationBar, basename="NavigationBar")
urlpatterns = [
path('', include(router.urls))
]
urlpatterns = format_suffix_patterns(urlpatterns)
public_views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import api_view, throttle_classes
from . view_utils import *
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
class NavigationBar(APIView):
"""
obtain up to date navigation bar (or side menu navigation) hierarchy.
"""
permission_classes = ([AllowAny])
def get(self, request, format=None):
"""
get user addresses
"""
return Response("this is a good response")
def get_extra_actions(cls):
return []
When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error:
AttributeError at /v1/navbar
type object 'NavigationBar' has no attribute 'get_extra_actions'
Request Method: GET
Request URL: http://web/v1/navbar
Django Version: 2.1
Exception Type: AttributeError
Exception Value:
type object 'NavigationBar' has no attribute 'get_extra_actions'
Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.6.8
Python Path:
['.',
'',
'/usr/local/lib/python36.zip',
'/usr/local/lib/python3.6',
'/usr/local/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/site-packages']
Server time: Tue, 2 Jul 2019 17:12:27 +0000
I would appreciate any pointers. Also, I fail to understand why the error message includes a Request URL: http://web/v1/navbar indication when web is not part of the URL I'm using. Where is web coming from??? I just use /v1/navbar/ to hit the endpoint.
There are two things wrong here. First, routers are for viewsets, not simple views. Secondly, with a class based view you need to call it via its as_view() method in the urlconf. So get rid of that router stuff and just do:
urlpatterns = [
path(r'navbar', NavigationBar.as_view(), name="NavigationBar")
]
Note, now you're not using a router, you don't need that get_extra_actions method at all.

Django Testing: URL mapping to the Class Based View

I'm new to Django testing so trying basic testing codes. But it is showing one error in second test class
Tests.py
from django.test import TestCase,Client
from .views import PostList
from django.urls import resolve
class SmokeTest2(TestCase):
def test_math(self):
self.assertEqual(1+1,2)
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
print({'found':found})
self.assertEqual(found.func(), PostList)
views.py
class PostList(ListView):
model = Post
template_name = 'home.html'
urls.py
urlpatterns = [
path('',views.PostList.as_view(),name ='list'),
]
When i am printing found its showing the o/p
{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}
But still I am getting this error
(blog_env) PS D:\django\blog_env\mysite> python manage.py test
D:\django\blog_env\mysite
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}
E.
======================================================================
ERROR: test_root_url_resolves_to_home_page_view (blog.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\django\blog_env\mysite\blog\tests.py", line 19, in test_root_url_resolves_to_home_page_view
self.assertEqual(found.func(), PostList)
TypeError: view() missing 1 required positional argument: 'request'
----------------------------------------------------------------------
Ran 2 tests in 0.069s
FAILED (errors=1)
Destroying test database for alias 'default'...
I was stung by this issue just now, ended up finding the solution in the documentation
class-based views need to be compared by name, as the functions generated by as_view() won't be equal due to different object ids, so the assertion should look like the below:
from django.test import TestCase
from django.urls import resolve
from .views import HomePageView
class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
resolver = resolve('/')
self.assertEqual(resolver.func.__name__, HomePageView.as_view().__name__)
from django.urls import resolve, reverse
class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
resolver = resolve('/')
self.assertEqual(resolver.func.view_class, HomePageView)
You can try this, it worked for me!
Since you are testing a Class based View, from the Traceback it can be seen that it's missing the request object. You can use the RequestFactory provided by the django.test package. Better read the following RequestFactory Documentation to get a good view of it. It will solve your problem.
from django.urls import resolve, reverse
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
response = self.client.get(resolve('/'))
response = self.client.get(reverse('your_app_name:list'))
self.assertEqual(response.status_code, 200)

A Schema is required to be provided to GraphQLView

I was following this tutorial to integrate Graphql with Django, I did everything according to that tutorial when I'm hitting graphql URL on my local machine
http://localhost:8000/graphql
I'm geting the following error
AssertionError at /graphql
A Schema is required to be provided to GraphQLView.
Request Method: GET
Request URL: http://localhost:8000/graphql
Django Version: 1.11.1
Exception Type: AssertionError
Exception Value:
A Schema is required to be provided to GraphQLView.
Exception Location: /home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages/graphene_django/views.py in init, line 84
Python Executable: /home/psingh/Projects/django_graphql/env/bin/python
Python Version: 2.7.6
Python Path:
['/home/psingh/Projects/django_graphql/project',
'/home/psingh/Projects/django_graphql/env/lib/python2.7',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/plat-x86_64-linux-gnu',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-old',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/site-packages']
Server time: Fri, 12 May 2017 12:18:31 +0000
In settings.py
GRAPHENE = {
'SCHEMA': 'project.schema.schema'
}
project> schema.py
import graphene
import mainapp.schema
class Query(mainapp.schema.Query, graphene.ObjectType):
# This class will inherit from multiple Queries
# as we begin to add more apps to our project
pass
schema = graphene.Schema(query=Query)
app>schema.py
import graphene
from graphene_django.types import DjangoObjectType
from cookbook.ingredients.models import Category, Ingredient
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
class Query(graphene.AbstractType):
all_categories = graphene.List(CategoryType)
all_ingredients = graphene.List(IngredientType)
def resolve_all_categories(self, args, context, info):
return Category.objects.all()
def resolve_all_ingredients(self, args, context, info):
# We can easily optimize query count in the resolve method
return Ingredient.objects.select_related('category').all()
project_urls.py
from django.conf.urls import include, url
from django.contrib import admin
from graphene_django.views import GraphQLView
import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
url(r'^', include('mainapp.urls')),
]
Any help would be great.I am new to the coding stuff.
Thanks in advance.
You have to add the schema to your settings.py as seen here:
GRAPHENE = {
'SCHEMA': 'cookbook.schema.schema'
}
You need 2 schema.py files, one at the root level of the project and one in the app folder.
if you don't want to add GRAPHENE variable in settings.py then you can pass scheme parameter in GraphQLView.as_view() method call
from onlineshop_project.scheme import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True, schema=schema)),
]
You can check the documentation.
Have you added "graphene_django" in INSTALLED_APPS under settings.py file ?
Check here - https://docs.graphene-python.org/projects/django/en/latest/tutorial-plain/#update-settings

Custom template in django form wizard - NameError

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.