Django form, request.post and initial

2020-01-19 10:59发布

问题:

I have a django form where I need to set a value for validation purposes which is not passed in as part of the standard Post request.

In my code I currently have something like this:

if request.method == 'POST':
        postform = CreatePostForm(request.POST, request.FILES, initial={'post_type':post.post_type})

        if postform.is_valid():
                .....

The value post_type is a selection with a value of something like 'QUE'

The issue I am having is that this does not appear to be valid. Does anyone have any suggestions on how to add the post_type value into the CreatePostForm class before the validation takes place.

Please note I do not want to expose this value on the form so including it as part of the post is not an option.

回答1:

One approach is to make it a property on the form class that you hand in as an argument when you instantiate it:

class CreatePostForm(forms.Form/ModelForm):
    def __init__(self, post_type, *args, **kwargs):
        super(CreatePostForm, self).__init__(*args, **kwargs)
        self.post_type = post_type

postform = CreatePostForm(post_type=post.post_type, request.POST, request.FILES)

Hope that helps you out.