使用所有记录预填充 Django ModelForm

Prepopulate Django ModelForm With all records

我正在尝试用所有记录预填充我的表单,但我收到错误消息 'QuerySet' 对象没有属性 '_meta' , 我尝试通过 initial 传递我的查询集,而我没有收到错误模板中的字段未呈现 initial={runninghours}

我的views.py:

def runninghours(request):
    runninghours = RunningHours.objects.all()
    form = RunningHoursModelForm()
    form_populated =  RunningHoursModelForm(initial={runninghours})
    if request.method == 'POST' and 'form-create' in request.POST:
        form = RunningHoursModelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(request.path_info)
    context = {"form": form,
               "rhs": form_populated}
    return render(request, 'runninghours.html', context)

模板:

<form method="POST" action="">
                        {% csrf_token %}
                       <td>{% render_field rhs.name  %}</td>
                       <td>{% render_field rhs.current_runninghours %}</td>
                       <td>{% render_field rhs.last_runninghours %}</td>
                       <td>{% render_field rhs.last_modified %}</td>
                       <td> <input type="hidden" name="update_runninghours_id" value="{{ rhs.pk }}" />
                        <input name="form-delete" type="submit" class="button1" value='Update Runninghours' /></td>
                    </form>

models.py:

class RunningHours(models.Model):
    name = models.CharField(max_length=100)
    current_runninghours = models.IntegerField(blank=True,null=True)
    last_runninghours = models.IntegerField(blank=True,null=True,default=0)
    last_modified = models.DateField(("Date"), default=datetime.date.today)

forms.py:

class RunningHoursModelForm(forms.ModelForm):
        model = RunningHours
        fields = ("name",
                  "current_runninghours",
                  "last_runninghours",)

我认为您不能使用 initial 传递查询集 runninghours。这需要一本字典作为参数。您可以做的是使用查询集来制作表单。

# forms.py

class RunningHoursModelForm(ModelForm):

    def __init__(self,company,*args,**kwargs):
        super (RunningHoursModelForm,self ).__init__(*args,**kwargs)
        self.fields['the_field_you_want'].queryset = RunningHours.objects.all()

    class Meta:
        model = RunningHours

如果你想用 RunningHours 的实例填充表单,你可以这样做

    particularRunningHours = RunningHours.objects.get(name=name)
    form_populated =  RunningHoursModelForm(initial={
        'current_runninghours': particularRunningHours.current_runninghours,
        ...
        })