1

我有一个 Django 项目,其中有一个从 DjangoCreateView类继承的视图。此视图用于将文件上传到服务器,并使用UploadedFile我创建的模型。UploadedFile还需要与项目相关联。

项目 ID 作为 URL 的一部分传入:(r'^projects/(?P<proj_key>\d+)/$', UploadedFileCreateView.as_view(), {}, 'upload-new')

问题是我不确定将这个键与我的model. 是否有CreateView我应该重写的方法或其祖先之一创建model,或者这可以在我的代码中的任何地方在我已经重写的方法之一中完成(虽然这感觉很hacky)。

此外,projectmy 的属性UploadedFile被定义为ForeignKeytype Project。我如何获得Project与之关联的?

这是我的model定义:

class Project(models.Model):
    """This is a project that is owned by a user and contains many UploadedFiles."""
    name = models.CharField(max_length=200)

class UploadedFile(models.Model):
    """This represents a file that has been uploaded to the server."""
    STATE_UPLOADED = 0
    STATE_ANNOTATED = 1
    STATE_PROCESSING = 2
    STATE_PROCESSED = 4
    STATES = (
        (STATE_UPLOADED, "Uploaded"),
        (STATE_ANNOTATED, "Annotated"),
        (STATE_PROCESSING, "Processing"),
        (STATE_PROCESSED, "Processed"),
    )

    status = models.SmallIntegerField(choices=STATES,
        default=0, blank=True, null=True) 
    file = models.FileField(upload_to=settings.XML_ROOT)
    project = models.ForeignKey(Project)

    def __unicode__(self):
        return self.file.name

    def name(self):
        return os.path.basename(self.file.name)

    def save(self, *args, **kwargs):
        if not self.status:
            self.status = self.STATE_UPLOADED
        super(UploadedFile, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        os.remove(self.file.path)
        self.file.delete(False)
        super(UploadedFile, self).delete(*args, **kwargs)

这是我的视图定义:

class UploadedFileCreateView(CreateView):
    model = UploadedFile

    def form_valid(self, form):
        logger.critical("Inside form_valid")
        self.object = form.save()
        f = self.request.FILES.get('file')
        data = [{'name': f.name,
            'url': settings.MEDIA_URL + "files/" + f.name.replace(" ", "_"),
            'project': self.object.project.get().pk,
            'delete_url': reverse('fileupload:upload-delete',
                args=[self.object.id]),
            'delete_type': "DELETE"}]
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return super(UploadedFileCreateView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(UploadedFileCreateView, self).get_context_data(**kwargs)
        return context
4

1 回答 1

1

你可以在你打电话的地方做form.save()。只需传递commit=False,以便在添加项目 ID 之前它不会将其保存到数据库中。例如:

self.object = form.save(commit=False)
self.object.project_id = self.kwargs['proj_key']
self.object.save()

只需确保您的表单不包括项目字段。

编辑:要排除该字段,excludes请向表单元类添加一个变量:

class UploadedFileForm(forms.ModelForm):
    class Meta:
        model = UploadedFile
        excludes = ('project',)
于 2013-10-20T01:43:44.047 回答