Django " AttributeError: 'function' object has no attribute 'as_view' " - django

I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error.
Here is the error ;
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
databases=databases,
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\berat.berkol\SystemConsole\SystemConsole\urls.py", line 25, in <module>
path('', UserUpdateView.as_view(), name='home'),
AttributeError: 'function' object has no attribute 'as_view'
And my project's urls.py ;
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from userupdate.views import UserUpdateView
app_name='userupdate'
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',include('django.contrib.auth.urls')),
path('', UserUpdateView.as_view(), name='home'),
]
and my views.py ;
from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userupdate.forms import UserPassForm
from userupdate.forms import LoginForm
from django.views.generic import View
from django.contrib.auth.views import LoginView
from django.contrib.auth.mixins import LoginRequiredMixin
#csrf_protect
class UserUpdateView(LoginRequiredMixin,View):
emplate_name='home.html'
def get(self, request, *args, **kwargs):
return render(request,'home.html')
##method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(UserUpdateView, self).dispatch(self, request, *args, **kwargs)
#csrf_protect
class LoginUser(LoginView):
template_name = 'home.html' # your template
from_class = LoginForm() # your form
def get_success_url(self):
'''Here the part where you can implement your login logic'''
now = timezone.now()
# Get current day date object
# like: 12/02/2019 00:00:00
today = now.replace(minute=0).replace(second=0).replace(microsecond=0)
# Get the client from the user object
client = self.request.user.cli
# Get all the user today's logins and count them
client_logins = models.ClientLogins.objects.filter(
client=client,
date__gte=today,
date__lte=today + timedelta(days=1)
).count()
if client_logins < 1: # Or: if not client_logins:
# create a login tracker record
models.ClientLogins.objects.create(
client=client,
date=now # Store the date where the user logged in the website
)
return reverse_lazy('home')
# Or redirect to: settings.LOGIN_REDIRECT_URL
request.session.get_expire_at_browser_close()
return super().get_success_url()
#csrf_protect
class passResetView(View):
def get(self,request):
form=UserUpdateForm()
return render('basarili')
def post(self,request):
passResetuser=self.model.objects.get(pk=2)
form=UserUpdateForm(request.POST,instance=passResetuser)
if form.is_valid():
username=form.cleaned_data('username')
password=form.cleaned_data('password')
number=form.cleaned_data('number')
message=form.cleaned_data('message')
context={'form':form}
return render(request,'home.html',context)
I don't know if it's required but here is my app's urls.py ;
from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from userupdate.views import HomeView
from django.contrib.auth import views as auth_views
app_name='userupdate'
urlpatterns = [
path('', views.UserUpdateView.as_view(template_name='home.html'), name='home'),
path('login/',
LoginView.as_view(
template_name='login.html'),
name="login"),
#path('passResetView',views.passResetView.as_view(template_name="home.html"),name='passResetView'),
path('passreset/',
passResetView.as_view(
template_name='passreset.html'),
name="PasswordReset"),
]
I haven't configured the form pages yet so ignore them for now.
I will build them with the FormView.
By the way I tried the TemplateView also but i didn't help its makes the same error.

You can't use #csrf_protect on a class-based view, or at least not directly. This decorator will return a function, and that function of course has no .as_view() method.
You can work with the #method_decorator [Django-doc], which will decorate the class:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
#method_decorator(csrf_exempt, name='dispatch')
class UserUpdateView(LoginRequiredMixin,View):
template_name = 'home.html'
# …
That being said, it is often not a good idea to make a CSRF exempt, since that makes your view vulnerable to Cross-Site Request Forgery [wiki].

Related

django.core.exceptions.ImproperlyConfigured

