2009-03-02 29 views
175

Tôi có Mô hình như sau.Django đặt giá trị biểu mẫu mặc định

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() 

Tôi cũng có mẫu biểu mẫu cho mô hình trên như sau.

class JournalForm(ModelForm): 
    tank = forms.IntegerField(widget=forms.HiddenInput()) 

    class Meta: 
     model = TankJournal 
     exclude = ('user','ts') 

Tôi muốn biết làm thế nào để thiết lập giá trị mặc định cho rằng lĩnh vực ẩn chứa .. Dưới đây là chức năng của tôi để hiển thị/lưu các hình thức cho đến nay

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)) 

Cảm ơn.

Trả lời

313

Bạn có thể sử dụng ban đầu đó được giải thích here

Bạn có hai lựa chọn hoặc là cư giá trị khi gọi hình thức constructor:

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

hoặc thiết lập giá trị trong định nghĩa hình thức:

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

Và làm thế nào là biến 'initial' truyền cho các hình thức thực tế? Trong mô hình biểu mẫu thực tế, chúng ta phải viết như một tham số/đối số? – mgPePe

+0

có, * initial * là thông số có tên –

+0

chờ đợi, wut? Điều đó có nghĩa là gì? Bạn có nghĩa là, một nơi nào đó trong _init_ của mẫu tôi cần một cái gì đó như: tank = initial.tank? Hay gì đó? Hay nó sẽ xảy ra một cách kỳ diệu? – bharal

Các vấn đề liên quan