python - template - Django設置了默認的表單值




python form (3)

你可以使用here解釋的初始

調用窗體構造函數時,您有兩個選項填充值:

form = JournalForm(initial={'tank': 123})

或者在表單定義中設置值:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

我有一個模型如下。

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.tank = id
    return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request))

謝謝。


其他解決方案:創建表單後設置初始值:

form.fields['tank'].initial = 123

我有這個其他的解決方案(我發布它,以防其他人使用模型中的以下方法):

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





model