管理内联由共享UUID间接链接,而不是由外键链接

时间:2011-10-05 10:27:40

标签: django

我有帖子和附件。我的问题的根源是我希望能够在创建附件之前创建附件(因为用户在填写帖子的详细信息之前使用花哨的Ajax上传小部件上传附件)。我到达的解决方案是给每个帖子一个UUID。在实例化帖子的模型时(即,在创建帖子之前)生成UUID。上传附件时,它们与此UUID相关联。在我提出问题之前,这里是代码草图,以便更准确地显示正在发生的事情:

 # 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()
      # ...

这在我的应用程序中运行良好,但我希望它也能在管理界面中运行。我如何在帖子的管理表单中内联附件,即使它们是由共享的nonce而不是外键间接链接的?

1 个答案:

答案 0 :(得分:0)

为内联提供自定义模型表单:

 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

从内联中排除nonce字段:

 class AttachmentInline(admin.TabularInline):

     exclude = ['nonce']
     model = Attachment
     form = AttachmentForm

为新帖子想出一个新的nonce:

 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]