tags:

views:

1611

answers:

2

Another question on some forms

Here is my model

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

Here is my modelform

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

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

Here is my method to save it

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

When it saves.. it complains the tank is not a TankProfile but a Integer.. how can I override the form object to make tank a TankProfile

thanks

+1  A: 

Why are you overriding the definition of tank?

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

If you omit this override, Django handles the foreign key reference for you.

"how can I override the form object to make tank a TankProfile?"

I don't understand this question, since it looks like you specifically overrode the form to prevent the foreign key from working.

S.Lott
I need to turn the tank object into a hiddenfield so its referenced on the form as a hidden input
Mike
+4  A: 

I think you want this:

class JournalForm(ModelForm):
    tank = forms.ModelChoiceField(label="",
                                  queryset=TankProfile.objects.all(),
                                  widget=forms.HiddenInput)
that just gives me thisException Value: int() argument must be a string or a number, not 'TankProfile'
Mike