我有一个ModelForm,在ModelChoiceField中,我需要按request.user过滤对象。提交数据后,出现错误“ init ()为参数'crescator'获得了多个值”。我该如何修复?
#My Form
class AdaugaPereche(forms.ModelForm):
boxa = forms.IntegerField(label="Boxa", min_value=1)
sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year)
mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul")
femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela")
serie_pui_1 = forms.TextInput()
serie_pui_2 = forms.TextInput()
culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea",
required=False)
culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea",
required=False)
data_imperechere = forms.DateInput()
primul_ou = forms.DateInput()
data_ecloziune = forms.DateInput()
data_inelare = forms.DateInput()
comentarii = forms.TextInput()
# Functie pentru filtrarea rezultatelor dupa crescator
def __init__(self, crescator, *args, **kwargs):
super(AdaugaPereche, self).__init__(*args, **kwargs)
self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul",
perechi_masculi__isnull=True)
self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă",
perechi_femele__isnull=True)
self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
class Meta:
model = Perechi
fields = "__all__"
#My view
def perechenoua(request):
if request.method == "POST":
form = AdaugaPereche(request.POST, crescator=request.user)
if form.is_valid():
obj = form.save(commit=False)
obj.crescator = request.user
obj.save()
return HttpResponseRedirect("/perechi/")
else:
form = AdaugaPereche(crescator=request.user)
context = {
'form': form
}
template = loader.get_template("adauga-pereche.html")
return HttpResponse(template.render(context, request))
问题可能出在obj = form.save(commit = False)obj.crescator = request.user obj.save()吗?
答案 0 :(得分:1)
表单签名的__init__
函数在此处crescator
作为第一个参数,但是您将request.POST
作为该参数传递,此外,您还将其作为 named < / em>参数。通过调整参数,这应该可以工作:
class AdaugaPereche(forms.ModelForm):
# ...
def __init__(self, *args, crescator=None, **kwargs):
super(AdaugaPereche, self).__init__(*args, **kwargs)
self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul",
perechi_masculi__isnull=True)
self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă",
perechi_femele__isnull=True)
self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator)
# ...