Django class based generic views: cannot import name TemplateView - python

Django fires exception cannot import name TemplateView how to fix this?
view.py :
from django.views.generic import TemplateView
class Monitor(TemplateView):
template_name = 'helo.html'
urls.py :
from monitor.views import Monitor
urlpatterns = patterns('',
(r'^admin/', Monitor.as_view()),
)

I don't know what Django version you are using, but only in Django 1.3 a class called TemplateView exists. Its import should be:
from django.views.generic.base import TemplateView

Related

AttributeError: 'function' object has no attribute 'as_view',in urls.py

I written this logic in my views.py, and I used class based views, Detail view:
#login_required
class profileView(DetailView):
model = profile
template_name = "users/profile.html"
and in urls.py file I've written this:
from django.urls import path,include
from . import views
from .views import profileView
urlpatterns = [
path('register/',views.register,name="register"),
path('login/',views.login_user,name="login_user"),
path('profile/',profileView.as_view(),name="profile_view"),
]
the django version that I'm using is 3.1 and python version is 3.8.
I hope that someone has an answer to my question.
You can not make use of #login_required for a class-based view, since that returns a function. You use the LoginRequiredMixin [Django-doc]:
from django.contrib.auth.mixins import LoginRequiredMixin
class profileView(LoginRequiredMixin, DetailView):
model = profile
template_name = 'users/profile.html'

I am getting a TypeError after adding TemplateView to my views folder

I am getting a TypeError after adding TemplateView to my views folder.
I've done a test project earlier and it worked pretty fine.I am a beginner in django
#views.py
```python
from django.shortcuts import render
from django.views.generic import TemplateView
class HomeResponse(TemplateView):
template_name = 'home.html'
#urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomeResponse, name='blog_name'),
]
```
[1]: https://i.stack.imgur.com/5XpRZ.png
urlpatterns = [
path('', views.HomeResponse.as_view(), name='blog_name'),
]
This shall work, you should access CBV's by calling as_view() method on them.

Trying to trace a circular import error in Django Python

I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.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.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

Custom templates for custom AdminSite Django

I have two admin sites and I want to have different custom templates on both of them
This is my admin.py file:
from django.contrib import admin
from django.contrib.admin import AdminSite
from .models import Equipo
#admin.register(Equipo)
class EquipoAdmin(admin.ModelAdmin):
list_display = ('codigo', 'nombre', 'contador', 'unidades')
class AdminMantenimiento(AdminSite):
site_header = "MANTENIMIENTO"
class EquipoAdminMantenimiento(admin.ModelAdmin):
list_display = ('codigo', 'nombre')
admin_site = AdminMantenimiento(name='Administrador Mantenimiento')
admin_site.register(Equipo, EquipoAdminMantenimiento)
This is my urls.py file:
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/',admin_site.urls)
]
If I override the templates as per Django documentation changes would be applied to both AdminSites. How can I set custom templates for the class extending AdminSite?
The only way I could think to do this would be to explicitly override the url of the admin page you want to customize and point it to a different template. For example to customize a template in admin2/ but not admin1/
from django.contrib import admin
from django.urls import path
from Mantenimiento.admin import admin_site
from app.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('admin2/app/model', TemplateView.as_view(template_name='model_admin.html')),
path('admin2/', admin_site.urls)
]
This will only work if the more specific url definition (admin2/app/model) comes before the less specific definition (admin2/)

'function' object has no attribute 'as_view'

I am trying to use class based views, and get a strange error. The way I'm using the view seems to be the normal way:
ingredients/models.py:
from django.db import models
from django.utils import timezone
class Ingredient(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
def get_prices():
purchases = self.purchase_set.all()
prices = [purchase.price for purchase in purchases]
ingredients/views.py:
from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.edit import CreateView
from .models import Ingredient, Purchase
def IngredientCreateView(CreateView):
model = Ingredient
fields = ['all']
ingredients/urls.py:
from django.conf.urls import patterns, include, url
from ingredients.views import IngredientCreateView
urlpatterns = patterns('',
url(r'^new_ingredient$', IngredientCreateView.as_view(), name='new-ingredient'),
)
I get
AttributeError at /ingredients/new_ingredient
'function' object has no attribute 'as_view'
I am on django 1.8.5. Why won't this view work? Thank you
IngredientCreateView should be a class.
So your views.py replace:
def IngredientCreateView(CreateView):
with:
class IngredientCreateView(CreateView):
In my case, the problem was that I tried to use a #decorator on the class-based view as if it was a function-based view, instead of #decorating the class correctly.
EDIT: From the linked page, here is a way to apply #login_required to a class-based view:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
IngredientCreateView is a function, not a class.
The following line
def IngredientCreateView(CreateView):
should be replace with
class IngredientCreateView(CreateView):
def Some_def_View(CreateView):
#should be replaced with
class SomeClassView(CreateView)
In addition to what is already said here, Check the file name and class name if it is same then you might have to import the class properly.
File name /api/A.py
class A:
//some methods
In your main class
//App main class
from api.A import A
I faced the same problem but this solution worked for me..
in views.py file in viewclass you can use viewsets instead of CreateView
from rest_framework import viewsets
class YourClassView(viewsets.ModelViewSet):
in urls.py file you can use this routing pattern
from django.conf.urls import url
from rest_framework import routers
router = routers.DefaultRouter()
router.register('books',YourClassView)
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls)
]

Categories