Login

UpdateView

Author:
edcrewe
Posted:
February 15, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Whoops just an alternative implementation of UpdateView

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class ModelFormView(FormView):
    """ Use (?P<id>[\-0-9]*) urls.py lookups to populate form instance """

    lookups = ['id', ]

    def get_form_kwargs(self):
       """ Override to add instance """
        self.get_instance()
        kwargs = {'initial': self.get_initial()}
        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'instance': self.instance,
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        return kwargs

    def get_instance(self):
        """ Add in self.lookups list of attributes to search for instance """
        model = self.get_form_class()._meta.model
        for lookup in self.lookups:
            look = self.kwargs.get(lookup, '')
            if look:
                try:
                    self.instance = model.objects.get(*((lookup, look),))
                    self.pk = self.instance.pk
                    return self.pk
                except ObjectDoesNotExist:
                    self.instance = None
                                                                                                                          
        return 0

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.