Trouble calling the form constructor from django createview - django

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.

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 Pass parameters to Form, getting KeyError

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

overriding empty_value_display for specified field not working in django Admin

I have written a model as follows:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3)
birth_date = models.DateField(blank=True, null=True)
And my modeladmin is as follows:
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date')
def view_birth_date(self, obj):
return obj.birth_date
view_birth_date.empty_value_display = '-empty-'
As documented in django 2.1 https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.empty_value_display, I am trying to do this but its not working.
Its gives me fielderror. Even I didn't understand its purpose.
My traceback:
Traceback (most recent call last):
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 703, in get_form
return modelform_factory(self.model, **defaults)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 551, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\forms\models.py", line 266, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (view_birth_date) specified for Author
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 604, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1639, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1525, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 1554, in _changeform_view
ModelForm = self.get_form(request, obj, change=not add)
File "C:\Users\monikat\Envs\django_training\lib\site-packages\django\contrib\admin\options.py", line 707, in get_form % (e, self.__class__.__name__)
django.core.exceptions.FieldError: Unknown field(s) (view_birth_date) specified for Author. Check fields/fieldsets/exclude attributes of class AuthorAdmin.
Does anyone know why this error is coming?
The problem is that you have defined view_birth_date in the fields attribute of model admin class.
Since it is not present in your db model, it is giving error. Such custom fields will work for list_display, in which you can fetch the value from a method as you have done above, see the docs.
Now if you want some custom field to display on the add/change page , you have to create a custom form and there you can define your custom fields.
If the custom field is just for representation , you can define it as readonly as :
class AuthorAdmin(admin.ModelAdmin):
fields = ('name', 'title', 'view_birth_date')
readonly_fields = ['view_birth_date']
def view_birth_date(self, obj):
return obj.title
view_birth_date.empty_value_display = '-empty-'
Hope it helps!

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.