Last active
August 29, 2015 14:04
-
-
Save karthikbgl/ab235e09b963dbc05af5 to your computer and use it in GitHub Desktop.
Django ModelAdmin "Save as New"
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
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