Skip to content

Instantly share code, notes, and snippets.

@karthikbgl
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karthikbgl/ab235e09b963dbc05af5 to your computer and use it in GitHub Desktop.
Save karthikbgl/ab235e09b963dbc05af5 to your computer and use it in GitHub Desktop.
Django ModelAdmin "Save as New"
class MyModelAdminForm(forms.ModelForm):
'''
To add the option 'Save as New', by default does not work for reverse
ManyToMany/ForeignKey fields. In other words, does not copy over the
reverse attributes. A simple workaround to make this happen is:
update the cleaned_data and returning it in the context.
Something like this:
'''
def clean(self, *args, **kwargs):
cd = self.cleaned_data
if self.request.method == 'POST' and '_saveasnew' in self.request.POST:
#Lets say the slug attribute is unique:
name = cd.get('name', '')
slug = cd.get('slug', '')
slug_exists = Campaign.objects.filter(slug=slug).exists()
while slug_exists:
name = name + ' Copy'
slug = slug + '-copy'
slug_exists = Campaign.objects.filter(slug=slug).exists()
cd.update({'name': name, 'slug': slug})
return cd
class Meta:
model = MyModel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment