如何在Django中使用复选框打勾获取字段(布尔字段)

时间:2020-02-14 02:40:42

标签: python django forms orm

我的模板:我想获取带有刻度标记的数据,然后将其呈现到其他视图。

 <form class="hero-menu">
                    {% for test in test %}
                    <div class="category-block">
                      <ul class="dropdown-list">
                        <li>
                          <a href="#"><h4 data-modal-target="menu-test-popup">
                              {{test.name|title}}
                            </h4></a>
                        </li>
                        {% for subtest in test.subtest.all %}
                        <!-- {% if subtest.test_id == test.id %}   -->
                           <li>
                            <div class="checkbox-group">
                              <input type="checkbox" id="aUniqueName" name={{subtest.name}}
                              value="example"/>
                              <label for="aUniqueName">
                               {{subtest.name|title}}
                              </label>
                            </div>
                          </li>
                          <!-- {% endif %}  -->
                        {% endfor %}


                      </ul>
                    </div>
                    {% endfor %}


                    <button class="button">Generate Report</button>
                  </form>

这是我的模型。在我的模型中,我有Test,它在子测试中具有外键。

class Test(models.Model):
    name = models.CharField(max_length=100)
    def __str__(self):
        return self.name


class Subtest(models.Model):
    name = models.CharField(max_length=100)
    test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True)
    unit = models.CharField(max_length=10)
    reference_value = models.IntegerField()
    selected = models.BooleanField(default=False)
    def __str__(self):
        return self.name

这是我的观点。为了方便起见,我使用了template_context_processor。

def list_subtest(request):
return {'subtest':Subtest.objects.all(),'test':Test.objects.all().prefetch_related('subtest')}

1 个答案:

答案 0 :(得分:1)

首先,我邀请您从FBV更改为CBV,相信我会积极改变Django中的所有编程。

我看不到您的发帖方式。我会把你留在这里我是怎么做到的:

[template.html]

<form action="" method="POST"> {% csrf_token %}
    {% for test in tests %}
        {% for subtest in subtests %}
            <input type="hidden" name="test_id" value="{{test.id}}">
            {% if test.id == subtest.test_id && subtest.selected %}
                <label>
                    <input type="checkbox" name="{{subtest.id}}" checked>{{subtest.name}}
                </label>
            {% else %}
                <label>
                    <input type="checkbox" name="{{subtest.id}}">{{subtest.name}}
                </label>
            {% endif %}
        {% endfor %}
    {% endfor %}
    ...

    <input class="btn btn-success" type="submit" value="GENERATE REPORT">
</form>

[views.py]

from .models import (
    Subtest,
    Test,
)
from django.views.generic import ListView

class ListSubsets(ListView):

    context_object_name = 'tests' # This replace context['tests']
    model = Test
    paginate_by = 1
    template_name = 'core/index.html'

    def get_context_data(self, **kwargs):
        context = super(ListSubsets, self).get_context_data(**kwargs)
        context['subtests'] = Subtest.objects.all()
        # context['tests'] = Test.objects.all() # Without prefetch_related
        return context

    def post(self, request):
        post_dict = request.POST.dict()
        # test = Test.objects.get(id = post_dict['test_id'])
        subtests = Subtest.objects.all()
        for subtest in subtests:
            try:
                if str(subtest.test_id) in post_dict:
                    update = Subtest.objects.get(test = subtest.test_id)
                    update.selected = True
                    update.save()
            except:
                print("Doesn't exist.")
        return self.get(request, *args, **kwargs)

还有许多更细微的方法可以做到,其他更有效的方法,但是真正正确的方法应该是JavaScript。测试角度,我邀请您,请切换到CBV。

-------------------------------- o -------------- ------------------

[settings.py]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',

                # Our context processor for every app.
                # Core.
                'apps.functions.processor.cntxt_prcssr_templates_core',
           ],
        },
    },
]

[processor.py]

from .models import (
    Test,
    Subtest
)

# tests = Test.objects.all()
# subtests = Subtest.objects.all()

def cntxt_prcssr_templates_core(request=None):

    # TEST.
    'tests':       Test.objects.all(),
    # 'tests':       tests,

    # SUBTEST
    'subtests':    Subtest.objects.all(),
    # 'subtests':    subtests,

    return cntxt_templates_core

然后,您只能访问任何模板的测试或子测试。 (html)