Django覆盖表单

时间:2009-03-03 15:55:22

标签: python django forms

某些形式的另一个问题

这是我的模特

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

            #
            # saving the test
            #
            obj.save()

        else:
            print form.errors

    else:
        form = JournalForm(initial={'tank': id})

当它保存时..它抱怨坦克不是TankProfile而是整数..如何覆盖表单对象以使坦克成为TankProfile

感谢

2 个答案:

答案 0 :(得分:5)

我想你想要这个:

class JournalForm(ModelForm):
    tank = forms.ModelChoiceField(label="",
                                  queryset=TankProfile.objects.all(),
                                  widget=forms.HiddenInput)

答案 1 :(得分:2)

为什么要重写坦克的定义?

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

如果省略此覆盖,Django会为您处理外键引用。

“如何覆盖表单对象以使tank成为TankProfile?”

我不明白这个问题,因为看起来你专门覆盖了表单以防止外键工作。