我有一个模型如下.
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/')
谢谢.
您可以使用此处说明的初始值
调用表单构造函数时,有两个选项可以填充值:
form = JournalForm(initial={'tank': 123})
或者在表单定义中设置值:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
其他解决方案:创建表单后设置初始值:
form.fields['tank'].initial = 123
如果从POST值创建modelform,则可以通过以下方式分配initial:
form = SomeModelForm(request.POST, initial={"option": "10"})
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values
我有另外一个解决方案(我发布它以防万一其他人,因为我使用模型中的以下方法):
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__
函数asself.fields['is_active'].initial = False