Django Pass parameters to Form, getting KeyError - django

I'm trying to pass two parameters to initialize my form, I have tried different ways to achieve this but I get the same error over an over, this is the error that I'm getting (Traceback):
Traceback (most recent call last):
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
File "C:\Users\jorge.lopez\Documents\Personal\Carros\carros\AC\forms.py", line 100, in __init__
self.carro = kwargs.pop('carro')
Exception Type: KeyError at /payments/addtoexistingweek/1/2020-W07
Exception Value: 'carro'
Update
Exception Type: NoReverseMatch at /payments/addtoexistingweek/1/2020-W07
Exception Value: Reverse for 'pagoaexistente' with no arguments not found. 1 pattern(s) tried: ['payments/addtoexistingweek/(?P<carro>[0-9]+)/(?P<semana>[-a-zA-Z0-9_]+)$']
urls.py
path('payments/addtoexistingweek/<int:carro>/<slug:semana>',
views.AgregarPagoSemana.as_view(), name='pagoaexistente'),
views.py
Update
class AgregarPagoSemana(CreateView):
template_name = "AC/add_paymentexistingweek.html"
model = Pagos
form_class = AgregarPagoTransaccionExistente
def get_form_kwargs(self):
kwargs = super(AgregarPagoSemana, self).get_form_kwargs()
kwargs['carro'] = self.kwargs.get('carro')
kwargs['semana'] = self.kwargs.get('semana')
return kwargs
forms.py
class AgregarPagoTransaccionExistente(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.carro = kwargs.pop('carro')
self.semana = kwargs.pop('semana')
super(AgregarPagoTransaccionExistente, self).__init__(*args, **kwargs)
class Meta:
model = Pagos
fields = ('carro', 'pago', 'fecha', 'semana', 'renta')
widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}),
'semana': forms.DateInput(attrs={'type': 'week'})
}
I don´t know if I'm understanding the error correctly and 'carro' is not getting the value.

You are passing the kwarg 'carro' to the view, but not to the form.
In your view, override the "get_form_kwargs" method and return the kwarg.
def get_form_kwargs(self):
kwargs = super(InternalResetPasswordView, self).get_form_kwargs()
kwargs['carro'] = self.kwargs.get('carro')
return kwargs

Related

Creating object with generics CreateApiView 'request' required

This is my serializer and Viewset, i want to create an instance of Like if someone likes a product (Post request 'products/product:id/like'). But i get an error that 'request' is required.
class LikeSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
product = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Like
fields = ('user', 'product',)
class LikeProductApi(generics.CreateAPIView):
queryset = Like.objects.all()
serializer_class = LikeSerializer
def create(self, request, *args, **kwargs):
product_id = self.kwargs['pk']
product = ProductInStore.objects.get(id=int(product_id))
if Like.objects.filter(user=self.request.user, product=product).exists():
raise ValidationError(_("This user already likes this product"))
else:
return super().create(user=self.request.user, product_id=product_id, **kwargs)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "/Users/jakubstrawa/programming/PythonKuba/api/ecommerce/views.py", line 124, in create
return super().create(user=self.request.user, product_id=product_id, **kwargs)
TypeError: create() missing 1 required positional argument: 'request'
Do you have any idea why?
You are making a super() call with the wrong parameters, it should be:
def create(self, request, *args, **kwargs):
product_id = self.kwargs['pk']
if Like.objects.filter(user=self.request.user, product_id=product_id).exists():
raise ValidationError(_("This user already likes this product"))
else:
return super().create(request, *args, **kwargs)
The issue is how you're calling create()
Try the below:
In the PythonKuba/api/ecommerce/views.py file
return super().create(request=self.request, product_id=product_id, **kwargs)
At the moment you are sending in the user, not the request

Django object of type 'method' has no len()

