Home > front end >  __init__() got multiple values for argument 'user'
__init__() got multiple values for argument 'user'

Time:02-04

I have a form, model and view and trying to show ModelChoiceField with filters

I wrote an init in my forms.py but when im trying to submit my form on html page i got an error:

"__init__() got multiple values for argument 'user' "

forms.py

class WorkLogForm(forms.ModelForm):
    worklog_date = forms.DateField(label='Дата', widget=forms.DateInput(
        attrs={'class': 'form-control', 'placeholder': 'Введите дату'}))
    author = forms.EmailField(label='Автор',
                              widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email автора'}))

    contractor_counter = forms.ModelChoiceField(queryset=CounterParty.objects.none())
    contractor_object = forms.ModelChoiceField(queryset=ObjectList.objects.none())
    contractor_section = forms.ModelChoiceField(queryset=SectionList.objects.none())

    description = forms.CharField(label='Описание',
                                  widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Описание'}))

    def __init__(self, user, *args, **kwargs):
        super(WorkLogForm, self).__init__(*args, **kwargs)
        counter_queryset = CounterParty.objects.filter(counter_user=user)

        object_queryset = ObjectList.objects.filter(
            Q(customer_guid__in=counter_queryset) | Q(contractor_guid__in=counter_queryset))

        section_queryset = SectionList.objects.filter(object__in=object_queryset)

        self.fields['contractor_counter'].queryset = counter_queryset
        self.fields['contractor_object'].queryset = object_queryset
        self.fields['contractor_section'].queryset = section_queryset

    class Meta:
        model = WorkLog
        fields = (
            'worklog_date', 'author', 'contractor_counter', 'contractor_object', 'contractor_section', 'description')

views.py

def create_work_log(request):
    if request.method == 'POST':
        form = WorkLogForm(request.POST, user=request.user)
        if form.is_valid():
            form.author = request.user
            work_log = form.save()
            return render(request, 'common/home.html')
    else:
        form = WorkLogForm(user=request.user)

    return render(request, 'contractor/create_work_log.html', {'form': form})


CodePudding user response:

In your forms init method you defined the parameters as:

def __init__(self, user, *args, **kwargs):

So your first parameter must be user instead of request.POST. So you can change

form = WorkLogForm(request.POST, user=request.user)

To

form = WorkLogForm(request.user, request.POST)
  • Related