Changes between Version 5 and Version 6 of CookBookNewformsAdminAndUser


Ignore:
Timestamp:
Aug 9, 2008, 12:27:37 PM (16 years ago)
Author:
oyvind
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • CookBookNewformsAdminAndUser

    v5 v6  
    22How to set the current user on the model instance using newforms admin.
    33
    4 '''TODO''' make it work with inline edited models, update code to show admin history
     4'''TODO''' make it work with inline edited models
    55
    66
     
    88#!python
    99
    10 from django.http import Http404, HttpResponse, HttpResponseRedirect
    11 from django.utils.html import escape
    12 from django.utils.safestring import mark_safe
    13 from django.db import models, transaction
     10# models.py
     11
    1412from django.contrib.auth.models import User
    15 from django.utils.encoding import force_unicode
    16 from django.utils.translation import ugettext as _
    1713
    1814class Post(models.Model):
    1915    user = models.ForeignKey(User)
    2016    content = models.TextField()
     17
     18# admin.py
    2119
    2220from django.contrib import admin
     
    2725
    2826    def __call__(self, request, url):
     27
    2928        self.user = request.user
     29
    3030        return super(PostModelAdmin, self).__call__(request, url)
    3131
    32     def save_add(self, request, model, form, formsets, post_url_continue):
    33         """
    34         Saves the object in the "add" stage and returns an HttpResponseRedirect.
     32    def save_model(self, request, form, change):
    3533
    36         `form` is a bound Form instance that's verified to be valid.
    37         """
    38         from django.contrib.admin.models import LogEntry, ADDITION
    39         from django.contrib.contenttypes.models import ContentType
    40         opts = model._meta
    4134        new_object = form.save(commit=False)
     35
    4236        new_object.user = self.user
    4337        new_object.save()
     38
    4439        form.save_m2m()
    45 
    46         if formsets:
    47             for formset in formsets:
    48                 # HACK: it seems like the parent obejct should be passed into
    49                 # a method of something, not just set as an attribute
    50                 formset.instance = new_object
    51                 formset.save()
    52 
    53         pk_value = new_object._get_pk_val()
    54         LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), ADDITION)
    55         msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': opts.verbose_name, 'obj': new_object}
    56         # Here, we distinguish between different save types by checking for
    57         # the presence of keys in request.POST.
    58         if request.POST.has_key("_continue"):
    59             request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
    60             if request.POST.has_key("_popup"):
    61                 post_url_continue += "?_popup=1"
    62             return HttpResponseRedirect(post_url_continue % pk_value)
    63         if request.POST.has_key("_popup"):
    64             return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
    65                 # escape() calls force_unicode.
    66                 (escape(pk_value), escape(new_object)))
    67         elif request.POST.has_key("_addanother"):
    68             request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
    69             return HttpResponseRedirect(request.path)
    70         else:
    71             request.user.message_set.create(message=msg)
    72             # Figure out where to redirect. If the user has change permission,
    73             # redirect to the change-list page for this object. Otherwise,
    74             # redirect to the admin index.
    75             if self.has_change_permission(request, None):
    76                 post_url = '../'
    77             else:
    78                 post_url = '../../../'
    79             return HttpResponseRedirect(post_url)
    80     save_add = transaction.commit_on_success(save_add)
    81 
    82     def save_change(self, request, model, form, formsets=None):
    83         """
    84         Saves the object in the "change" stage and returns an HttpResponseRedirect.
    85 
    86         `form` is a bound Form instance that's verified to be valid.
    87 
    88         `formsets` is a sequence of InlineFormSet instances that are verified to be valid.
    89         """
    90         from django.contrib.admin.models import LogEntry, CHANGE
    91         from django.contrib.contenttypes.models import ContentType
    92         opts = model._meta
    93         new_object = form.save(commit=False)
    94         new_object.user = self.user
    95         new_object.save()
    96         form.save_m2m()
    97         pk_value = new_object._get_pk_val()
    98 
    99 
    100         if formsets:
    101             for formset in formsets:
    102                 formset.save()
    103 
    104         # Construct the change message. TODO: Temporarily commented-out,
    105         # as manipulator object doesn't exist anymore, and we don't yet
    106         # have a way to get fields_added, fields_changed, fields_deleted.
    107         change_message = []
    108         #if manipulator.fields_added:
    109             #change_message.append(_('Added %s.') % get_text_list(manipulator.fields_added, _('and')))
    110         #if manipulator.fields_changed:
    111             #change_message.append(_('Changed %s.') % get_text_list(manipulator.fields_changed, _('and')))
    112         #if manipulator.fields_deleted:
    113             #change_message.append(_('Deleted %s.') % get_text_list(manipulator.fields_deleted, _('and')))
    114         #change_message = ' '.join(change_message)
    115         if not change_message:
    116             change_message = _('No fields changed.')
    117         LogEntry.objects.log_action(request.user.id, ContentType.objects.get_for_model(model).id, pk_value, force_unicode(new_object), CHANGE, change_message)
    118 
    119         msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': opts.verbose_name, 'obj': new_object}
    120         if request.POST.has_key("_continue"):
    121             request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
    122             if request.REQUEST.has_key('_popup'):
    123                 return HttpResponseRedirect(request.path + "?_popup=1")
    124             else:
    125                 return HttpResponseRedirect(request.path)
    126         elif request.POST.has_key("_saveasnew"):
    127             request.user.message_set.create(message=_('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': opts.verbose_name, 'obj': new_object})
    128             return HttpResponseRedirect("../%s/" % pk_value)
    129         elif request.POST.has_key("_addanother"):
    130             request.user.message_set.create(message=msg + ' ' + (_("You may add another %s below.") % opts.verbose_name))
    131             return HttpResponseRedirect("../add/")
    132         else:
    133             request.user.message_set.create(message=msg)
    134             return HttpResponseRedirect("../")
    135     save_change = transaction.commit_on_success(save_change)
     40       
     41        return new_object
    13642
    13743admin.site.register(Post, PostModelAdmin)
Back to Top