Y
Y
YuriyCherniy2020-04-19 23:00:50
Django
YuriyCherniy, 2020-04-19 23:00:50

Does it make sense to use an if condition on form.is_valid() if the form field is forms.ChoiceField?

Given this form:

class MessengerForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        initial_messenger = UserProfile.objects.first().messenger
        self.fields['messenger'].initial = initial_messenger

    messenger = forms.ChoiceField(
        choices=[
            ('whatsapp', 'WhatsApp'),
            ('telegram', 'Telegram')
        ],
        label='Мессенджер для связи'
    )

Is there a need to check the validity of the data if the user can only enter the suggested options?
In other words, the correct way would be:
def post(self, request, **kwargs):
    messanger_form = MessengerForm(request.POST)
    if messanger_form.is_valid():
        profile = UserProfile.objects.get(pk=kwargs['pk'])
        profile.messenger = messanger_form.cleaned_data['messenger']
        profile.save()
        return super().post(self, request, **kwargs)
    else:
        return somthing

or this is enough:
def post(self, request, **kwargs):
    messanger_form = MessengerForm(request.POST)
    messanger_form.is_valid():
    profile = UserProfile.objects.get(pk=kwargs['pk'])
    profile.messenger = messanger_form.cleaned_data['messenger']
    profile.save()
    return super().post(self, request, **kwargs)

From the point of view of the noob if, it is not needed, as the choice of data is provided by the application and they will always be valid. But given that a noob can make mistakes, there is a high probability of leaving a hole in the application. How to proceed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-04-19
@YuriyCherniy

The data from the client always needs to be checked, which prevents me from making a request with my hands and substituting any value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question