拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用所有记录预填充DjangoModelForm

使用所有记录预填充DjangoModelForm

白鹭 - 2022-01-23 2071 0 0

我正在尝试用所有记录预填充我的表单,但我收到错误 'QuerySet' object has no attribute '_meta' ,我尝试只通过初始查询集传递我的查询集,而我没有收到错误模板中的栏位没有呈现 initial={runninghours}

我的意见.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>

模型.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)

表格.py:

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

uj5u.com热心网友回复:

我不认为你可以通过使用 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,
        ...
        })
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *