我正在尝试在验证之前在视图中设置字段值“用户”,如下面的示例所示。但我仍然收到验证消息 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
)