I have a app to manage book orders from some people, here is the model :
class Order(models.Model):
person = models.ForeignKey(Person)
book = models.ForeignKey(Book)
qty = models.IntegerField(default=0)
I also use a ModelFormSet to allow people to order several books at once. Although the form use initial 0 values for the “qty” field, I’m afraid some people will use an empty string instead of it.
So, what I want is to “convert” this Null entry to 0 before the form is processed (but after it has been bound, obviously)
I found the following solution:
def order(request, person_id):
if request.method == "POST":
# Hack to correct Null entries from user... TODO: find better way...
posted_datas = request.POST.copy()
for p in [k for k,v in posted_datas.items() if re.compile("qty").search(k) and not v]:
posted_datas[p] = 0
formset = BookOrderFormSet(posted_datas)
if formset.is_valid():
....
It works fine, and I feel it will probably help someone in the same situation, but i’m wondering if there is a better/cleaner way to go…
edit
So you want to forgive user who deletes default 0 and leaves the qty field empty w/o providing any suitable number, by reseting the value of the field to 0 w/o showing him the error “qty is required”? Normally, better not to do this IMHO =)
But if you want, besides check-and-set it in view, you could also patch the clean method of form Field to not to raise exception for empty value but change it to the default instead. For example
ignore following prev misunderstanding answer
I don’t think you need this extra work. Django form and models protects it well: