Django set default form values
我有一个模型如下。
1 2 3 4 5 6 | 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() |
我还有一个上面模型的模型表单,如下所示。
1 2 3 4 5 6 | class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts') |
号
我想知道如何设置油箱隐藏字段的默认值。这是到目前为止显示/保存表单的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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.tank = id return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request)) |
谢谢。
你可以用这里解释的首字母
您有两个选项,一个是在调用表单构造函数时填充该值:
1 | form = JournalForm(initial={'tank': 123}) |
或在表单定义中设置值:
1 | tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) |
如果要从发布值创建模型表单,则可以通过以下方式分配初始值:
1 | form = SomeModelForm(request.POST or None, initial={"option":"10"}) |
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/提供初始值
其他解决方案:创建表单后设置初始值:
1 | form.fields['tank'].initial = 123 |
我有另一个解决方案(我在发布它,以防像我一样的其他人使用模型中的以下方法):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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', }) } |
初始值在