Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Admin inlines linked indirectly by a shared UUID instead of by foreign key
- # models.py
- import uuid
- from django.db import models
- class Post(models.Model):
- nonce = models.CharField(max_length=36)
- class FooPost(Post):
- body = models.TextField()
- class UploadedFile(models.Model):
- url = models.URLField(max_length=1024)
- nonce = models.CharField(max_length=36)
- @classmethod
- def get_unique_nonce(cls):
- while True:
- nonce = str(uuid.uuid4())
- if not cls.objects.filter(nonce=nonce).exists():
- return nonce
- class Attachment(UploadedFile):
- post = models.ForeignKey(Post)
- # views.py
- class FooPostForm(forms.ModelForm):
- def __init__(self, *args, **kwargs):
- super(PostForm, self).__init__(*args, **kwargs)
- self.initial.setdefault('uuid', UploadedFile.get_unique_uuid())
- def save(self, *args, **kwargs):
- obj = super(FooPostForm, self).save(*args, **kwargs)
- if kwargs.get('commit', True):
- for file in UploadedFile.objects.filter(nonce=obj.nonce)
- Attachment(uploadedfile_ptr=file, post=obj).save_base(raw=True)
- return obj
- class Meta:
- model = FooPost
- def foo_post(request):
- assert request.method == 'POST'
- form = FooPostForm(request.POST)
- if form.is_valid():
- post = form.save()
- # ...
- class AttachmentForm(django.forms.ModelForm):
- def save(self, *args, **kwargs):
- obj = super(AttachmentForm, self).save(*args, **kwargs)
- obj.nonce = self.instance.nonce
- if kwargs.get('commit', True):
- obj.save()
- return obj
- class AttachmentInline(admin.TabularInline):
- exclude = ['nonce']
- model = Attachment
- form = AttachmentForm
- class PostAdminForm(django.forms.ModelForm):
- def __init__(self, *args, **kwargs):
- super(PostAdminForm, self).__init__(*args, **kwargs)
- self.initial.setdefault('nonce', S3File.get_unique_nonce())
- # A particular kind of post
- class FooPostAdmin(admin.ModelAdmin):
- form = PostAdminForm
- inlines = [AttachmentInline]
Add Comment
Please, Sign In to add comment