generic.edit.CreateView分配默认值并插入数据库

时间:2016-12-06 17:04:29

标签: python django model django-class-based-views

我有以下基于类的视图,它使用我的模型生成“创建”屏幕:

class ProjectCreateView(generic.edit.CreateView):
    model = Project
    fields = ['project_title','project_description','created_date']
    template_name = 'steps/project-detail.html'
    success_url = reverse_lazy('index')   

型号:

class Project(models.Model):
    project_title = models.CharField(max_length=200)
    project_description = models.CharField(max_length=200, default="")
    created_date = models.DateTimeField('date created')
    owner = models.ForeignKey(User)

    def __str__(self):
        return self.project_title 

现在,问题在于,如果我不希望'created_date'出现在实际表单上。相反,我希望每当按下提交按钮或将记录添加到数据库时自动填充它。我怎样才能做到这一点?

最后,是否可以默认指定owner字段?也就是说,我需要使用创建此记录的用户的信息填充该字段。

1 个答案:

答案 0 :(得分:2)

ownercreated_date移出您的字段列表。然后覆盖form_valid并在调用super()之前在表单的实例上设置值。

由于您要设置所有者,因此可以使用LoginRequiredMixin确保只有已登录的用户才能访问该视图。

from datetime import datetime

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView


class ProjectCreateView(LoginRequiredMixin, CreateView):
    model = Project
    fields = ['project_title','project_description']
    template_name = 'steps/project-detail.html'
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        form.instance.owner = self.request.user
        form.instance.created_date = datetime.now()
        return super(ProjectCreateView, self).form_valid(form)