Django 调用 @classmethod 从 SystemCreateView 创建

Django call @classmethod create from SystemCreateView

我想通过SystemCreateView调用@classmethod创建System模型。但是,当前未调用创建类方法,因此未计算系统模型的 z-属性,但仍保持默认值 4.

模型Class的简化版本为:

class System(models.Model):
    project     = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE)
    x           = models.IntegerField(default=1)
    y           = models.IntegerField(default=4)

    # calculated properties
    z = models.IntegerField(default=4)

    @classmethod
    def create( cls, project, x, y):
        system = cls(project=project, x=x, y=y)

        # Calculated properties
        system.z = x*y
        return system

SystemForm 定义为:

class SystemForm(forms.ModelForm):
    class Meta:
        model = System
        fields = [
            'x',
            'y'
        ]

CreateView目前如下:

class SystemCreateView(LoginRequiredMixin, CreateView):
    model = System
    template_name = 'system/create.html'
    form_class = SystemForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        project_id = self.kwargs['pk']
        project = get_object_or_404(Project, pk=project_id)
        obj.project = project
        return super(SystemCreateView, self).form_valid(form)

    def get_context_data(self, *args, **kwargs):
        context = super(SystemCreateView, self).get_context_data(*args, **kwargs)
        context['project_id'] = self.kwargs['pk']
        return context

您可以使用表单清理数据中的值调用 class 方法,而不是保存表单。然后你应该 return 重定向响应而不是调用 super() (这将保存表单。

self.obj = System.create(project, x=form.cleaned_data['x'], y=form.cleaned_data['y'])
return redirect(self.get_success_url())