Wednesday, January 18, 2017

Re: prepopulate form with model instance values using UpdateView and ModelForm

On Wednesday 18 January 2017 14:26:52 Benjamin Dauer wrote:

> Hi Melvyn,

>

> That's exactly what I'm trying to do, but prior to making the changes

> it wasn't prepopulating. At each stage I tested and was getting blank

> fields albeit based off of the correct model.

>

> Maybe it's because I don't provide the pk in the URL? I was trying to

> avoid that.

 

Gotcha! By default the class-based generic views provide two ways to identify the instance:

- pk

- slug

 

Look at slug_field and slug_url_kwarg here.

 

But in the end, this is passed to get_object() (method also shown on that handy page) and this shall return the instance to be shown.

The tricky part about passing this in a form, is that you're fighting the order: the form is processed after the instance is loaded.

 

The best way to go is to put something in the URL that uniquely identifies the object and then override get_object() to work with that. Note that little added security is gained from hiding the PK, but if user-friendly URLs is what you're after, slugs (or some other field(s) with unique=True) are the way to go.

 

--

Melvyn Sopacua

No comments:

Post a Comment