Reputation: 1
I would like to update the configuration of a device using a Model Form. I suceeded in passing the user to the model form and I can choose device_id which belongs to the current user. But when I submit the Form, i get an error: init() got multiple values for argument 'user' Is there also a way to put the additional Field "your_device" as the first (before all other fields) of the model form?
I tried to remove user = request.user from the POST Method in views.py but then I get another error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict'
This is my forms.py:
class ConfigForm(forms.ModelForm):
your_device = forms.ModelChoiceField(queryset=Device.objects.none())
class Meta:
model = Config
fields = [
'location',
'meas_pos',
'loudest_pos',
'spl_range',
'weighting',
'tx_int',
'offset',
'limit',
'notification']
def __init__(self, user, *args, **kwargs):
super(ConfigForm, self).__init__(*args, **kwargs)
self.fields['your_device'].queryset = Device.objects.filter(Q(customer=user) | Q(admin=user))
and my views.py:
def config_view(request):
if request.method == 'POST':
form = ConfigForm(request.POST, user = request.user)
if form.is_valid():
instance = form.save(commit=False)
object_id = form.cleaned_data.get('your_device')
id_ = Index.object.get(id=object_id).device_id
instance.device_id = id_
index_id=Index.objects.get(device_id=id_)
instance.cfg_nbr=index_id.current_cfg+1
index_id.current_cfg=index_id.current_cfg+1
index_id.cfg_received=False
index_id.save()
instance.save()
messages.success(request, f'Configuration successfully changed!')
else:
form = ConfigForm(user=request.user)
context = {
'form' : form
}
return render(request, 'my_spl/config.html', context)
Upvotes: 0
Views: 38
Reputation: 599600
You've redefined the signature of the form init, so that the first positional parameter is user
. So when you pass request.POST, user=request.user
the first argument is taken to be user, and then the second one... is also user, which can't happen.
The solution is not to change the signature, but to get the user from kwargs:
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(ConfigForm, self).__init__(*args, **kwargs)
Upvotes: 1