问题:Django设置默认表单值
我有一个模型如下:
class TankJournal(models.Model):
user = models.ForeignKey(User)
tank = models.ForeignKey(TankProfile)
ts = models.IntegerField(max_length=15)
title = models.CharField(max_length=50)
body = models.TextField()
我也有上述模型的模型形式,如下所示:
class JournalForm(ModelForm):
tank = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = TankJournal
exclude = ('user','ts')
我想知道如何为该坦克隐藏字段设置默认值。这是我到目前为止显示/保存表格的功能:
def addJournal(request, id=0):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
# checking if they own the tank
from django.contrib.auth.models import User
user = User.objects.get(pk=request.session['id'])
if request.method == 'POST':
form = JournalForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
# setting the user and ts
from time import time
obj.ts = int(time())
obj.user = user
obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])
# saving the test
obj.save()
else:
form = JournalForm()
try:
tank = TankProfile.objects.get(user=user, id=id)
except TankProfile.DoesNotExist:
return HttpResponseRedirect('/error/')
回答 0
您可以使用初始被解释这里
您有两个选择,可以在调用表单构造函数时填充值:
form = JournalForm(initial={'tank': 123})
或在表单定义中设置值:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
回答 1
其他解决方案:创建表单后设置初始:
form.fields['tank'].initial = 123
回答 2
如果要通过POST值创建模型形式,则可以通过以下方式分配初始值:
form = SomeModelForm(request.POST, initial={"option": "10"})
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values
回答 3
我有另一个解决方案(如果其他人正在使用该模型中的以下方法,我会发布它):
class onlyUserIsActiveField(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
self.fields['is_active'].initial = False
class Meta:
model = User
fields = ['is_active']
labels = {'is_active': 'Is Active'}
widgets = {
'is_active': forms.CheckboxInput( attrs={
'class': 'form-control bootstrap-switch',
'data-size': 'mini',
'data-on-color': 'success',
'data-on-text': 'Active',
'data-off-color': 'danger',
'data-off-text': 'Inactive',
'name': 'is_active',
})
}
缩写在__init__
函数上定义为self.fields['is_active'].initial = False
回答 4
我希望这可以帮助您:
form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id
回答 5
如Django文档所述,initial
不是default
。
字段的初始值打算在HTML中显示。但是,如果用户删除该值,并最终为此字段发送回空白值,则该
initial
值将丢失。因此,您不会获得默认行为所期望的结果。该默认行为是:如果值验证过程将采取
data
说法不包含字段的任何值。
要实现这一点,一种简单的方法是将initial
和结合起来clean_<field>()
:
class JournalForm(ModelForm):
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
(...)
def clean_tank(self):
if not self['tank'].html_name in self.data:
return self.fields['tank'].initial
return self.cleaned_data['tank']