2

我正在尝试在验证之前在视图中设置字段值“用户”,如下面的示例所示。但我仍然收到验证消息 user is required ,表明它没有被设置。我做错了什么?

谢谢,

视图.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))

表格.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
        )
4

2 回答 2

5

正如文档所解释的,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
于 2013-03-22T11:41:47.840 回答
0
form = BatchForm(request.user, request.POST)
# Check we have valid data before saving trying to save.
if form.is_valid():
    [.........]
于 2013-03-22T11:32:41.223 回答