`I have watched a tutorial. But that was an old version of Django 1.1 and now I am using Django 4.1.So there is a problem that is telling me about django.core.exceptions.ImproperlyConfigured: "post/(?\d+)$" is not a valid regular expression: unknown extension ?<p at position 6. I didn't get it what it was
views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,DetailView,DeleteView,CreateView,UpdateView)
# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
#######################################
## Functions that require a pk match ##
#######################################
#login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
return redirect('post_detail', pk=pk)
#login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/comment_form.html', {'form': form})
#login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)
#login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail', pk=post_pk)
urls.py file
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('accounts/login/', views.LoginView.as_view(), name='login'),
path('accounts/logout/', views.LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
]
blog.urls file here
from django.urls import path,re_path
from blog import views
urlpatterns = [
path('',views.PostListView.as_view(),name='post_list'),
path('about/',views.AboutView.as_view,name='about'),
re_path(r'post/(?<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
path('post/new/',views.CreatePostView.as_view(),name='post_new'),
re_path(r'post/(?<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
re_path(r'post/(?<pk>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'),
path('drafts/',views.DraftListView.as_view(),name='post_draft_list'),
re_path(r'post/(?<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
re_path(r'comment/(?<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
re_path(r'comment/(?<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
re_path(r'post/(?<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
]
Here is the error message
C:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite>python manage.py migrate
Traceback (most recent call last):
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 235, in _compile
return re.compile(regex)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\re.py", line 252, in compile
return _compile(pattern, flags)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\re.py", line 304, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_parse.py", line 950, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_parse.py", line 443, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_parse.py", line 748, in _parse
raise source.error("unknown extension ?<" + char,
re.error: unknown extension ?<p at position 6
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite\manage.py", line 22, in <module>
main()
File "C:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 448, in execute
output = self.handle(*args, **options)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 97, in handle
self.check(databases=[database])
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 475, in check
all_issues = checks.run_checks(
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
return check_method()
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 477, in check
messages.extend(check_resolver(pattern))
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
return check_method()
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 477, in check
messages.extend(check_resolver(pattern))
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
return check_method()
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 387, in check
warnings.extend(self.pattern.check())
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 213, in check
warnings.extend(self._check_pattern_startswith_slash())
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 164, in _check_pattern_startswith_slash
regex_pattern = self.regex.pattern
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 142, in __get__
instance.__dict__["regex"] = instance._compile(pattern)
File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 237, in _compile
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: "post/(?<pk>\d+)$" is not a valid regular expression: unknown extension ?<p at position 6
I guess your regex is not valid.
Change it to
re_path(r'post/(?P<pk>\d+)/$',views.PostDetailView.as_view(),name='post_detail')
You should format your path according to correct regex path.
For example:
re_path(r'post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'),
re_path(r'post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
re_path(r'post/(?P<pk>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'),
re_path(r'post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
re_path(r'comment/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'),
re_path(r'comment/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'),
re_path(r'post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
A better way of doing this would be to use path itself, like so:
path('post/<int:pk>',views.PostDetailView.as_view(),name='post_detail'),
path('post/<int:pk>/edit/',views.PostUpdateView.as_view(),name='post_edit'),
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),
path('post/<int:pk>/comment/',views.add_comment_to_post,name='add_comment_to_post'),
path('comment/<int:pk>/approve/',views.comment_approve,name='comment_approve'),
path('comment/<int:pk>/remove/',views.comment_remove,name='comment_remove'),
path('post/<int:pk>/publish/',views.post_publish,name='post_publish'),

Django Rest Framework Module Not Found Error

I made sure that every step was followed correctly but this happened and I don't know how to solve this.
**ERROR:**
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000017F5090E620>
Traceback (most recent call last):
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Chrisannesuuuu\etona\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Chrisannesuuuu\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Chrisannesuuuu\etona\etona\etona\urls.py", line 3, in <module>
import etona.quickstart.views
ModuleNotFoundError: No module named 'etona.quickstart'
urls.py
from django.urls import include, path
from rest_framework import routers
import etona.quickstart.views
router = routers.DefaultRouter()
router.register(r'users', etona.quickstart.views.UserViewSet)
router.register(r'groups', etona.quickstart.views.GroupViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from etona.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
when typing python manage.py runserver, the error above appeared. How can i fix it? help please. Im trying to run the djangorestframework and connect it to angular to have a simple registration , so i followed the instructions on this website https://www.django-rest-framework.org/tutorial/quickstart/ but it doesn't seem to work on me. Maybe I missed something. Please help. Thanks.
Use quickstart.views instead of import etona.quickstart.views in urls.py and views.py
use in views.py change this line
from etona.quickstart.serializers import UserSerializer, GroupSerializer
to
from quickstart.serializers import UserSerializer, GroupSerializer
urls.py -from
etona.quickstart import views
to
from quickstart import views

Django Rest Framework AttributeError 'function' object has no attribute 'model' in router.register

I try my first Django API using Django Rest Framework. Everything was fine, but I change something and stuck in this AttributeError and don't understand what to do. my code looks like in tutorial and it is half past 4 am, I really need help.
so,
this is the callback
python3 manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/dev/test/demo/api_demo/api_demo/urls.py", line 7, in <module>
router.register(r'developers', views.DevViewSet)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 72, in register
base_name = self.get_default_base_name(viewset)
File "/home/dev/test/demo/lib/python3.5/site-packages/rest_framework/routers.py", line 152, in get_default_base_name
return queryset.model._meta.object_name.lower()
AttributeError: 'function' object has no attribute 'model'
this is url.py file
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'^api_demo', include(router.urls)),
]
this is views.py
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all
serializer_class = DevSerializer
and serializer
from rest_framework import serializers
from .models import Developers
class DevSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Developers
fields = ('name', 'surname', 'skills', 'education', 'employment_history')
and models
from django.db import models
class Education(models.Model):
university = models.CharField(max_length=50)
year_of_graduation = models.DateField()
class Empl_history(models.Model):
company = models.CharField(max_length=50)
role = models.CharField(max_length=30)
fr = models.DateField(verbose_name='from')
to = models.DateField()
class Developers(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=30)
skills = models.ForeignKey('Skills', on_delete=models.CASCADE)
education = models.ManyToManyField(Education)
employment_history = models.ManyToManyField(Empl_history)
class Skills(models.Model):
SKILLS_CHOICES = (
('p', 'Python'),
('d', 'Django'),
('drf', 'Django Rest Framework'),
)
skills_choices = models.CharField(max_length=2, choices=SKILLS_CHOICES,)
and in settings I added this 'rest_framework' and 'developers' to INSTALLED_APPS, also I add this code in the end
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'PAGE_SIZE': 10
}
Will be very thankfull for any advice and critic
For the queryset declaration you need to call the function and return the QuerySet rather then pass the reference to the function e.g. change queryset = Developers.objects.all to queryset = Developers.objects.all()
from rest_framework.viewsets import ModelViewSet
from developers.models import Developers
from .serializers import DevSerializer
class DevViewSet(ModelViewSet):
queryset = Developers.objects.all()
serializer_class = DevSerializer
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from developers import views
router = routers.DefaultRouter()
router.register(r'developers', views.DevViewSet)
urlpatterns = [
url(r'^admin', admin.site.urls),
url(r'', include(router.urls)),
]

ImportError: cannot import name 'BookList'

This a relative import error that got me crazy.
Here below is the directory tree and code:
books
├── admin.py
├── apps.py
├── forms.py
├── __init__.py
├── models.py
├── tests.py
├── urls.py
└── views.py
models.py
from django.db import models from django.core.urlresolvers import reverse
from . import views
class BookList(models.Model):
cover = models.ImageField(upload_to='cover/%Y/%m/%d')
# cover = models.CharField(max_length=200, blank=False)
title = models.CharField(max_length=100, blank=False)
author = models.CharField(max_length=50)
publisher = models.CharField(max_length=50)
review = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse(views.detail_book, kwargs={'id': self.id})
views.py (The code crashed at the line below pdb.set_trace())
import pdb
from django.views import generic
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
pdb.set_trace()
from .models import BookList
from .forms import BookListForm
class BookRecommend(generic.ListView):
model = BookList
template_name = 'books/books_list.html'
context_object_name = 'books'
paginate_by = 1
def add_book(request):
if request.method == 'POST':
form = BookListForm(request.POST)
if form.is_valid():
book = form.save()
return HttpResponseRedirect(reverse(detail_book, kwargs={id: book.id}))
else:
form = BookListForm()
return render(request, 'books/add_book.html', {'form': form})
def delete_book(request):
pass
def modify_book(request):
pass
def detail_book(request, id=1):
book = get_object_or_404(BookList, id=id)
return render(request, 'books/detail_book.html', {'book': book})
Trace back:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb621a2fc>
Traceback (most recent call last):
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/home/michael/Envs/DJ19/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/michael/Envs/DJ19/Profile/books/models.py", line 4, in <module>
from . import views
File "/home/michael/Envs/DJ19/Profile/books/views.py", line 9, in <module>
from .models import BookList
ImportError: cannot import name 'BookList'
There no obstacle at the previous version before i add some view functions.
Thanks in advance!

cannot import LoginView?

i'm learning some things about Django 1.9 and i want to make a login form but with class-based views.
This is mi view code:
from django.shortcuts import render
from django.contrib.auth.views import LoginView
class AlumnoLoginView(LoginView):
template_name = "alumno/login.html"
redirect_authenticated_user = True
And this is my urls code:
from django.conf.urls import url, include
from .views import AlumnoLoginView
app_name = 'alumno'
urlpatterns = [
url(r'^login/$', AlumnoLoginView.as_view(), name="login"),
]
This make an error:
ImportError: cannot import name LoginView
But if I delete the code inside urls nothing happens.
This is the full error trace (with François change):
Unhandled exception in thread started by <function wrapper at 0x7f044ad8ac08>
Traceback (most recent call last):
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run
self.check(display_num_errors=True)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/studentadmin/urls.py", line 21, in <module>
url(r'^alumno/', include('alumno.urls')),
File "/home/plafhz/Envs/StudentAdmin/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/urls.py", line 3, in <module>
from alumno.views import AlumnoLoginView
File "/home/plafhz/Envs/StudentAdmin/studentadmin/alumno/views.py", line 3, in <module>
from django.contrib.auth.views import LoginView as BaseLoginView
ImportError: cannot import name LoginView
What is wrong?
How I fix it?
Thank :)
Class-based views LoginView and LogoutView are introduced on Django 1.11 and function-based views 'login' and 'logout' are deprecated since then.
You can use class-based views LoginView and LogoutView like this:
from django.contrib.auth.views import LoginView, LogoutView
urlpatterns = [
url(r'^login/$', LoginView.as_view(template_name='...'), name="login"),
]
There's no view called LoginView in django.contrib.auth.views
I think you need.
from django.contrib.auth.views import login
LoginView only available from Django 1.11
cannot import LoginView?
You must be using lower version of django ..Login view supported only in 1.11 or higher version..
You need to install 1.11 or higher version
pip install django==1.11