0

I am displaying a django form and I want to prepare some field data before it is passed to to be rendered. In the django docs, I see plenty of places where form data is accessed, but none where form data is set before display.

Any thoughts or suggestions on how to do this?

Here's an example similar to the django docs.

-----------forms.py--------------

class BookForm(ModelForm):
    author = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,
                widget=forms.Select(choices=TITLE_CHOICES))
    birth_date = forms.DateField(required=False)

-----------views.py--------------

def author_view(request):
    if request.method == 'POST': 
        #  DO My processing... 
    form = BookForm() 
    # How can I edit, or preset my form fields here?
    c = Context({
      'form': form,
    })
    return prepCxt(request, 'book.html', c)   # Wrapper for easy display
codingJoe
  • 4,713
  • 9
  • 47
  • 61

1 Answers1

1

In your views you have:

def author_view(request):
    if request.method == 'POST': 
        #  DO My processing... 
    form = BookForm() 
    # How can I edit, or preset my form fields here?
    c = Context({
      'form': form,
    })
    return prepCxt(request, 'book.html', c)   # Wrapper for easy display

You should move your form=BookForm() before the if:

def author_view(request):
    form = BookForm() 
    if request.method == 'POST': 
        #  DO My processing... 

What happens is that the if "POST" section adds a value in form and then it could get overriden.

Secondly if you are trying to change something in the way it display you are probably best adding default/initial values:

Django set default form values:

BookForm(initial={ 'myfield': 'myval'})

if you are tryiong to change values that you want to save to the DB then you:

if form.is_valid():
   myobject = form.save(commit=false)
   myobject.myfield = mval
   myobj.save()

   form = BookForm(instance = myobjext)

Something else? Please be more specific.

Community
  • 1
  • 1
James Khoury
  • 21,330
  • 4
  • 34
  • 65
  • -1 for saying the form instantiation should go before the if statement. It needs to go inside - if post, then instantiate with the post data, otherwise instantiate an empty form. – Daniel Roseman Oct 21 '11 at 08:24
  • @DanielRoseman It dosen't have to. It can go before or in an else. It makes little difference. – James Khoury Oct 22 '11 at 03:08