Django BooleanField不适用于编辑表单

时间:2017-11-06 19:12:05

标签: python django

我的情况:

Models.py

class Box(models.Model):
    is_empty = models.BooleanField(default=False)
    upload_date = models.DateTimeField(auto_add_now=True)

Forms.py

class BoxForm(forms.ModelForm):
    class Meta:
        model = Box
        fields = (is_empty,)

Views.py

def edit_box(request, pk):
    box = get_object_or_404(Box, pk=pk)
    if request.method == 'POST':
        form = BoxForm(request.POST, instance=box)
        if form.is_valid():
            form.save()
        return redirect('home')
    else:
        form = BoxForm(instance=box)
    return render(request, 'form.html', {'form': form})

问题是,当我进入模板表单并且我想更改复选框值时,我无法执行此操作,它似乎已禁用,我不知道为什么。

修改 Template.html

...
<form class="row gap-y" method="POST">{% csrf_token %}
  <div class="col-2">
    <div class="checkbox">
        {% render_field form.is_empty class="form-control" %}
        <label for="id_description-is_empty">Is empty?</label>
    </div>
  </div>
  <div class="col-2">
      <button class="btn btn-bold btn-primary" type="submit">Save</button>
  </div>
</form>
...

1 个答案:

答案 0 :(得分:0)

最后我实现了解决方案:

我必须更改 templates.html ,例如:

public class Tester
{
    public static class AssemblyLoggerMCVE
    {

        public static Lazy<Window> Window { get; } = new Lazy<Window>(NewWindowHandler);

        private static Window NewWindowHandler() => new Window();

        public static IScheduler Scheduler =>
            new DispatcherScheduler(Window.Value.Dispatcher);

    }

    /// This passes
    [StaFact]
    public void AssemblyLoggerMCVEShouldWork()
    {
        AssemblyLoggerMCVE.Scheduler.Should().NotBeNull();

    }

    /// This fails
    [StaFact]
    public void AssemblyLoggerShouldWork()
    {
        AssemblyLogger.Scheduler.Should().NotBeNull();

    }
}

在复选框字段中无需呈现class =&#34; control-form&#34;,然后使用浏览器控制台,查找字段 id 并复制到标签中 strong> param。