Django 2.0:如果值

时间:2018-10-19 15:41:29

标签: django django-forms django-templates

我将 ModelChoiceField 更改为 TextInput 。 我在一个类中有一个名为“文件名”的字段,其类型为:models.ForeignKey('Filename', on_delete=models.SET_NULL, null=True, blank=True),如下所示:

models.py

class Event(models.Model):
    name = models.CharField('Name', max_length=100, blank=True, default='')
    filename = models.ForeignKey('Filename', on_delete=models.SET_NULL, null=True, blank=True)


class Filename(models.Model):
    name = models.CharField('Name', max_length=50)

    def __str__(self):
        return self.nome    

这是我的“ forms.py”的一部分,在定义模板(myappname / templates / myappname / event_edit.html)后,我在前端使用show form

forms.py

class EventEditForm(forms.ModelForm):
    def __init__(self, data=None, *args, **kwargs):
        if data is not None:
            data = data.copy()
            if data['filename']:
                f, f_created = Filename.objects.get_or_create(nome=data['filename'])
                data['filename'] = m.id
        super(EventEditForm, self).__init__(data=data, *args, **kwargs)

        self.fields['filename'] = forms.ModelChoiceField(queryset=Filename.objects.all(), widget=forms.TextInput(attrs={'class': 'form-control', 'value':self.instance.filename}))
        self.fields['filename'].required = False

    class Meta:
        model = Event
        fields = ['name', 'filename']

这是我的 event_edit.html

<form method="post" class="form-horizontal">
    {% csrf_token %}
    {% for field in event_form %}
        <div class="form-group form-group-lg">
            <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{field.label}}</label>
            <div class="col-sm-6">
                {{ field }}
            </div>
            <div class="col-sm-4">
            {{ field.errors }}
            </div>
        </div>
    {% endfor %}
    <div class="form-group">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary btn-lg center-block">Save</button>
        </div>
    </div>
</form> 

问题是,如果我将ModelChoiceField重写为TextInput,则“文件名”字段将显示 id 而不是字段 name 。 否则,如果我将其保留为选择字段,它将正确显示值而不是id。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

根据您的评论和EventEditForm中的代码,您需要一种表单:

  • 显示Event.name和链接的Filename.name
  • 使用提交的名称更新Event.name
  • 使用提交的文件名查找或创建Filename并更新Event.filename

这应该有效:

class EventEditForm(forms.ModelForm):
    """
    Calling form.save() will:

    * update the Event.name
    * update the Event.filename with a Filename instance 
      found or created using the supplied name

    """
    fname = forms.CharField(
        label='Filename',
        required=False,
        widget=forms.TextInput(attrs={'class': 'form-control'}),
    )

    class Meta:
        model = Event
        fields = ['name',]
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
        }

    def __init__(self, *args, **kwargs):
        super(EventEditForm, self).__init__(*args, **kwargs)
        self.initial['fname'] = self.instance.filename

    def save(self, commit=True):
        instance = super(EventEditForm, self).save(commit=False)
        cleaned_fname = self.cleaned_data['fname']
        if cleaned_fname:
            f, f_created = Filename.objects.get_or_create(name=cleaned_fname)
            instance.filename = f
        else:
            instance.filename = None
        if commit:
            instance.save()
        return instance