TypeError: as_view() - Django - python

I got an error.
And i have no ideia how to fix it, take a look, this is the error:
TypeError: as_view() takes 1 positional argument but 2 were given
This as you can see is the code of my "model.py" page.
from django.db import models
from django.contrib.gis.db import models
class RoadsLines(models.Model):
gid = models.IntegerField()
geom = models.MultiLineStringField()
def __str__(self): # __unicode__ on Python 2
return '%s %s' % (self.gid, self.geom)
This as you can see is the code of my "views.py" page.
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from rest_framework import generics
from world.models import RoadsLines
from world.serializers import RoadsLinesSerializer
class ListCreateRoadsLines(generics.ListCreateAPIView):
queryset = RoadsLines.objects.all()
serializer_class = RoadsLinesSerializer
This as you can see is the code of my "urls.py" page.
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
from world import views
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'Roads', views.ListCreateRoadsLines)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls', namespace='rest_framework'))
]
What am I doing wrong?
Thank you in advance!

ListCreateRoadsLines is a view, not a viewset. You should include it in your url patterns, instead of trying to register it:
urlpatterns = [
url(r'^Roads$', views.ListCreateRoadsLines.as_view()),
url(r'^', include(router.urls)),
url(r'^api/', include('rest_framework.urls',
namespace='rest_framework'))
]

Related

Circular import error when I open the Django server

When I open the server(Django) I get this error: "The included URLconf 'admin.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import."
I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py.
App urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('/api', include('crud.urls')),
]
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserSerializer
class UserView(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response({"users": users})
serializer.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
email = serializers.EmailField()
password = serializers.CharField(max_length=255)
disease = serializers.CharField(max_length=255)
logo = serializers.TextField()
crud urls.py
Here, the issue is at the second line: if I remove that line I fix the error
from django.urls import path
from .views import UserView
app_name='crud'
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('users/', UserView.as_view()),
]
Please add error trace for better understanding of the issue.
Meanwhile try changing this:
path('/api', include('crud.urls'))
to:
path('api/', include('crud.urls')),
and
from .views import UserView
to:
from crud import views
urlpatterns = [
path('users/', views.UserView.as_view()),
]

Django-Oscar URLs for Django 2.0?

