I am getting list index out of range error in my application. It is an e-learning system and the error occurs when a student tries to enroll in for a course. I am using django 1.8.6. This is my error.
IndexError at /students/course/12/
list index out of range
Request Method: GET
Request URL: http://127.0.0.1:8000/students/course/12/
Django Version: 1.8.6
Exception Type: IndexError
Exception Value: list index out of range
Exception Location: D:\DjangoSchoolProject\env\educa\lib\site-
packages\django\db\models\query.py in __getitem__, line 201
Python Executable: D:\DjangoSchoolProject\env\educa\Scripts\python.exe
Python Version: 3.6.5
Python Path:
['D:\\DjangoSchoolProject\\educa',
'D:\\DjangoSchoolProject\\env\\educa\\Scripts\\python36.zip',
'D:\\DjangoSchoolProject\\env\\educa\\DLLs',
'D:\\DjangoSchoolProject\\env\\educa\\lib',
'D:\\DjangoSchoolProject\\env\\educa\\Scripts',
'c:\\users\\greendelta\\appdata\\local\\programs\\python\\python36-
32\\Lib',
'c:\\users\\greendelta\\appdata\\local\\programs\\python\\python36-
32\\DLLs',
'D:\\DjangoSchoolProject\\env\\educa',
'D:\\DjangoSchoolProject\\env\\educa\\lib\\site-packages']
and this is the python file I am using to enroll student.
from django import forms
from courses.models import Course
class CourseEnrollForm(forms.Form):
course = forms.ModelChoiceField(queryset=Course.objects.all(),
widget=forms.HiddenInput)
Any help will be greatly appreciated. I have also included my view.py file below
Here is my view.py file.
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import get_object_or_404, redirect
from django.views.generic.base import TemplateResponseMixin, View
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.forms.models import modelform_factory
from django.db.models import Count
from django.apps import apps
from django.core.cache import cache
from braces.views import LoginRequiredMixin, PermissionRequiredMixin, \
CsrfExemptMixin, JsonRequestResponseMixin
from students.forms import CourseEnrollForm
from .models import Subject, Course, Module, Content
from .forms import ModuleFormSet
class OwnerMixin(object):
def get_queryset(self):
qs = super(OwnerMixin, self).get_queryset()
return qs.filter(owner=self.request.user)
class OwnerEditMixin(object):
def form_valid(self, form):
form.instance.owner = self.request.user
return super(OwnerEditMixin, self).form_valid(form)
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
model = Course
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_course_list')
template_name = 'courses/manage/course/form.html'
class ManageCourseListView(OwnerCourseMixin, ListView):
template_name = 'courses/manage/course/list.html'
class CourseCreateView(PermissionRequiredMixin,
OwnerCourseEditMixin,
CreateView):
permission_required = 'courses.add_course'
class CourseUpdateView(PermissionRequiredMixin,
OwnerCourseEditMixin,
UpdateView):
permission_required = 'courses.change_course'
class CourseDeleteView(PermissionRequiredMixin,
OwnerCourseMixin,
DeleteView):
success_url = reverse_lazy('manage_course_list')
template_name = 'courses/manage/course/delete.html'
permission_required = 'courses.delete_course'
class CourseModuleUpdateView(TemplateResponseMixin, View):
template_name = 'courses/manage/module/formset.html'
course = None
def get_formset(self, data=None):
return ModuleFormSet(instance=self.course,
data=data)
def dispatch(self, request, pk):
self.course = get_object_or_404(Course, id=pk, owner=request.user)
return super(CourseModuleUpdateView, self).dispatch(request, pk)
def get(self, request, *args, **kwargs):
formset = self.get_formset()
return self.render_to_response({'course': self.course,
'formset': formset})
def post(self, request, *args, **kwargs):
formset = self.get_formset(data=request.POST)
if formset.is_valid():
formset.save()
return redirect('manage_course_list')
return self.render_to_response({'course': self.course,
'formset': formset})
class ContentCreateUpdateView(TemplateResponseMixin, View):
module = None
model = None
obj = None
template_name = 'courses/manage/content/form.html'
def get_model(self, model_name):
if model_name in ['text', 'video', 'image', 'file']:
return apps.get_model(app_label='courses', model_name=model_name)
return None
def get_form(self, model, *args, **kwargs):
Form = modelform_factory(model,
exclude=['owner', 'order', 'created', 'updated'])
return Form(*args, **kwargs)
def dispatch(self, request, module_id, model_name, id=None):
self.module = get_object_or_404(Module,
id=module_id,
course__owner=request.user)
self.model = self.get_model(model_name)
if id:
self.obj = get_object_or_404(self.model,
id=id,
owner=request.user)
return super(ContentCreateUpdateView,
self).dispatch(request, module_id, model_name, id)
def get(self, request, module_id, model_name, id=None):
form = self.get_form(self.model, instance=self.obj)
return self.render_to_response({'form': form,
'object': self.obj})
def post(self, request, module_id, model_name, id=None):
form = self.get_form(self.model,
instance=self.obj,
data=request.POST,
files=request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.owner = request.user
obj.save()
if not id:
# new content
Content.objects.create(module=self.module,
item=obj)
return redirect('module_content_list', self.module.id)
return self.render_to_response({'form': form,
'object': self.obj})
class ContentDeleteView(View):
def post(self, request, id):
content = get_object_or_404(Content,
id=id,
module__course__owner=request.user)
module = content.module
content.item.delete()
content.delete()
return redirect('module_content_list', module.id)
class ModuleContentListView(TemplateResponseMixin, View):
template_name = 'courses/manage/module/content_list.html'
def get(self, request, module_id):
module = get_object_or_404(Module,
id=module_id,
course__owner=request.user)
return self.render_to_response({'module': module})
class ModuleOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def post(self, request):
for id, order in self.request_json.items():
Module.objects.filter(id=id,
course__owner=request.user).update(order=order)
return self.render_json_response({'saved': 'OK'})
class ContentOrderView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def post(self, request):
for id, order in self.request_json.items():
Content.objects.filter(id=id,
module__course__owner=request.user).update(order=order)
return self.render_json_response({'saved': 'OK'})
class CourseListView(TemplateResponseMixin, View):
model = Course
template_name = 'courses/course/list.html'
def get(self, request, subject=None):
subjects = cache.get('all_subjects')
if not subjects:
subjects = Subject.objects.annotate(total_courses=Count('courses'))
cache.set('all_subjects', subjects)
all_courses = Course.objects.annotate(total_modules=Count('modules'))
if subject:
subject = get_object_or_404(Subject, slug=subject)
key = 'subject_{}_courses'.format(subject.id)
courses = cache.get(key)
if not courses:
courses = all_courses.filter(subject=subject)
cache.set(key, courses)
else:
courses = cache.get('all_courses')
if not courses:
courses = all_courses
cache.set('all_courses', courses)
return self.render_to_response({'subjects': subjects,
'subject': subject,
'courses': courses})
class CourseDetailView(DetailView):
model = Course
template_name = 'courses/course/detail.html'
def get_context_data(self, **kwargs):
context = super(CourseDetailView, self).get_context_data(**kwargs)
context['enroll_form'] = CourseEnrollForm(initial={'course':self.object})
return context
I still do not have a working solution to my problem.
Kinda hard give any good answer without the entire code, please post your view.py thats render your page
This usualy happends when your try to access array with fixed position without checking if this exists or have this currently position
someArray = [1,2,3]
print(someArray[200])
Probabily you trying to acess your queryset or any array with wrong position
Related
I am trying to perform an action from superuser accept/reject the task, but after login from superuser it show the error. even if i logged in from non superuser if show the same error
403 Forbidden
i am trying first time perform action from superuser i don't know how can i fix this issue
View.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
def test_func(self):
if self.request.user == User.is_superuser:
return True
else:
return False
template_name = 'approve.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self, request):
Urls.py
urlpatterns = [
path('approve',Approval.as_view(), name='approve')
]
You check if the user is a superuser with:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
template_name = 'approve.html'
def test_func(self):
return self.request.user.is_superuser
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {'all_saloon': all_saloon})
The all_saloon is however strange: it means that if it is a list or QuerySet it will each time work with the same data, and thus if later a new Saloon is constructed, it will not take that into account.
You can alter the handle_no_permission function to determine what to do in case the test fails:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.shortcuts import redirect
class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
template_name = 'approve.html'
def test_func(self):
return self.request.user.is_superuser
def handle_no_permission(self):
return redirect('name-of-some-view')
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {'all_saloon': all_saloon})
Likely you want to work with a ListView [Django-doc] instead.
I want to check if user in true editUser before open url and create post,
urls.py", line 13, in
path('new/', PostCreateView.as_view(), name='new_post'),
AttributeError: 'NoneType' object has no attribute 'as_view'
def notLoggedUsers(view_func):
def wrapper_func(request,*args,**kwargs):
if not request.user.profile.editUser:
return redirect('index')
else:
return view_func(request,*args,**kwargs)
return wrapper_func
#notLoggedUsers
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = 'crud/new_post.html'
form_class = PostForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Firstly your decorator has a small mistake, the indentation for return wrapper_func is wrong. Next to decorate class based views you should use method_decorator [Django docs] and specify the method of the class that should be decorated (Decorate the dispatch method if it needs to decorate the complete view):
from django.utils.decorators import method_decorator
def notLoggedUsers(view_func):
def wrapper_func(request, *args, **kwargs):
if not request.user.profile.editUser:
return redirect('index')
else:
return view_func(request, *args, **kwargs)
return wrapper_func
#method_decorator(notLoggedUsers, name='dispatch')
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
template_name = 'crud/new_post.html'
form_class = PostForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
You should not decorate your class-based view with a decorator that returns a function, since then that function has no .as_view attribute.
Django has some tooling to apply a decorator to a function of the class-based view, we can however also implement a mixin and work with that mixin:
from django.contrib.auth.mixins import UserPassesTestMixin
from django.shortcuts import redirect
class EditUserPermissionPlugin(LoginRequiredMixin, UserPassesTestMixin):
def test_func(self):
try:
return self.user.profile.editUser
except Profile.DoesNotExist:
return False
def handle_no_permission(self):
return redirect('index')
Then we can use this for our view:
class SomeCreateView(EditUserPermissionPlugin, CreateView):
# …
I have this code in urls
from .views import testview
urlpatterns = [
path('test/<pk>', testview.as_view(), name='test')
]
And this is my view :
class testview(FormView):
template_name = 'test/test.html'
form_class = ExampleForm
def form_valid(self, form):
cl = form.cleaned_data
book= Book(user_id='pk',
book = cl['book'],
price = book.price )
return create_book(self.request, book)
So how can I take that pk in the urls and use it inside the view?
You can use self.kwargs to access the URL parameters...
For example:
class testview(FormView):
template_name = 'test/test.html'
form_class = ExampleForm
def form_valid(self, form):
pk_from_url = self.kwargs['pk']
# rest of your code
You can get the object during the dispatch for the view and the url param is added to the kwargs for the view;
class TestFormView(FormView):
template_name = 'test/test.html'
form_class = ExampleForm
book = None
def dispatch(self, request, *args, **kwargs):
self.book = get_object_or_404(
Book, pk=kwargs.get('pk')
)
return super().dispatch(request, *args, **kwargs)
Reading these docs may be useful; https://docs.djangoproject.com/en/3.1/ref/class-based-views/base/#django.views.generic.base.View.dispatch
i'm creating like button for my django blog i import api to use ajex from django rest frameworks but i'm getting error in that the error is get() got an unexpected keyword argument 'pk' django
view.py
class PostLikeToggle(RedirectView):
def get_redirect_url(self, *args, **kwargs):
obj = get_object_or_404(Post, pk=kwargs['pk'])
url_ = obj.get_absolute_url()
user = self.request.user
if user.is_authenticated:
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
return url_
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
class PostLikeApiToggle(APIView):
authentication_classes = [authentication.SessionAuthentication]
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
def get_redirect_url(self, *args, **kwargs):
obj = get_object_or_404(Post, pk=kwargs['pk'])
url_ = obj.get_absolute_url()
user = self.request.user
updated = False
liked =False
if user.is_authenticated:
if user in obj.likes.all():
liked = False
obj.likes.remove(user)
else:
liked = True
obj.likes.add(user)
updated = True
data = {
"updated":updated,
"liked":liked
}
return Response(data)
urls.py
path('blog/<int:pk>/like/', PostLikeToggle.as_view(),name='Like-Toggle'),
path('blog/api/<int:pk>/like/', PostLikeApiToggle.as_view(),name='Like-Api-Toggle'),
models.py
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User,on_delete=models.CASCADE)
likes =models.ManyToManyField(User,blank=True,related_name='post_likes')
content = models.TextField()
img = models.ImageField(upload_to='pics',blank=True)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('LoveTravel-Details', kwargs={'pk': self.pk})
def get_like_url(self):
return reverse('Like-Toggle', kwargs={'pk':self.pk})
def get_api_like_url(self):
return reverse('Like-Api-Toggle', kwargs={'pk':self.pk})
can someone please help me get() got an unexpected keyword argument 'pk' in that error
The error is quite explicit. The get method is missing an argument.
In order to fix that:
class PostLikeApiToggle(APIView):
...
def get(self, request, pk, format=None):
Why did you get that error ?
Your urls.py defines the path as 'blog/<int:pk>/like/'. Django will resolve that url and call the view's method - get in your case - with the group names/values as keyword arguments - refer to the point 4 of the documentation for more details about how Django processes requests.
I am currently using Django-registration-redux for my authentication system.
Already logged in user can visit the login and registration page again; which is not good enough. How can I prevent them from this since the views.py comes by default in Django-registration-redux
I think that should be done in the views.py that come with Django-registration-redux
Here is the views.py
"""
Views which allow users to create and activate accounts.
"""
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
from django.conf import settings
from django.utils.decorators import method_decorator
from django.views.decorators.debug import sensitive_post_parameters
try:
from django.utils.module_loading import import_string
except ImportError:
from registration.utils import import_string
from registration import signals
# from registration.forms import RegistrationForm
REGISTRATION_FORM_PATH = getattr(settings, 'REGISTRATION_FORM', 'registration.forms.RegistrationFormUniqueEmail')
REGISTRATION_FORM = import_string( REGISTRATION_FORM_PATH )
class _RequestPassingFormView(FormView):
"""
A version of FormView which passes extra arguments to certain
methods, notably passing the HTTP request nearly everywhere, to
enable finer-grained processing.
"""
def get(self, request, *args, **kwargs):
# Pass request to get_form_class and get_form for per-request
# form control.
form_class = self.get_form_class(request)
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def post(self, request, *args, **kwargs):
# Pass request to get_form_class and get_form for per-request
# form control.
form_class = self.get_form_class(request)
form = self.get_form(form_class)
if form.is_valid():
# Pass request to form_valid.
return self.form_valid(request, form)
else:
return self.form_invalid(form)
def get_form_class(self, request=None):
return super(_RequestPassingFormView, self).get_form_class()
def get_form_kwargs(self, request=None, form_class=None):
return super(_RequestPassingFormView, self).get_form_kwargs()
def get_initial(self, request=None):
return super(_RequestPassingFormView, self).get_initial()
def get_success_url(self, request=None, user=None):
# We need to be able to use the request and the new user when
# constructing success_url.
return super(_RequestPassingFormView, self).get_success_url()
def form_valid(self, form, request=None):
return super(_RequestPassingFormView, self).form_valid(form)
def form_invalid(self, form, request=None):
return super(_RequestPassingFormView, self).form_invalid(form)
class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, request, form):
new_user = self.register(request, form)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
def registration_allowed(self, request):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, request, form):
"""
Implement user-registration logic here. Access to both the
request and the full cleaned_data of the registration form is
available here.
"""
raise NotImplementedError
class ActivationView(TemplateView):
"""
Base class for user activation views.
"""
http_method_names = ['get']
template_name = 'registration/activate.html'
def get(self, request, *args, **kwargs):
activated_user = self.activate(request, *args, **kwargs)
if activated_user:
success_url = self.get_success_url(request, activated_user)
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
return super(ActivationView, self).get(request, *args, **kwargs)
def activate(self, request, *args, **kwargs):
"""
Implement account-activation logic here.
"""
raise NotImplementedError
def get_success_url(self, request, user):
raise NotImplementedError
Here is my main/project urls.py
urlpatterns = [
url( 'admin/', admin.site.urls),
url(r'^$', views.home, name='homepage'),
url(r'^user/', include('User.urls')),
#url(r'^accounts/register/$', MyRegistrationView.as_view(),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thanks, any help will be appreciated
Below are the file showing identation error
indentaion error
views file
In the dispatch method of your views you can check if the user is authenticated and redirect them to another page, for example:
class RegistrationView(_RequestPassingFormView):
...
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if request.user.is_authenticated:
return redirect('some_url')
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
The if user.is_authenticated prevents both logged-in and not-logged-in user from accessing the registration page.
class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.
"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'
#method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
"""
Check that user signup is allowed before even bothering to
dispatch or do other processing.
"""
if self.request.user.is_authenticated:
return redirect('/')
if not self.registration_allowed(request):
return redirect(self.disallowed_url)
return super(RegistrationView, self).dispatch(request, *args, **kwargs)
def form_valid(self, request, form):
new_user = self.register(request, form)
success_url = self.get_success_url(request, new_user)
# success_url may be a simple string, or a tuple providing the
# full argument set for redirect(). Attempting to unpack it
# tells us which one it is.
try:
to, args, kwargs = success_url
return redirect(to, *args, **kwargs)
except ValueError:
return redirect(success_url)
def registration_allowed(self, request):
"""
Override this to enable/disable user registration, either
globally or on a per-request basis.
"""
return True
def register(self, request, form):
"""
Implement user-registration logic here. Access to both the
request and the full cleaned_data of the registration form is
available here.
"""
raise NotImplementedError