开发者

replace values in form.data when form fails validation

I have a form field which requires a json object as its value when it is rendered. When the form is submitted it returns a comma seperated string of ids as its value (not a json string). however if the form does not validate i want to turn this string of ids back into a json string so it will display properly (is uses jquery to render the json object correctly).

how would i do this?

I was thinking of overwriting the form.clean method but when I tried to change self.data['fieldname'] I got the error 'This QueryDict instance is immutable'

and 开发者_如何学JAVAwhen i tried to change self.cleaned_data['fieldname'] it didn't make a difference to the value of the field.

Thanks


I ended up doing

if request.method == 'POST': 
    new_data = request.POST.copy() 
    form = MyForm(data=new_data) 
    if form.is_valid():  
        form.save()  
    else:  
        new_data['myField'] = '[{'id':1,'value':some json object}]' 

I did this in the view rather than on the form class. I don't know if this is the best way to do it but its worked for me. Doing request.POST.copy() allowed me to change the post variables which is one of the errors I was getting in the first place.

Hope this helps someone

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