简体   繁体   中英

How to populate formview with model data when fetched via GET

I have the form display info via GET request, currently I assign a new form in get_context_data, is there a better way to do it? And http decorator doesn't work too.

@require_http_methods(['GET',])
class UniversityDetail(SingleObjectMixin, FormView):
    model = KBUniversity
    form_class = KBUniversityForm
    template_name = 'universities/form.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(UniversityDetail, self).get(self, request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(UniversityDetail, self).get_context_data(**kwargs)
        context['form'] = KBUniversityForm(instance=self.object)
        context['university_id'] = self.object.pk
        return context

Use UpdateView instead of FormView with SingleObjectMixin . In 99% of the cases you should not override the get method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM