i am not able to run this code
viwes.py
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from . models import Task
from . forms import Taskform
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView,DeleteView
class Tasklistview(ListView):
model = Task
template_name = 'home.html'
context_object_name = 'task'
class Detailview(DetailView):
model=Task
template_name = "details.html"
context_object_name = 'task'
class Updateview(UpdateView):
model = Task
template_name = "update.html"
context_object_name = "task"
fields = ('name', 'priority', 'date')
def get_success_url(self):
return reverse_lazy('todoapp:cbvdetail',kwargs={'pk':self.object.id})
class Deleteview(DetailView):
model = Task
template_name = 'delete.html'
success_url = reverse_lazy('todoapp:home')
urls.py
from django.urls import path
from . import views
app_name='todoapp'
urlpatterns = [
path('',views.home,name='home'),
path('delete/<int:id>/',views.delete,name='delete'),
path('edit/<int:id>/',views.update,name='update'),
path('cbvhome/',views.Tasklistview.as_view(),name='home'),
path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'),
path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'),
]
when i run this code i am getting a error this page isn't working right now
i am not able to run this code
gngnitgbnugriujvnnvtvnviuvntnvtvitu
You are inheriting you Deleteview from a DetailView, not a DeleteView, hence the error:
from django.views.generic import DeleteView
class Deleteview(DeleteView):
model = Task
template_name = 'delete.html'
success_url = reverse_lazy('todoapp:home')
I would however strongly advise not to give your views names like Deleteview, since it is easy to confuse this with the Django builtin class-based views. Usually the model is specified in the name, so TaskDeleteView instead of Deleteview:
class TaskDeleteView(DeleteView):
model = Task
template_name = 'delete.html'
success_url = reverse_lazy('todoapp:home')
Related
I've been attempting to construct a multi-step form using the Django session wizard for hours, but I keep getting the error, AttributeError: 'function' object has no property 'as_view'. I'm not sure why this mistake occurred. Any ideas?
views
from django.shortcuts import render
from formtools.wizard.views import SessionWizardView
from .forms import WithdrawForm1, WithdrawForm2
class WithdrawWizard(SessionWizardView):
template_name = 'withdraw.html'
form_list = [WithdrawForm1, WithdrawForm2]
def done(self, form_list, **kwargs):
form_data = [form.cleaned_data for form in form_list]
return render(self.request, 'done.html', {'data': form_data})
forms
from django import forms
from .models import Investment, Withdraw
from .models import WithdrawStepOne, WithdrawStepTwo
class WithdrawForm1(forms.ModelForm):
class Meta:
model = WithdrawStepOne
fields = ['investment_id',]
class WithdrawForm2(forms.ModelForm):
class Meta:
model = WithdrawStepTwo
fields = [
'proof_of_address',
'user_pic'
]
urls
from django.urls import path
from .forms import WithdrawForm1, WithdrawForm2
from . import views
urlpatterns = [
path('withdraw/', views.WithdrawWizard.as_view(), name='withdraw'),
]
You used #login_required decorator on WithdrawWizard class, but the decorator works only for function based views.
Use LoginRequiredMixin for class based views.
i can't call my detail class using reverse_lazy
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from . models import Task
from . forms import Taskform
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
class Tasklistview(ListView):
model = Task
template_name = 'home.html'
context_object_name = 'task'
class Detailview(DetailView):
model=Task
template_name = "details.html"
context_object_name = 'task'
class Updateview(UpdateView):
model = Task
template_name = "update.html"
context_object_name = "task"
fields = ('name', 'priority', 'date')
def get_success_url(self):
return reverse_lazy("cbvdetail",kwargs={'pk':self.object.id})
urls.py
from django.urls import path
from . import views
app_name='todoapp'
urlpatterns = [
path('',views.home,name='home'),
# path('details', views.details,name='ere')
path('delete/<int:id>/',views.delete,name='delete'),
path('edit/<int:id>/',views.update,name='update'),
path('cbvhome/',views.Tasklistview.as_view(),name='home'),
path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'),
path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'),
]
i want to resolve this
You specified an app_name in the urls.py file. That means you need to prefix the name of the view with that app label, so:
def get_success_url(self):
return reverse_lazy('todoapp:cbvdetail', kwargs={'pk':self.object.id})
If you override get_success_url, it does not make much sense to work with reverse_lazy, since that method will (normally) only be triggered in case the urls are already loaded, you can thus work with:
from django.urls import reverse
# ⋮
def get_success_url(self):
return reverse('todoapp:cbvdetail', kwargs={'pk':self.object.id})
I was just getting started on using Django's rest framework. The problem I faced is that Rest Framework didn't fetch from the right URL: I want it to get the list of Todos but it returned the URL where the API was located.
(Might be easy for many of you, but I am completely fresh to drf)
serializers
from .models import Todo
from rest_framework import serializers
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Todo
fields = ['title', 'desc', 'level', 'created']
urls
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'todos', views.TodoViewSet)
urlpatterns = [
path('', views.IndexView.as_view(), name='todo_all'),
path('api/', include(router.urls)),
]
views
from django.views.generic.base import TemplateView
from rest_framework import viewsets
from .models import Todo
from .serializers import TodoSerializer
class IndexView(TemplateView):
template_name = "todo/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['todos'] = Todo.objects.all()
return context
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
What I want Rest to get:
What Rest actually displayed:
Like, I want the data of the todos, not the URL. Thanks in advance.
You have used HyperlinkedModelSerializer. Try to use ModelSerializer instead.
from .models import Todo
from rest_framework import serializers
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ['title', 'desc', 'level', 'created']
I have a ListView class in views.py, I want to add a condition if the authenticated user displays another template
urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
PostListView,
)
urlpatterns = [
path('', PostListView.as_view(), name='index'),
]
Views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import (
ListView,
)
from .models import Post
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
class PostListView(ListView):
model = Post
template_name = 'page/index.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 7
i want to add
if self.request.user.is_authenticated:
template_name = 'page/index.html'
else:
template_name = 'page/home.html'
Django 2.2.x
You can override the get_template_names function [Django-doc]:
class PostListView(ListView):
model = Post
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 7
def get_template_names(self):
if self.request.user.is_authenticated:
return ['page/index.html']
else:
return ['page/home.html']
As the documentation says, this function:
Returns a list of template names to search for when rendering the template. The first template that is found will be used.
If template_name is specified, the default implementation will return a list containing template_name (if it is specified).
That being said, if you do not plan to render the list on your home.html page, it might be better to perform a redirect to another page, instead of just rendering a page. Otherwise, if you later want to add more content to your home.html page, you will each time need to update all the views that render this.
The basic implementation [GitHub] in the TemplateResponseMixin [Django-doc] is thus:
def get_template_names(self):
"""
Return a list of template names to be used for the request. Must return
a list. May not be called if render_to_response() is overridden.
"""
if self.template_name is None:
raise ImproperlyConfigured(
"TemplateResponseMixin requires either a definition of "
"'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
I seem to be having a TypeError problem on my program using Django.
Views.py
from __future__ import unicode_literals
from django.shortcuts import render
from .models import Anteproyecto
from .forms import formulario_anteproyecto
from django.views.generic import CreateView
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin
class CrearAnteproyecto(SuccessMessageMixin, CreateView):
model = Anteproyecto
form_class = formulario_anteproyecto
template_name = "crear_anteproyectos.html"
success_url = reverse_lazy('crear_anteproyecto')
success_message = "El anteproyecto ha sido creado"
def form_valid(self, form):
self.object = form.save()
Forms. py
from django import forms
from .models import Anteproyecto
class formulario_anteproyecto:
class Meta:
model = Anteproyecto
fields = ['titulo', 'resumen','estado','palabras_claves']
Models.py
from __future__ import unicode_literals
from django.db import models
from taggit.managers import TaggableManager
from Actividades.models import Actividades
ESTADOS = (('Activo', 'Activo'), ('Inactivo', 'Inactivo'))
class Anteproyecto(models.Model):
titulo = models.CharField(max_length=100, verbose_name='TÃtulo')
estado = models.CharField(max_length=8, verbose_name="Estado", choices=ESTADOS, default='Activo')
resumen = models.CharField(max_length=500, verbose_name="Resumen")
claves = TaggableManager(verbose_name = "Palabras claves")
actividad = models.ForeignKey(Actividades, on_delete=models.CASCADE)
class Meta :
verbose_name = 'Anteproyecto'
verbose_name_plural = 'Anteproyectos'
def __str__(self):
return self.titulo
Importing the app "Actividades" to be used as a reference in models. Using as well Django-taggit to use a field that can work as tags, still not implemented due to TypeError. Html is a bootstrap template which prints the form as a paragraph. There are other creates in different views that use the same coding as this however this one is giving me the error.
Your formulario_anteproyecto does not inherit from anything. It needs to inherit from forms.ModelForm.