Creating object with generics CreateApiView 'request' required - django

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

Related

KeyError at /api/rooms/create-grade/ 'grade'

I don't understand this error one bit, I'm trying to do a basic create method but I get a KeyError what am i doing wrong
This is serializer.py code
class GradeCreateSerializer(serializers.ModelSerializer):
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
class Meta:
model = Grade
fields = ["grade"]
# ordering = ['-created_date']
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
try:
perms = Perm.objects.get(user=user)
except:
perms = None
if user.role in ['OWNER', 'PARTNER']:
school = user.owns.first()
elif perms is not None:
if user.role == 'STAFF' and perms.can_crt_grade_class:
school = user.works
instance = Grade.objects.create(
grade=validated_data['grade'],
school=school,
)
instance.save()
return instance
what am I doing wrong??
I have added the error traceback as requested
error traceback
Traceback (most recent call last):
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 19, in create
self.perform_create(serializer)
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\mixins.py", line 24, in perform_create
serializer.save()
File "F:\Projects\SchoolProject\main\Abugida\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "F:\Projects\SchoolProject\main\Classes\serializers.py", line 45, in create
grade=validated_data['grade'],
KeyError: 'grade'
it says that grade=validated_data['grade'], this the problem but i don't get it.
I have found a solution to my issue, it was because of grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display") this means when using a ChoiceField to define your field you don't need to pass the source="" as the field uses the choice to determine it
So changing
grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display")
to
grade = serializers.ChoiceField(choices=GRADES)
did the trick

How do I properly deserialize data with django-money?

I have Model that contains MoneyField from djmoney
class Task(models.Model):
description = models.CharField(max_length=512)
user = models.ForeignKey("user.User", on_delete=models.CASCADE)
price = MoneyField(
max_digits=8,
decimal_places=2,
default_currency="USD",
default=0)
Serializer
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = "__all__"
read_only_fields = ("user",)
My APIView POST function of Viewset
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=201, headers=headers)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
When I'm trying to POST data in format like this
{
"description": "Test",
"price": "20.00"
}
It gives me an error, that
'decimal.Decimal' object has no attribute 'amount' with given Traceback.
How can I solve this issue?
Traceback (most recent call last):
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/user/PycharmProjects/my_project/tackapp/tack/views.py", line 37, in create
serializer.is_valid(raise_exception=True)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 227, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 426, in run_validation
value = self.to_internal_value(data)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/serializers.py", line 483, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/fields.py", line 569, in run_validation
self.run_validators(value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/rest_framework/fields.py", line 593, in run_validators
validator(value)
File "/home/user/.virtualenvs/my_project/lib/python3.10/site-packages/djmoney/models/validators.py", line 30, in __call__
cleaned = cleaned.amount
I did found workaround like this but I'm trying to get my code clean and simple. And I think that I am missing something.
So basically serializer expects value in Money object, but did not expect str from it's own serializer methods
def create(self, request, *args, **kwargs):
price = Money(request.data["price"], "USD")
serializer = self.get_serializer(data=request.data | {"price": price})
...

How to limit serializing in Django Rest Framework?

I have 2 serializers that add and subtract (they are the same, with the difference being add +=1 and subtract -=1) points to an answer. I want to limit them so that a user can only use add point to an answer once. Do you have any idea how to get to it in Django Rest Framework?
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
class SubtractPointsSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('number_of_points',)
def update(self, instance, validated_data):
instance.number_of_points -= 1
instance.save()
return instance
Internal Server Error: /api/v1/answers/2/addpoints
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 226, in put
return self.update(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 68, in update
self.perform_update(serializer)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/mixins.py", line 78, in perform_update
serializer.save()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/serializers.py", line 200, in save
self.instance = self.update(self.instance, validated_data)
File "/Users/jakubstrawa/programming/gitlabdeor/api/questions/serializers.py", line 74, in update
if not instance.addition_done and self.request.user not in instance.voters.all():
AttributeError: 'AddPointsSerializer' object has no attribute 'request'
You can always add a Boolean field that stores if addition/subtraction was done. You can store every User that had voted already so noone will vote twice (also will not vote for both +1/-1).
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
addition_done = models.BooleanField(default=False)
subtraction_done = models.BooleanField(default=False)
voters = models.ManyToManyField('User', default=None, blank=True)
===========================================================
class SubtractPointsSerializer(serializers.ModelSerializer):
...
def update(self, instance, validated_data):
if not instance.subtraction_done:
instance.number_of_points -= 1
instance.subtraction_done = True
instance.save()
return instance
You can also divide ManyToMany field into two separated (one for addition, another for subtraction).

post() missing 2 required positional arguments: 'self' and 'request'

I am trying to save a post request but I am getting post() missing 2 required positional arguments: 'self' and 'request' error.
View:
class MakeLeaveRequest(generics.CreateAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = MakeLeaveRequestSerializer
# login_url = '../../users/v1/login/'
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid(raise_exception=True):
# self.perform_create(serializer)
date = serializer.save()
print(date)
# headers = self.get_success_headers(serializer.data)
return Response({'ok':'ok'}, status=status.HTTP_201_CREATED)
Serializer:
class MakeLeaveRequestSerializer(serializers.ModelSerializer):
# date_to = serializers.DateField()
# date_from = serializers.DateField()
# description = serializers.CharField()
# types_of_leave = serializers.IntegerField()
class Meta:
model = LeaveRequest
fields = ('date_to', 'date_from', 'description',
'types_of_leave',)
def create(self, validated_data):
user = self.context['request'].user
print(user)
# print(validated_data['date_to'])
try:
LeaveRequest.objects.create(user = user)
except ObjectDoesNotExist:
pass
return user
Trace Path :
admin
2019-01-02
Internal Server Error: /attend/v1/leaveRequest
Traceback (most recent call last):
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/
python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py", line 52, in inner
return func(*args, **kwds)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/generics.py", line 192, in post
return self.create(request, *args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/attendanceregistersystem/attendance/views.py", line 78, in create
date = serializer.save()
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/attendanceregistersystem/attendance/serializers.py", line 30, in create
LeaveRequest.objects.create(user = user)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create
obj.save(force_insert=True, using=self.db)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save
force_update=force_update, update_fields=update_fields)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/db/models/base.py", line 769, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in send
for receiver in self._live_receivers(sender)
File "/home/bishwa/attendanceRegisterSystem/attendanceregistersystem/.venv/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp>
for receiver in self._live_receivers(sender)
TypeError: post() missing 2 required positional arguments: 'self' and
'request'

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)