Created
January 5, 2014 06:01
-
-
Save powellc/8264947 to your computer and use it in GitHub Desktop.
ModelAdmin code to make save_as work for models with unique slugs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_view(self, request, form_url='', extra_context=None): | |
save_as_new = request.POST.get("_saveasnew", '') | |
if extra_context is None: | |
extra_context = {} | |
# keep the save as new in case of validation errors | |
extra_context['save_as_new'] = save_as_new | |
# but if it is a real new addition, remove _saveasnew from POST | |
if not save_as_new and '_saveasnew' in request.POST: | |
del request.POST['_saveasnew'] | |
if save_as_new: | |
request.POST['slug'] = self.make_slug_unique(request.POST['slug']) | |
return super(RegistrationFormAdmin, self).add_view(request, form_url, | |
extra_context=extra_context) | |
def make_slug_unique(self, slug): | |
counter = 1 | |
while True: | |
not_unique = RegistrationForm.objects.filter(slug=slug) | |
if len(not_unique) == 0: | |
return slug | |
slug = '{0}-{1}'.format(slug, counter) | |
counter += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment