views:

234

answers:

1

I've seen some similar questions, but nothing that quite pointed me in the direction I was hoping for. I have a situation where I have a standard django form built off of a model. This form has a drop down box where you select an item you want to post a comment on. Now I'd like people to be able to browse by items, and click a link to comment on that particular item. What I'd like is for when a user clicks that link they'll be presented with the same old form, however, the dropbox will be defaulted to the item they wanted to comment on.

Is there a sane way to do this with the existing form? Should I create a separate form entirely for this need?

As a note, this isn't a true comment system, and isn't intended to be. One idea I had was to construct urls like:

comment/?q=item1

Catching the 'item1' section, and then over riding the save function to force that into the form, while hiding the company in the form. From a UI standpoint, I'm not ecstatic with that idea though. Any thoughts or ideas?

+1  A: 

If I'm reading your question right, this is a fairly common use-case and well support by django forms. You can use the same form for both scenarios you describe.

Let's say the item to be commented has the primary key 5. You would build a link for the user to click with a URL that looks like this:

<a href="/comment/5/">Comment on me</a>

(This would work just as well with a slug field, though see the comment below about how the identifier must match the ID in the field's choices: /comment/my_item_1/)

Your view would pick up the parameter, and pass it on to the form in the initial parameter:

def show_comment_form(request, item_id):
    form = MyCommentForm(initial={'item_drop_down':item_id})

The form will be displayed with the drop-down pre-selected. For this example to work, of course, the item_id parameter must match whatever the choice identifier is for the item field (if it's built automatically off a model field, as it sounds, that will probably be the primary key of the available items' class).

By this I mean that, if the choices were to look like:

choices = ( (1, 'Item 1'),
            (2, 'Item 2') )

Then the item_id should be 1 or 2 as that's what will be in the resulting <select> options (ie: <option value="1">Item 1</option>). Automatically created ModelForm classes will take care of this for you, otherwise just be vigilant.

You can find more information here in the django docs: Dynamic Initial Values

Jarret Hardie