Django Forms - 在提交时指定ModelForm模型?

时间:2015-08-25 17:37:26

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

我正在创建一个表单,该表单可以根据用户从不同视图中选择的模型将数据保存到四个表中的一个。我不想为每个模型创建相同的表单。

当用户点击提交时,有没有办法将模型名称传递给表单?

以下是代码:

models.py

class TagModel(MP_Node):
    slug = models.SlugField(max_length=64, blank=True)
    name = models.CharField(max_length=64)

    generic_objecttag_set = GenericRelation('ObjectTag')

    def __str__(self):
        return self.name

    class Meta:
        unique_together = (
            ('slug',),
        )
        abstract = True


class Concept(TagModel):
    class Meta:
        verbose_name = 'Concepts'


class Difficulty(TagModel):
    class Meta:
        verbose_name = 'Difficulty'

class QuestionType(TagModel):
    class Meta:
        verbose_name = 'Question Type'

class QuestionFormat(TagModel):
    class Meta:
        verbose_name = 'Question Format'

forms.py

class TagModelForm(forms.ModelForm):
    def clean(self):
        cleaned_data = super(TagModelForm, self).clean()
        cleaned_data['slug'] = slugify(cleaned_data.get('name', ''))
        return cleaned_data

    class Meta:
        model = models.TagModelForm
        fields = ('slug', 'name',)
        widgets = {
            'slug': forms.HiddenInput(),
        }

views.py

class TagCreateView(FormView):
    form_class = forms.TagModelForm
    template_name = 'tags/create.html'


    @method_decorator(permission_required('tags.add_tag'))
    def dispatch(self, request, *args, **kwargs):
        arg_model = kwargs.get('tree_name', None)
        if arg_model:
            self.curr_model = get_model('tags', arg_model)
        return super(TagCreateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        data = form.cleaned_data
        curr_model = self.curr_model
        curr_model.add_root(**data)
        return super(TagCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse('tags:index')

1 个答案:

答案 0 :(得分:1)

我肯定会尝试表单继承并执行以下操作:

class TagForm(forms.ModelForm):
    def clean():
        #...
    # whatever other methods here, etc.


class ConceptTagForm(TagForm):
    class Meta:
        model = models.Concept

class DifficultyTagForm(TagForm):
    class Meta:
        model = models.Difficulty
# etc