我有一个模型如下:
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)