Django ModelForm,初始数据未显示在重新显示上

时间:2011-06-24 18:35:54

标签: python django django-forms

我有一个Django ModelForm,传递了一些初始数据。到目前为止工作正常。

但是,如果用户没有填写所有数据,或者犯了另一个错误,则在重新显示表单时不会再次查找初始值。

这是一段代码:

class TrainingAddForm(forms.ModelForm):
class Meta:
    model = TrainingTasks
    fields = ('task','ac_reg','date','wo_no')

def __init__(self, *args, **kwargs):
    super(TrainingAddForm, self).__init__(*args, **kwargs)
    self.fields['task'].required = False
    self.fields['task'].widget.attrs['disabled'] = 'disabled'
    self.fields['date'].widget = widgets.AdminDateWidget()

def clean_task(self):
    return

在form.py中:

def add_trainingtask(request, task_id):

if request.POST:
    form = TrainingAddForm(request.POST)

    if form.is_valid():
        tt = TrainingTasks(
            trainee = request.user,
            task = Tasks.objects.get(pk=task_id),
            date = form.cleaned_data['date'],
            ac_reg = form.cleaned_data['ac_reg'],
            wo_no = form.cleaned_data['wo_no'],
        )
        tt.save()
        return HttpResponseRedirect('/admin/tot/tasks/')

else:
    form = TrainingAddForm(initial = {"task": task_id})

return render_to_response('admin/tot/trainingtasks/add.html', {
        'form': form,
        'task_id': task_id
    },
    context_instance = RequestContext(request)
)

如果用户未填写即日期(这是强制性的),将重新显示表单,显示错误(需要字段),但不再显示task_id的基础记录。 ID仍然存在,也可以保存记录(纠正错误后),这对用户来说几乎是一个恼人的错误。

我想我错过了一些代码,但我无法理解。

1 个答案:

答案 0 :(得分:1)

我不确定我理解您的表单或您的观点的逻辑。

您已包含任务字段,但已停用该字段。禁用任务字段后,该值不会出现在request.POST集合中。

在您的视图中,您将task_id参数作为初始数据传递给表单,如果request.method是POST,则从数据库中检索Task对象。

看起来这个任务是你想要分配给TrainingTask的东西,但是它不一定是你想要包含在表单中的东西。鉴于此,我会:

#forms.py
class TrainingAddForm(forms.ModelForm):
    class Meta:
        model = TrainingTasks
        fields = ('ac_reg','date','wo_no',)
        #not include the task

    def __init__(self, *args, **kwargs):
        super(TrainingAddForm, self).__init__(*args, **kwargs)
        self.fields['date'].widget = widgets.AdminDateWidget()

#views.py
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render
from your_app.forms import TrainingAddForm
from your_app.models import Task, TrainingTasks

def add_trainingtask(request, task_id):
    #make sure we have a valid Task object, or redirect.
    #you could also use a try/except Task.DoesNotExist and show an error
    task = get_object_or_404(Task, pk=task_id)

    form = TrainingAddForm(request.POST or None)
    if request.POST:
        if form.is_valid():                
            tt = TrainingTasks(
                trainee = request.user,
                task = task,
                date = form.cleaned_data['date'],
                ac_reg = form.cleaned_data['ac_reg'],
                wo_no = form.cleaned_data['wo_no'],
            )
            tt.save()
            #dont hard-code the url here
            return HttpResponseRedirect(reverse('admin_tot_tasks'))
    return render(request, 'admin/tot/trainingtasks/add.html', {'form': form,
        'task' : task})

希望能帮到你。