Django-Oscar has apparently been updated to Django 2.0. I am new to Django, I am not sure how I would update the URLs that are mentioned in the Oscar Tutorial:
from django.conf.urls import include, url
from django.contrib import admin
from oscar.app import application
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
# The Django admin is not officially supported; expect breakage.
# Nonetheless, it's often useful for debugging.
url(r'^admin/', include(admin.site.urls)),
url(r'', include(application.urls)),
]
This is the url that is currently available:
urlpatterns = [
path('admin/', admin.site.urls),
]
So, do this mean that I would change the django-oscar URls to?:
path(r'^i18n/', include('django.conf.urls.i18n')),
The documentation on readthedocs is out of date for some reason - here's the most recent version on Github which provides configuration for Django 2.
To use path you need to remove the regular expression syntax in the URLs. The use of include() also has been dropped for url configs passed directly, so you end up with:
from django.urls import include, path
from django.contrib import admin
from oscar.app import application
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('admin/', admin.site.urls),
path('', application.urls),
]
Django oscar always put their URLs in their app directory's apps.py file and then include that URL's to project level urls.py file, that's the design decision for Django oscar. But I would recommend you use path() than url() as this will help you to avoid the complexity.
##django-oscar/src/oscar/apps/basket/apps.py
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext_lazy as _
from oscar.core.application import OscarConfig
from oscar.core.loading import get_class
class BasketConfig(OscarConfig):
label = 'basket'
name = 'oscar.apps.basket'
verbose_name = _('Basket')
namespace = 'basket'
def ready(self):
self.summary_view = get_class('basket.views', 'BasketView')
self.saved_view = get_class('basket.views', 'SavedView')
self.add_view = get_class('basket.views', 'BasketAddView')
self.add_voucher_view = get_class('basket.views', 'VoucherAddView')
self.remove_voucher_view = get_class('basket.views', 'VoucherRemoveView')
def get_urls(self):
urls = [
url(r'^$', self.summary_view.as_view(), name='summary'),
url(r'^add/(?P<pk>\d+)/$', self.add_view.as_view(), name='add'),
url(r'^vouchers/add/$', self.add_voucher_view.as_view(),
name='vouchers-add'),
url(r'^vouchers/(?P<pk>\d+)/remove/$',
self.remove_voucher_view.as_view(), name='vouchers-remove'),
url(r'^saved/$', login_required(self.saved_view.as_view()),
name='saved'),
]
return self.post_process_urls(urls)
then imported by project level config.py file
##django-oscar/src/oscar/config.py
# flake8: noqa, because URL syntax is more readable with long lines
from django.apps import apps
from django.conf import settings
from django.conf.urls import url
from django.urls import reverse_lazy
from django.views.generic.base import RedirectView
from oscar.core.application import OscarConfig
from oscar.core.loading import get_class
class Shop(OscarConfig):
name = 'oscar'
def ready(self):
from django.contrib.auth.forms import SetPasswordForm
self.catalogue_app = apps.get_app_config('catalogue')
self.customer_app = apps.get_app_config('customer')
self.basket_app = apps.get_app_config('basket')
self.checkout_app = apps.get_app_config('checkout')
self.search_app = apps.get_app_config('search')
self.dashboard_app = apps.get_app_config('dashboard')
self.offer_app = apps.get_app_config('offer')
self.password_reset_form = get_class('customer.forms', 'PasswordResetForm')
self.set_password_form = SetPasswordForm
def get_urls(self):
from django.contrib.auth import views as auth_views
from oscar.views.decorators import login_forbidden
urls = [
url(r'^$', RedirectView.as_view(url=reverse_lazy('catalogue:index')), name='home'),
url(r'^catalogue/', self.catalogue_app.urls),
url(r'^basket/', self.basket_app.urls),
url(r'^checkout/', self.checkout_app.urls),
url(r'^accounts/', self.customer_app.urls),
url(r'^search/', self.search_app.urls),
url(r'^dashboard/', self.dashboard_app.urls),
url(r'^offers/', self.offer_app.urls),
# Password reset - as we're using Django's default view functions,
# we can't namespace these urls as that prevents
# the reverse function from working.
url(r'^password-reset/$',
login_forbidden(
auth_views.PasswordResetView.as_view(
form_class=self.password_reset_form,
success_url=reverse_lazy('password-reset-done'),
template_name='oscar/registration/password_reset_form.html'
)
),
name='password-reset'),
url(r'^password-reset/done/$',
login_forbidden(auth_views.PasswordResetDoneView.as_view(
template_name='oscar/registration/password_reset_done.html'
)),
name='password-reset-done'),
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$',
login_forbidden(
auth_views.PasswordResetConfirmView.as_view(
form_class=self.set_password_form,
success_url=reverse_lazy('password-reset-complete'),
template_name='oscar/registration/password_reset_confirm.html'
)
),
name='password-reset-confirm'),
url(r'^password-reset/complete/$',
login_forbidden(auth_views.PasswordResetCompleteView.as_view(
template_name='oscar/registration/password_reset_complete.html'
)),
name='password-reset-complete'),
]
return urls
Oscar's idea is to modularize every app. That's why it stores app's all url to apps.py in every app folder and include that to project level config.py file.

Django REST Framework move all urls to router

