Django: form validation errors on form creation

Django: form validation errors on form creation

Let's say I have a Django form with ChoiceField:

Let's say I have a Django form with ChoiceField:

class MyForm(forms.Form):
    name = forms.CharField(label="Name", required=True)
    some_object = forms.ChoiceField(label="Object", choices=[(0, '-----')] + [(x.id, x.name) for x in Obj.objects.all()])

Choisefield is being initialized with list of objects headed by 'empty choice'. There is no object with pk=0. In that form I have a clean() method:

def clean(self):
    if not Obj.objects.filter(self.cleaned.data['some_object'].exists():
        self.errors.update({'some_object': ['Invalid choice']})

It works well when I'm sending a form to a server, if data in it doesn't match conditions, field.is_valid returns False and I render form with error messages. But, when I create an empty form like this:

if request.method == 'GET':
    data = {'name': 'Untitled',
            'some_object': 0}
    form = MyForm(data)
    return render(request, 'app\template.html', {'form': form})

Django renders form with error message ('Invalid choice') even though form was just created and 'Object' select was intended to be set in empty position. Is it possible to disable form clean() method in specific cases? Or mayb

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Django Tutorial | Django Course

🔥Intellipaat Django course: https://intellipaat.com/python-django-training/ 👉This Python Django tutorial will help you learn what is django web development &...

Developing Restful APIs with Python, Django and Django Rest Framework

This article is a definitive guide for starters who want to develop projects with RESTful APIs using Python, Django and Django Rest Framework.