8

这一定是一件非常简单的事情,但我似乎无法通过它..

我试图构建一个用户可以更新 ModelForm 的表单。首先,他插入一个用户 ID,然后我想向他展示预填充原始数据的表单,以便他只能更改他想要的字段。

在我的朋友 google、stackoverflow 和 django 文档的帮助下,我得出了这个结论:

视图.py

 user = User.objects.get(user_id=usr)  
 if request.method == 'POST':  
      form = TableForm(request.POST)  
      if form.is_valid():  
           #do something  
 else:  
      form = TableForm(instance=user)  
      return render_to_response('template.html',{'form':form})  

表格.py

class TableForm(forms.ModelForm):
     pres_clinic = forms.ModelChoiceField(queryset=PresClinic.objects.all(),
        widget=SelectWithPop(), label=ugettext("Clinic presentation"),
        required=False)

     MAYBECHOICES = (
         ('', '---------'),
         (ugettext('Yes'), ugettext('Yes')),
         (ugettext('No'), ugettext('No')))

     bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext(
            "BCG scar"), required=False)
     mantoux_register = forms.ChoiceField(choices=MAYBECHOICES,
        label=ugettext("Mantoux register"), required=False)
     date_diag = forms.DateField(widget=DateTimeWidget, label=ugettext(
         "Diagnosis date"), required=False)
     situation = forms.ModelChoiceField(queryset=Situation.objects.all(),
        widget=SelectWithPop(), label=ugettext("Patient status"),
        required=False)
     date_situation = forms.DateField(widget=DateTimeWidget, label=ugettext(
        "Date patient status"), required=False)

  class Meta:
    model = Table
    fields = ('pres_clinic', 'bcg_scar', 'mantoux_register',
            'date_diag', 'situation', 'date_situation')

def clean(self):
    cleaned_data = self.cleaned_data
    diag = cleaned_data.get('date_diag')

    errors = []

    now = datetime.date.today()

    if diag is not None and diag != u'':
        if diag > now:
            errors.append(ugettext('The field "Diagnosis date" should be '
                'smaller than the actual date'))
    if errors:
        raise ValidationError(errors)

    return cleaned_data

模板:

 {{ form }} # presents the empty form and not the data from that user  

django的版本是1.4

谁能告诉我出了什么问题以及为什么我看不到填充的表格?

非常感谢你

4

2 回答 2

14

您需要定义一个用于初始数据的字典,并将 TableForm(instance=user) 更改为 TableForm(initial=dict),例如:

 user = User.objects.get(user_id=usr)  
 if request.method == 'POST':  
     form = TableForm(request.POST)  
     if form.is_valid():  
         #do something  
 else:  
      data = {'pres_clinic' : 'value', 'bcg_scar' : 'value', 'mantoux_register' : 'value'}
      form = TableForm(initial=data)  
 return render_to_response('template.html',{'form':form})  

我还将渲染从 if 语句中响应,因此如果表单无效,页面应该重新加载并显示任何错误。

有关django 文档的更多信息,请点击此处

我希望这有帮助!

于 2013-04-06T16:10:59.300 回答
4

你可以试试'model_to_dict'

from django.forms.models import model_to_dict

 user = User.objects.get(user_id=usr)  
 if request.method == 'POST':  
     form = TableForm(request.POST)  
     if form.is_valid():  
         #do something  
 else:          
     form = TableForm(initial=model_to_dict(user))  
 return render_to_response('template.html',{'form':form})
于 2016-12-29T14:30:46.243 回答