Aaron Lelevier
Aaron Lelevier

Reputation: 20838

Django pre-fill a form drop down box based on url request

I would like to pre-fill a drop down box based on a URL request from a URL tag. I'm trying to get it where the site is a list of books, and when you're on a book page, if you want to take some notes on that book, then you would hit the "take notes" button, and it would take you to a note form page where the drop down box at the top for the name of the book would be pre-filled from the title of the book page that you just came from.

My url on the "book/detail.hmtl" page looks like this:

{% url 'books:take_notes' book.id %}

view.py - then for the take notes page I tried to prefill the NoteForm() like this:

def take_notes(request, book_id):
  mybook = Book.objects.get(pk=boo_id)
  form = NoteForm(initial={'book':mybook.title})

urls.py -

url(r'^take_notes/(?P<book_id>\d+)/$', views=take_notes, name='take_notes'),

The NoteForm() has 3 fields

class NoteForm(forms.ModelForm):
    class Meta:
        model = Note 
        fields = ('book', 'title', 'note',)
        widgets = {
            'note': forms.Textarea,
        }

When I use initial for "title" it will prepopulate, but it won't for 'book' because it is a drop down box. Any ideas? Thanks.

Upvotes: 1

Views: 1901

Answers (2)

Rohan
Rohan

Reputation: 53386

Try setting book_id instead of book in the view as

 form = NoteForm(initial={'book_id':book_id})

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600049

You're trying to prepopulate the select box by passing the title, which is presumably what is displaying in the control. But you should pass the underlying value, which in the case of a ForeignKey is the id of the related object.

Upvotes: 1

Related Questions