[Answer]-Django form create or edit exclude object

1👍

You need to do this in __init__() method, and also pass instance variable if available while instantiating the form.

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'])

In view you would have to create form as

myform = CountryForm(instance=country_obj) 

or

myform = CountryForm(request.POST, instance=country_obj) 
👤Rohan

Leave a comment