使用Django的FormView

时间:2014-02-19 19:28:07

标签: python django django-forms

我有django模型:

class ProjectFile(models.Model):

    TYPES = (
        (1, "Public"),
        (2, "In Project"),
        (3, "Specific")
    )

    project = models.ForeignKey(Project)
    file = models.FileField(upload_to="files/")
    type = models.SmallIntegerField(choices=TYPES)

    created_by = models.ForeignKey(User)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.file.name + " - " + self.project.name

    def is_downloadable(self, user):
        if self.file.project.type == 1:
            return True

        return False

并形成:

class FileUploadForm(forms.ModelForm):

    class Meta:
        model = ProjectFile
        exclude = ['created_by', 'created_at', 'updated_at', 'project']

我的视图类(FormView)是:

class UploadFileView(FormView):
    form_class = FileUploadForm
    template_name = "project/file_upload.html"

所以,我现在的问题是:如何将数据添加到views.py UploadFileForm中的排除字段中。例如,created_by必须等于request.user

1 个答案:

答案 0 :(得分:1)

如果您的观点旨在创建ProjectFile,我建议您使用CreateView,并覆盖form_valid方法。

from django.views.generic import CreateView

class UploadFileView(CreateView):
    form_class = FileUploadForm
    template_name = 'project/file_upload.html'
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(UploadFileView, self).form_valid(form)

即使您希望使用FormView

,您仍然可以覆盖相同的方法