I have little experience in python. Please could you help me. There is an old project which has the following structure
# -*- coding: utf-8 -*-
import re
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from rest_framework import routers # i added it
import home.views
router = routers.DefaultRouter() # i added it
urlpatterns = [
url(r'^$', home.views.HomeView.as_view()),
url(r'^api/v2/', include('api.v2.urls', namespace='api-v2')),
url(r'^help/', include('helps.urls', namespace='helps')),
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), # i added it
url(r'^', include(router.urls)) # i added it
]
I would like to make REST API so that you can see all possible routes. So i try to add rest_framework.urls. As I understood it is necessary to use VeiwSet to add it to router. I do not quite understand how I can use what I already have to see links in a REST API? Or for each link i need to create a Veiwset?
For example api.v2.urls contains next: (similar in helps.urls, etc)
# -*- coding: utf-8 -*-
from django.conf.urls import url
import api.v2.views
urlpatterns = [
url(r'^data/info', api.v2.views.info_data),
url(r'^visits$', api.v2.views.visits),
url(r'^additional_info/', api.v2.views.additional_info),
]
a Viewset combines several views into a same class. You can have it for example to provide CRUD api for one of your Django model.
I recommend to read http://www.django-rest-framework.org/api-guide/viewsets/
You can register the Viewset in a router. I will generate an url for every view of the views
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing user instances.
"""
serializer_class = UserSerializer
queryset = User.objects.all()
in urls.py
from myapp.views import UserViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='user')
urlpatterns = [
...
url(r'^', include(router.urls))
]
If you print the router.urls
for url in router.urls: print(url)
You will see something like:
<RegexURLPattern user-list ^ users/$>
<RegexURLPattern user-list ^ users\.(?P<format>[a-z0-9]+)/?$>
<RegexURLPattern user-detail ^ users/(?P<pk>[^/.]+)/$>
<RegexURLPattern user-detail ^ users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$>
It shows the url for every view of the viewset
You can also have regular View for your REST API. http://www.django-rest-framework.org/api-guide/views/ which can be added to your urls like any usual Django view.
I hope it helps
I believe you will need to declare explicitly the urls that you want to show:
This is what i have in one of my projects:
urlpatterns = [
# Your stuff: custom urls includes go here
url(r'^api/$', api_root, name='api-root'),
]
#api_view(['GET'])
#permission_classes((IsAdminUser, ))
def api_root(request, format=None):
return Response({
'apples': reverse('my-api:oranges-all'),
'oranges': reverse('my-api:oranges-list'),
})

How to connect with Django REST framework to front-end

I'm new on Django REST Framework. I have an index.html where I have simple form for adding items and back-end with Django. I can't understand, how I can connect index.html to Django REST Framework.
I have the next code-files:
models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=100)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Book
from rest_framework import viewsets
from .serializers import BookSerializer
class Index(TemplateView):
template_name = "index.html"
def get_context_data(self):
context = super(Index, self).get_context_data()
return context
class BookViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Book.objects.all().order_by('title')
serializer_class = BookSerializer
urls.py
from django.conf.urls import url, include
from rest_framework import routers
from myapp import views
router = routers.DefaultRouter()
router.register(r'books', views.BookViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
]
serializers.py
from .models import Book
from rest_framework import serializers
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ('title','category')
And if I run localhost:8000/index I get an error 'Page not found'. I can't understand how correct I should include my html pages to the django code. Should I use a router.register for this?
Let's start by defining what django-rest-framework is and what it is not.
It is a nice toolkit to build web APIs. This means that you can define several endpoints (urls) that will handle incoming requests and will return a response in JSON or XML format.
It is not an html rendering tool though. This means that you can't return a response that contains html code to be rendered as a page in the browser. It will return pure json or xml data.
Now, your questions consists of 2 problems:
You can't access the index.html page.
You don't know how to connect this page with the books endpoint.
Regarding problem 1
Check the TEMPLATES settings. Where is your index.html placed? Does django know where to find it? Check out the TEMPLATES setting and assure you have set it up correctly.
Regarding problem 2
Because of the fact that the django-rest-framework endpoint handles incoming requests, you need to generate such a request. But if you will simply access the endpoint in your browser, the page will load/reload and you will see the data from your endpoint in json form on your page.
For your page to remain the same, but at the same time to make a request to your endpoint, you need to use ajax (Asynchronous JavaScript and XML) from within your index.html page. You can emit an ajax request by using one of the following:
With pure JavaScript, by means of XMLHttpRequest class. See this SO question and answers to see how this is made.
If you use jQuery, it has a jQuery.ajax() method to make an ajax request.
If you use any other frontend framework (angular, backbone, ember, etc.), all they have an implementation of ajax calls. Check their documentation for that.
And basically that's it. Good luck!
Could you try putting the api url after your index like this?
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^', include(router.urls)),
]
Or why not use /api/ for your REST Api urls:
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
]
And be sure that you have added 'rest_framework', to INSTALLED_APPS
EDIT:
To access /index/ you must fix your urls.py:
urlpatterns = [
url(r'^index/$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Django NameError: name 'views' is not defined

I am working through this tutorial on rapid site development with Django.
I have followed it exactly (as far as I can see), but get the following error when I try to view the index page:
NameError at /name 'views' is not defined
Exception location: \tuts\urls.py in <module>, line 12
Here's urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
)
Here's views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
items = Item.objects.order_by("-publish_date")
now = datetime.datetime.now()
return render(request,'portfolio/index.html', {"items": items, "year": now.year})
And here's models.py:
from django.db import models
# Create your models here.
class Item(models.Model):
publish_date = models.DateField(max_length=200)
name = models.CharField(max_length=200)
detail = models.CharField(max_length=1000)
url = models.URLField()
thumbnail = models.CharField(max_length=200)
I also have a basic index.html template in place. From looking around I think I need to import my view somewhere.
But I'm completely new to Django so I have no clue. Any ideas?
The error line is
url(r'^$', views.index, name='index'),
#----------^
Here views is not defined, hence the error. You need to import it from your app.
in urls.py add line
from <your_app> import views
# replace <your_app> with your application name.
from .views import index
here we have to import views model classes on urls model so above sentence import your view model class on urls model.
add this code in urls.py
If you are using rest_framework in django then import:
from rest_framework import views

Categories

Resources