Django形成自定义字段

时间:2017-07-12 14:01:47

标签: python django forms

如果我们有一个modelForm,其中某些字段与模型不直接对应,那么我们如何让表单以自定义方式处理它们,同时默认保存其余字段?

例如,我们有一个支持多语言描述的项目模型。模型是:

class Item(models.Model):
    name = models.ForeignKey(Localization)
    on_sale = models.BooleanField(default=False)

class Localization(models.Model):
    de = models.TextField(blank=True, null=True, verbose_name='de')
    eng = models.TextField(blank=True, null=True, verbose_name='eng')

添加/编辑项目的表单如下所示:

class ItemForm(forms.ModelForm):
    id = forms.CharField(widget=forms.HiddenInput(), max_length=128, label='')
    name_eng = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='eng')
    name_de = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='de')
    on_sale = forms.CharField(widget=forms.CheckboxInput(), label='on_sale', )

    class Meta:
        model = Item
        fields = ('id', 'on_sale',)

现在保存此表单应该做的是新项目 - 使用两个名称字段创建本地化对象,然后创建一个带有on_sale字段的Item对象,链接到Localization对象。对于现有项目 - 编辑相应的Localization对象,然后编辑Item本身的on_sale字段。

我使用单独的函数完成任务,该函数分别处理请求中的自定义字段,但是通过表单的save()方法完成所有操作看起来更好。或者我错了吗?

PS我很遗憾地问一个明显破旧的问题,但我完全没有按照其他例子做我想做的事。

更新

我实际上是通过这里的提示帮助我按照我想要的方式工作。代码如此,如果可以优化,请告诉我。

class NameForm(forms.ModelForm):
    # id = forms.CharField(widget=forms.HiddenInput(), max_length=128, label='')
    id = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='id', required=False)
    name_eng = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='eng')
    name_de = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='de')
    gender = forms.CharField(widget=forms.CheckboxInput(), label='gender', required=False)

    class Meta:
        model = Name
        fields = ('id', 'gender',)

    def save(self):
        instance = super(NameForm, self).save(commit=False)
        obj_id = self.cleaned_data['id']
        if obj_id:
            instance_bd = Name.objects.get(pk=obj_id)
            loc = instance_bd.name
            loc.de = self.cleaned_data['name_de']
            loc.eng = self.cleaned_data['name_eng']
            loc.save()
            instance.id = obj_id
        else:
            loc = Localization(de=self.cleaned_data['name_de'], eng=self.cleaned_data['name_eng'])
            loc.save()
        instance.name = loc
        instance.save()
        return instance

视图只是

@login_required
def admin_lists(request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            form.save()
    forms = {'name': NameForm()}
    return render(request, 'admin/lists.html', {'forms': forms})

1 个答案:

答案 0 :(得分:0)

在这种情况下最好不要使用forms'save方法,试试这个

if request.method == 'POST':
    form = ItemForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        post = request.POST
        set_name_eng= post['name_eng']
        set_name_de= post['name_de']
        set_on_sale = post['on_sale']

        #now here we create the anothers objects
        a = Localization(de=set_name_de, eng=set_name_eng)
        a.save()

        b = Item(name=a, on_sale=sale)
        b.save()

我不明白最后一部分,但我认为你需要更好地组织你的模特和表格,让我知道,我会尽力帮助你