change a form value before validation in Django form

前端 未结 4 1418
难免孤独
难免孤独 2021-02-19 03:00

I have a django form and on my view function I do this :

search_packages_form = SearchPackagesForm( data = request.POST )

I would like to overw

4条回答
  •  时光取名叫无心
    2021-02-19 03:22

    Probably not the Django way but based on https://stackoverflow.com/a/17304350/2730032 I'm guessing the easiest way to change your form value before validation is to do something like the following:

    def search_packages_view(request):
        if request.method == 'POST'
            updated_request = request.POST.copy()
            updated_request.update({'price': NEW_PRICE})
            search_packages_form = SearchPackagesForm(updated_request)
            if search_packages_form.is_valid():
                 # You're all good
    

    This works but I'd be interested if anyone has another way that seems more in line with Django, or if there isn't: then an explanation about why.

提交回复
热议问题