4👍
The order in which you defined the parameters is:
def __init__(self, ubc, *args, **kwargs):
whereas you make a call to the __init__
with:
form = ChangeMemberForm(request.POST, ubc=ubc.id)
So you called it with an unnamed first parameter, whereas the first parameter is ubc
. So as a result, the __init__
function received two values for the ubc
parameter: request.POST
, and ubc.id
, and of course that does not make sense.
So you should replace it with:
form = ChangeMemberForm(ubc.id, request.POST)
So here that means that the first parameter (ubc.id
) is redirected to the ubc
parameter, and the second (request.POST
) is the first parameter of the *args
, which is a parameter of the super().__init__
call.
2👍
The convention in django is to pass the form data as the first positional argument when you initialize a form.
The problem with your ChangeMemberForm
is that ubc
is declared as the first positional argument. So when you try to ChangeMemberForm(request.POST, ubc=ubc.id)
both arguments would be interpreted as ubc
, and python throws an exception.
When you subclass Form
it’s better to use only named arguments for any extra arguments required by your custom form class. With python 3, simply put ubc
between *args
and **kwargs
in the __init__
method signature.
class ChangeMemberForm(forms.Form):
def __init__(self, *args, ubc, **kwargs):
...
(If you are using python 3.4 or earlier, you must include a default value for ubc
, as mentioned by Willem in a comment)
If you have to support python 2, this syntax is not valid, and you must instead do something like this.
class ChangeMemberForm(forms.Form):
def __init__(self, *args, **kwargs):
ubc = kwargs.pop('ubc')
...
- [Django]-Django: getattr function (get field name)
- [Django]-Django admin throws error after installing tastypie?
- [Django]-How do I send channels 2.x group message from django-celery 3 task?