0
我有帖子和附件。我的问题的根源在于,我希望可以在创建附件之前创建附件(因为用户在填写帖子的详细信息之前使用花哨的Ajax上传小部件上传附件)。我得到的解决方案是给每个帖子一个UUID。 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()
# ...
这种运作良好,在我的应用程序,但我想它也是在管理界面工作。如何在帖子的管理员表单中嵌入附件,即使它们是通过共享的随机数间接链接而不是通过外键链接的?