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')
我想知道如何设置坦克隐藏领域的默认值..这里是我的function来显示/保存表格到目前为止
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 = JournalForm(initial={'tank': 123})
或者在窗体定义中设置值:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
如果你正在从POST值创buildmodelform,可以这样分配初始值:
form = SomeModelForm(request.POST or None, initial={"option": "10"})
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values