gpt4 book ai didi

django - 在表单验证之前在 View 中设置字段值 'user'

转载 作者:行者123 更新时间:2023-12-02 22:09:28 24 4
gpt4 key购买 nike

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

谢谢,

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))

表单.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
)

最佳答案

作为the documentation解释说,initial 值不用于在表单中设置数据,它们仅用于显示初始值。

如果您不想显示用户但想自动设置它,最好的办法是将用户字段完全从 ModelForm 中排除,并在保存时在 View 中设置它。或者,由于您出于其他原因将其作为参数传递,您可以将其添加到 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

关于django - 在表单验证之前在 View 中设置字段值 'user',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com