I just added pagination to a ListView in Django, but it is returning object of type 'method' has no len() error, even though I am overriding the get_queryset method and it is not returning anything different from the queryset.
The view causing the error looks like this:
class ProductList(ListView):
paginate_by = 10
model = Product
context_object_name = 'products'
template_name = 'catalog/product/product_list.html'
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def queryset(self):
categories = Category.objects.filter(company=self.request.user.profile.company)
return Product.objects.filter(category__in=categories)
def get_context_data(self, **kwargs):
context = super(ProductList, self).get_context_data(**kwargs)
context['customers'] = Customer.objects.filter(company=self.request.user.profile.company)
context['categories'] = Category.objects.filter(company=self.request.user.profile.company)
return context
The full traceback:
Traceback (most recent call last):
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/ubuntu/dawipo/catalog/views.py", line 105, in dispatch
return super().dispatch(*args, **kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/views/generic/list.py", line 157, in get
context = self.get_context_data()
File "/home/ubuntu/dawipo/catalog/views.py", line 113, in get_context_data
context = super(ProductList, self).get_context_data(**kwargs)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/views/generic/list.py", line 119, in get_context_data
paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/views/generic/list.py", line 69, in paginate_queryset
page = paginator.page(page_number)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/paginator.py", line 73, in page
number = self.validate_number(number)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/paginator.py", line 51, in validate_number
if number > self.num_pages:
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/paginator.py", line 100, in num_pages
if self.count == 0 and not self.allow_empty_first_page:
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/ubuntu/dawipoenv/lib/python3.6/site-packages/django/core/paginator.py", line 95, in count
return len(self.object_list)
Exception Type: TypeError at /catalog/list/
Exception Value: object of type 'method' has no len()
How am I supposed to paginate with an overriden queryset without it showing this error?
The method you override is get_queryset(…) [Django-doc], not queryset, queryset is an attribute, you can set a QuerySet object for that, but not use queryset as a method. You thus implement this as:
from django.contrib.auth.mixins import LoginRequiredMixin
class ProductList(LoginRequiredMixin, ListView):
paginate_by = 10
model = Product
context_object_name = 'products'
template_name = 'catalog/product/product_list.html'
# use get_queryset, not queryset
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(
category__company=self.request.user.profile.company
)
# …
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Trouble calling the form constructor from django createview

I tried to pass the user( i.e, request.user) to my modelform constructor as given in this link.But i am getting
TypeError: __init__() got an unexpected keyword argument 'us'
error. Here's my view
class dealAdd(generic.CreateView):
form_class = dealForm
template_name='deals/deal_Add.html'
def get_context_data(self,**kwargs):
context=super(dealAdd,self).get_context_data(**kwargs)
llist=lead.objects.all()
clist=contacts.objects.all()
context.update({'leadob':llist,'contob':clist})
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(dealAdd, self).get_form_kwargs()
kwargs.update({'us': self.request.user})
return kwargs
and my form constructor
def __init__(self,*args,**kwargs):
usr=kwargs.pop('us')
super(dealForm,self).__init__(*args, **kwargs)
print(usr)
# print(self)
the traceback says that i have error at
context=super(dealAdd,self).get_context_data(**kwargs)
So is there a problem in my view?
Traceback:
Internal Server Error: /deals/dealAdd
Traceback (most recent call last):
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\CapC\Desktop\Sabith\crm1\deals\views.py", line 21, in get_context_data
context=super(dealAdd,self).get_context_data(**kwargs)
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\CapC\Desktop\Django\env\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
TypeError: __init__() got an unexpected keyword argument 'us'
[06/Oct/2018 15:18:41] "GET /deals/dealAdd HTTP/1.1" 500 91563
my form
class dealForm(forms.ModelForm):
class Meta:
model=deals
fields= '__all__'
widgets={
'refno':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'status':forms.Select(choices=stat,attrs={'class':'btn btn-deals'}),
'transaction_price':forms.TextInput(attrs={'class':'input-sm form-
control ember-view ember-text-field'}),
'estimated_closing_date':forms.TextInput(attrs={'class':'input-sm
form-control ember-view ember-text-field'}),
Maybe it's because of the order.
Your CreateView call get_context_data first before get_form_kwargs. It means it 'pop' your 'us' before it updated it.
Just change usr=kwargs.pop('us', None) to avoid error or use try/except for it.

How to pass user id from view to Form's init method?

I have reviewed many questions/answers for hours and applied many techniques but I couldn't pass the user id to the form init() method, it always gives errors like "init() got an unexpected keyword argument 'request'". Anyone knows the reason?
Form, updated as requested in the comment:
class ChildChoreForm(ModelForm):
class Meta:
model = ChildChore
exclude = ('child',)
fields = '__all__'
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ChildChoreForm, self).__init__(*args, **kwargs)
self.fields['chore'].queryset = Chore.objects.filter(created_by=self.request.user)
ChildChoreFormSet = inlineformset_factory(Child, ChildChore, form=ChildChoreForm, extra=1)
View:
class ChildChoreUpdate(UpdateView):
model = Child
success_url = reverse_lazy('children-list')
form_class = ChildChoreFormSet
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
if hasattr(self, 'object'):
kwargs.update({'request': self.request})
return kwargs
The Errors I'm getting after opening the updaet web page:
Internal Server Error: /chore/children/23
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
return super().get(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'
Internal Server Error: /chore/children/23
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\base.py", line 89, in dispatch
return handler(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 190, in get
return super().get(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Python\py_projects\children_chores\chore\views.py", line 202, in get_context_data
data = super(ChildChoreUpdate, self).get_context_data(**kwargs )
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Python\lib\site-packages\django\views\generic\edit.py", line 33, in get_form
return form_class(**self.get_form_kwargs())
File "C:\Python\lib\site-packages\django\forms\models.py", line 898, in __init__
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
File "C:\Python\lib\site-packages\django\forms\models.py", line 569, in __init__
super().__init__(**defaults)
TypeError: __init__() got an unexpected keyword argument 'request'
The problem is that you have set up your form to accept a request argument in __init__, but you are initialising a formset, not a form. You need to modify the formset to accept that same argument and pass it to the forms in the formset:
# First define a base class that overrides __init__ and get_form_kwargs
from django.forms import BaseFormSet
class BaseChildChoreFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
# Handle the request argument that you are passing on init
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
# Add request to the kwargs that are passed to the form on init
kwargs['request'] = self.request
return kwargs
# Now set up your formset using this class
ChildChoreFormSet = inlineformset_factory(
Child, ChildChore, form=ChildChoreForm, formset=BaseChildChoreFormSet, extra=1)

'dict' object has no attribute 'filter' in django

I have created a class based view
class MyLibrary(generic.DetailView):
context_object_name = 'data'
def get_template_names(self):
request = self.request
template_name = 'my_library.html'
return [template_name]
def get_queryset(self):
request = self.request
user = request.user
context = {}
mainData = []
userIssuedBooks = BooksIssued.objects.filter(user=user)
print(userIssuedBooks)
if user.is_authenticated():
context['issuedBooks'] = userIssuedBooks
return context
I am getting following error when the view is getting called
Internal Server Error: /mylibrary/1/admin
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 149,
in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py", line 2
3, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py", line 88, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 117,
in get
self.object = self.get_object()
File "C:\Python34\lib\site-packages\django\views\generic\detail.py", line 38,
in get_object
queryset = queryset.filter(pk=pk)
AttributeError: 'dict' object has no attribute 'filter'
I have no clue why this error is getting generated. Can someone help to find what is wrong here?
In django DetailView, get_queryset expects user to return a queryset(as the name implies) but you returned a dict context. You need to do your current stuff in get_context_data instead.
Django doc about adding extra context.