django, name 'IndexView' is not defined - django

I am following this tutorial. At the moment I am at this point but when I start my server with python manage.py runserver 0.0.0.0:8000 and open the url in my browser, I receive following Error:
name 'IndexView' is not defined
This is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
from rest_framework_nested import routers
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
I don't know how to solve this problem, since I never saw myself even declaring this IndexView somewhere. It would be awesome if you guys could give me some suggestions on this one.
Edit:
my views.py
from django.shortcuts import render
# Create your views here.
from rest_framework import permissions, viewsets
from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data.'
}, status = status.HTTP_400_BAD_REQUEST)

You have to create that IndexView and import it in your urls.py.
Currently the interpreter complains since in the urls.py IndexView is unknown.
To create a new view you should create a new class in views.py, something like:
from django.views.generic.base import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
ps: please read the official Django docs, which is very good!

The IndexView class is in the boilerplate project's views file.
C:\...\thinkster-django-angular-boilerplate-release\thinkster_django_angular_boilerplate\views
Copy and paste that content into your project's views file.
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
class IndexView(TemplateView):
template_name = 'index.html'
#method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(IndexView, self).dispatch(*args, **kwargs)

in your urls.py
from .views import IndexView
url('^.*$', IndexView.as_view(), name='index'),
(.views or yourProject.views)
in your views.py
do what daveoncode wrote

Related

Django redirect another view from another app form

contact/views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
# return redirect('success')
return redirect('PostList') #another view from another app
return render(request, "contact.html", {'form': form})
# def successView(request):
# return HttpResponse('Success! Thank you for your message.')
contact/urls.py
from django.contrib import admin
from django.urls import path
from .views import contactView
urlpatterns = [
path('contact/', contactView, name='contact'),
# path('success/', successView, name='success'),
]
blog/views.py
from django.views import generic
from .models import Post, PostImage
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
# context['image_list'] = PostImage.objects.all()
# context['image_list'] = self.get_object().postimage_set.all()
context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug'))
return context
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I need the following in the SIMPLEST DRY manner possible; how do I write this redirect inside contact/views.py?
return redirect('PostList') #another view from another app
PostList is a class-based view from another app called blog. It is the homepage essentially.
for reference..
https://ordinarycoders.com/blog/article/django-messages-framework
In your project folder (eg, my_project/my_project) you should have a urls.py with something like this
path("admin/", admin.site.urls),
path("", include("blog.urls")),
path("", include("contact.urls"))
This allows django to look through all url files in the order listed. So long as all your url names and patterns are unique, then your view should be able to simply do
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse('home'))
'home' being the name value of the ListView.
(NB: if you have various applevel urls.py files with path(''... django will take the first one it hits)

why I have issues in importing views in the urls.py file?

from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:
employee
migrations folder
....other files
views.py
hrdjango
__init__.py
settings.py
urls.py
I feel like the urls can't access my views
this is the views.py
from .models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
urls.py
I am having unresolved import 'employee'message
Is this the project urls.py or the app-level urls.py? If this is your app level urls.py, then the import should be from . import views. If it is the project-level urls.py, then post up your file structure so we can see if the import structure is wrong.
I think the better solution would be to use separate urls.py file for separate apps and then include them to your root urls.
create a urls.py in your app.
in your root urls.py
from django.urls import path,include
urlpatterns = [
...,
...,
path('employee/', include('employee.urls')),
]

DRF - how to reverse a class based view in api_root

In Django REST Framework, I'm trying to add an API root to a views.py that has class based views.
Error:
$ http http://127.0.0.1:8000/api/
Error - django.urls.exceptions.NoReverseMatch: Reverse for 'SnippetListView' not found. 'SnippetList' is not a valid view function or pattern name.
backend/views.py
from backend.models import *
from backend.serializers import *
from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'snippets': reverse('SnippetList')
# 'snippets': reverse('SnippetListView')
# 'snippets': reverse('snippet-list')
# 'snippets': reverse('snippet_list')
})
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
backend/urls.py
from backend import views
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
path('', views.api_root),
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
]
Docs:
https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/#creating-an-endpoint-for-the-highlighted-snippets
You need to name the view url in order to use the reverse.
#urls.py
path('snippets/', views.SnippetList.as_view(), name='snippet-list'),
#views.py
'snippets': reverse('snippet-list', request=request, format=format)
The tutorial did not originally give names to the urls of the class based views.

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.

How do I insert a login if statement into FormWizard View for Django?

How would I insert "if request.user.is_authenticated" into the form wizard class below like shown in the example below? The idea is this view is my homepage and I would like to redirect to a different page if the user is already logged in.
Currently it is giving me "name 'request' is not defined" as an error message. I tried class BusinessWizard(request, SessionWizardView), but unfortunately it did not work. Maybe it is a simple oversight on my part. Thank you for your help!
views.py
class BusinessWizard(SessionWizardView):
if request.user.is_authenticated:
HttpResponseRedirect('some url')
else:
#some code and functions etc
The easiest way is to add the login_required user_passes_test decorator in the urlconf:
from django.conf.urls import patterns
from django.contrib.auth.decorators import user_passes_test
from .views import BusinessWizard
urlpatterns = patterns('',
(r'^wizard/$', user_passes_test(lambda user: user.is_anonymous(), 'some url', None)(BusinessWizard.as_view())),
)
Reference:
https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-in-urlconf
https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.decorators.user_passes_test
If you want to define your own decorator you can use the following snippet:
from functools import wraps
from django.conf.urls import patterns
from django.http import HttpResponseRedirect
from .views import BusinessWizard
def anonymous_required(redirect_url=None):
"""
Decorator that redirects authenticated users to a different URL.
"""
def decorator(view_func):
#wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.user.is_anonymous():
return view_func(request, *args, **kwargs)
return HttpResponseRedirect(redirect_url)
return _wrapped_view
return decorator
urlpatterns = patterns('',
(r'^wizard/$', anonymous_required('some url')(BusinessWizard.as_view())),
)