Django set default form values

0 votes
asked Mar 2, 2009 by mike

I have a Model as follows

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

I have a modelform as follows for that model

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

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

I want to know how to set the default value for that tank hidden field.. Here is my function to show/save the form so far

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

thanks!

2 Answers

0 votes
answered Mar 2, 2009 by sergey-golovchenko

You can use initial which is explained here

You have two options either populate the value when calling form constructor:

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

or set the value in the form definition:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 
0 votes
answered Jan 12, 2015 by quux

If you are creating modelform from POST values initial can be assigned this way:

form = SomeModelForm(request.POST or None, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...