user298519
user298519

Reputation: 1190

Django: How to put existing fields when displaying form for UpdateView?

I'm making an episode tracker website and when I want the user to edit a show, the form provided starts with empty fields. How do I fill the form with already existing fields? For example, when a user is watching a show and is originally at episode 5, how do I call the update form with the Episode field already at 5 instead of it being empty?

views.py

class ShowUpdate(UpdateView):
    model = Show
    slug_field = 'title'
    slug_url_kwarg = 'show'
    fields = ['description', 'season', 'episode']

show-detail.html

<form action="{% url 'show:show-update' show=show.title %}" method="post">
{% csrf_token %}
<button type="submit">Edit</button>
</form>

Upvotes: 2

Views: 1220

Answers (1)

Cody Parker
Cody Parker

Reputation: 1121

You can fill a form with the values in an UpdateView with

def get_initial(self):
    return { 'field1': 'something', 'field2': 'more stuff' }

Also the UpdateView inherits from the SingleObjectMixin, which provides get_object and get_queryset, so you could use either to get the object data you want to populate the form with. Something like:

def get_object(self):
        return Show.objects.get(pk=self.request.GET.get('pk')) 

Check out the docs for more info

Also, if you have a pk or slug as a parameter in your url, it should pick it up as well. Such as:

url(r'^shows/update/(?P<pk>\d+)/$',ShowUpdate.as_view())

Upvotes: 1

Related Questions