创建对象B时,使用对象B的ForeignKey创建对象A

时间:2018-12-07 08:30:11

标签: django python-3.x django-views

在Django管理面板的文本编辑器中创建帖子时,我上传了文件。我想通过外键将此文件与当前帖子链接。问题是该职位尚未创建,但我需要参考它。 我的模特:

class UploadFile(models.Model):
    upload_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, related_name="uploaded_file_author")
    file = models.FileField(null=True, blank=True, upload_to='files/%Y/%m/%d/',)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="file_post")

我的观点:

@require_POST
def file_upload(request):
    reqfile = UploadFile.objects.create(file=request.FILES['file'], upload_by=request.user, **post="need an object here")**
    return JsonResponse({'fileurl': reqfile.file.url})

我的ajax请求上传文件:

file_picker_callback: function(cb, value, meta) {
    if (meta.filetype == 'file') {
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'MIME_type');

        input.onchange = function () {
            var file = this.files[0];
            var reader = new FileReader();

            // FormData
            var fd = new FormData();
            var files = file;
            fd.append("file",files);

            // AJAX
            jQuery.ajax({
                url: "/fileupload/file/",
                type: "POST",
                data: fd,
                dataType: 'json',
                contentType: false,
                processData: false,
                cache: false,
                async: true
            }).done(function(response){
                var location = response.fileurl;
                reader.onload = function(){
                    // call the callback and populate the Title field with the file name
                    cb(location, { download : files.name });
                };
                reader.readAsDataURL(files);
            });
        };
        input.click();
    }
}

我的管理员:

from django.contrib import admin
from .models import Post, UploadMedia, UploadFile, UploadImage
from .forms import MyTextForm
# Register your models here.


class PostModelAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title", )}
    list_display = ["title", "updated", "created"]
    list_display_links = ["title"]
    list_filter = ["created", "tags"]
    search_fields = ["title", "content",]
    form = MyTextForm

    class Meta:
        model = Post

    class Media:
        js = ('//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', 'js/csrf_setup.js',
              'js/tinymce/tinymce.js', 'js/init-tinymce.js',)


admin.site.register(Post, PostModelAdmin)

2 个答案:

答案 0 :(得分:1)

如果未创建POST,但需要创建UploadFile实例,则可以将null = True添加到发布字段。

post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name="file_post")

创建帖子后,可以通过以下方式将其链接到您的upload_file实例:

upload_file.post = Post.objects.create(...)
upload_file.save()

答案 1 :(得分:0)

只需创建

@require_POST
def file_upload(request):
    post = Post.objects.create(....)
    reqfile = UploadFile.objects.create(file=request.FILES['file'], upload_by=request.user, post=post)
    return JsonResponse({'fileurl': reqfile.file.url})

或检索帖子实例并将其传递到那里:

from django.shortcuts import get_object_or_404

@require_POST
def file_upload(request, pk):
    post = get_object_or_404(Post, pk=pk)
    reqfile = UploadFile.objects.create(file=request.FILES['file'], upload_by=request.user, post=post)
    return JsonResponse({'fileurl': reqfile.file.url})