Guest User

Untitled

a guest
Aug 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. Admin inlines linked indirectly by a shared UUID instead of by foreign key
  2. # models.py
  3.  
  4. import uuid
  5. from django.db import models
  6.  
  7. class Post(models.Model):
  8. nonce = models.CharField(max_length=36)
  9.  
  10. class FooPost(Post):
  11. body = models.TextField()
  12.  
  13. class UploadedFile(models.Model):
  14. url = models.URLField(max_length=1024)
  15. nonce = models.CharField(max_length=36)
  16.  
  17. @classmethod
  18. def get_unique_nonce(cls):
  19.  
  20. while True:
  21. nonce = str(uuid.uuid4())
  22. if not cls.objects.filter(nonce=nonce).exists():
  23. return nonce
  24.  
  25.  
  26.  
  27. class Attachment(UploadedFile):
  28. post = models.ForeignKey(Post)
  29.  
  30. # views.py
  31.  
  32. class FooPostForm(forms.ModelForm):
  33.  
  34. def __init__(self, *args, **kwargs):
  35. super(PostForm, self).__init__(*args, **kwargs)
  36. self.initial.setdefault('uuid', UploadedFile.get_unique_uuid())
  37.  
  38. def save(self, *args, **kwargs):
  39. obj = super(FooPostForm, self).save(*args, **kwargs)
  40. if kwargs.get('commit', True):
  41. for file in UploadedFile.objects.filter(nonce=obj.nonce)
  42. Attachment(uploadedfile_ptr=file, post=obj).save_base(raw=True)
  43. return obj
  44.  
  45. class Meta:
  46. model = FooPost
  47.  
  48. def foo_post(request):
  49. assert request.method == 'POST'
  50. form = FooPostForm(request.POST)
  51. if form.is_valid():
  52. post = form.save()
  53. # ...
  54.  
  55. class AttachmentForm(django.forms.ModelForm):
  56.  
  57. def save(self, *args, **kwargs):
  58. obj = super(AttachmentForm, self).save(*args, **kwargs)
  59. obj.nonce = self.instance.nonce
  60. if kwargs.get('commit', True):
  61. obj.save()
  62. return obj
  63.  
  64. class AttachmentInline(admin.TabularInline):
  65.  
  66. exclude = ['nonce']
  67. model = Attachment
  68. form = AttachmentForm
  69.  
  70. class PostAdminForm(django.forms.ModelForm):
  71. def __init__(self, *args, **kwargs):
  72. super(PostAdminForm, self).__init__(*args, **kwargs)
  73. self.initial.setdefault('nonce', S3File.get_unique_nonce())
  74.  
  75. # A particular kind of post
  76. class FooPostAdmin(admin.ModelAdmin):
  77. form = PostAdminForm
  78. inlines = [AttachmentInline]
Add Comment
Please, Sign In to add comment