我想知道如何从查询集中排除可编辑对象,如果我使用相同的表单创建对象,它仍然有效。
我的表格:
class CountryForm(forms.ModelForm):
"""Form to create or edit Countries."""
name = forms.CharField()
flavor = forms.CharField(
widget=forms.Textarea(attrs={'width': 300, 'height': 100}))
history = forms.CharField(
widget=forms.Textarea(attrs={'width': 300, 'height': 100}))
likes_set = Country.objects.all().exclude(self)
likes = forms.ModelChoiceField(queryset=likes_set, empty_label="Country it likes"
class Meta:
model = Country
答案 0 :(得分:1)
您需要在__init__()
方法中执行此操作,并在实例化表单时传递instance
变量(如果可用)。
class CountryForm(forms.ModelForm):
"""Form to create or edit Countries."""
name = forms.CharField()
flavor = forms.CharField(
widget=forms.Textarea(attrs={'width': 300, 'height': 100}))
history = forms.CharField(
widget=forms.Textarea(attrs={'width': 300, 'height': 100}))
likes = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Country it likes"
class Meta:
model = Country
def __init__(self, *args, **kwargs):
super(CountryForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['likes'].queryset = Country.objects.exclude(kwargs['instance'])
在视图中,您必须创建表单
myform = CountryForm(instance=country_obj)
或
myform = CountryForm(request.POST, instance=country_obj)