在表单验证之前在视图中设置字段值'user'

时间:2013-03-22 11:27:52

标签: django django-forms

我试图设置字段值' user'在验证之前查看,您可以在下面的示例中看到。但我仍然需要验证消息用户是必需的,表明它没有被设置。我做错了什么?

谢谢,

view.py

def add_batch(request):
    # If we had a POST then get the request post values.
    if request.method == 'POST':

        form = BatchForm(data=request.POST, initial={'user': request.user})
        # Check we have valid data before saving trying to save.
        if form.is_valid():
            # Clean all data and add to var data.
            data = form.cleaned_data
            groups = data['groups'].split(",")
            for item in groups:
                batch = Batch(content=data['content'],
                              group=Group.objects.get(pk=item),
                              user=request.user
                              )
                batch.save()
            return redirect(batch.get_send_conformation_page())
        else:
            context = {'form': form}
            return render_to_response('sms/sms_standard.html', context, context_instance=RequestContext(request))

form.py

class BatchForm(forms.ModelForm):

    class Meta:
        model = Batch

    def __init__(self, user=None, *args, **kwargs):
        super(BatchForm, self).__init__(*args,**kwargs)
        if user is not None:
            form_choices = Group.objects.for_user(user)
        else:
            form_choices = Group.objects.all()
        self.fields['groups'] = forms.ModelMultipleChoiceField(
            queryset=form_choices
        )

2 个答案:

答案 0 :(得分:5)

正如the documentation所解释的那样,initial值不用于在表单中设置数据,它们仅用于显示初始值。

如果您不想显示用户但想要自动设置,最好的办法是完全从ModelForm中排除用户字段,并在保存时将其设置在视图中。或者,由于出于其他原因将其作为参数传递,您可以将其添加到POST数据中:

def __init__(self, user=None, *args, **kwargs):
    super(BatchForm, self).__init__(*args,**kwargs)
    if user is not None:
        if self.data:
            self.data['user'] = user

答案 1 :(得分:0)

form = BatchForm(request.user, request.POST)
# Check we have valid data before saving trying to save.
if form.is_valid():
    [.........]