0

I have 2 radio buttons in the UI, one for setting a variable (ng-model) say selected as true (ng-value=true) and other one for setting it as false (ng-value=false). Now, when none of them is selected it results in the variable selected being absent from the outgoing request (as expected).

However, when that is dealt with Django Forms, the self.data dictionary in the clean() method gives False on accessing self.data.get('selected') / self.data['selected'] why is that so? Shouldn't it be None or at least give a key-error when it was not even present in the actual request?

Note that the variable 'selected' is actually a field in a Django Model with default=False, is that thing responsible for this behaviour? How can I circumvent this situation considering that altering the Django Model field isn't an option?

2
  • Do you mind sharing your form and model code?
    – Rubico
    Aug 5, 2021 at 18:22
  • @Rubico I can't share the code but the relevant parts are all normal like Form having having a Meta class for choosing the model and selecting its fields in a tuple etc. Model field selected is also a simple boolean field with default=False Aug 5, 2021 at 18:36

1 Answer 1

0

So I dealt with it the other day by checking for the selected key in the raw request.body. Now, since its a string, I had to parse it to a dict and then access the mentioned key using :

json.loads(request.body).get('selected')

In this way, if selected is not present at all when none of the radio buttons are selected, I get None. Similarly, if the radio button for ng-value=true is selected then I get True and vice-versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.