[Django]-How to validate django form only when adding not editing

3👍

in your clean method, you can use self.initial to know whether it is adding or editing. If it is editing, the self.initial will not be empty. But when it is adding, self.initial will be dictionary of what the previous value.

2👍

If you are editing form, then the form has some instance, and you can check if that exists.

If it does, then you are probably editing existing object.. right?

Example:
If you are editing object with form, you create form object much like this:

form = MyForm(instance = myobject)

Then in your form class methods you can check if form has saved instance in a way that it is described here:
Test if Django ModelForm has instance

1👍

in your clean_name function exclude the current object from queryset

query.filter('name = ', name).exclude(pk=self.pk)

or change the if condition to check that page and current object are not the same.

👤Ashok

0👍

Sorry, I couldn’t comment below your guys post, don’t know why.

@sunn0 : I didn’t use django models, coz deploy the app in appengine, so use appengine model instead.

@Zayatzz : May you show a little code how to do it? Since whether we are adding or editing, we always bound the form to request.POST before validation, so don’t know how to differentiate.

@Ashok : I made a workaround based on your suggestion. Since previously I didn’t pass the pk to form, but passing the prev object as param instead, so couldn’t exclude by using pk. So, I change the code and put additional key as pk (if create, let key empty, but if edit fill key with pk) and just check in if condition, if key field not empty, then it means we are editing. Not sure if it is best practice, but it works anyway.

0👍

I can suggest to override form’s init method
https://stackoverflow.com/a/70845558/15080117
because there is an argument instance.

Leave a comment