如何在django中添加一个变量,该变量根据view.py中的其他变量获取特定值

m0rkklqb  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(116)

我想使form2变量,我们必须添加条件,从注册表中选择机构名称,其中机构代码等于form1变量中存在的机构代码,并在上下文中传递form2,以便可以在模板文件中打印。
我在view.py中添加了代码

def view_eligibility_admin(request):
form1 = Eligibility_Check.objects.all() 
form2 = {}  # Initialize an empty dictionary to store institute names
    for item in form1:
institute_code = item.Centre_code
        try:
            register_entry = Register.objects.get(institute_code=institute_code) 
            institute_name = register_entry.institute_name
            form2[institute_code] = institute_name
        except Register.DoesNotExist:
              # Handle the case where the institute code doesn't exist in the Register model
            form2[institute_code] = "N/A"
    context = {'form1': form1, 'form2': form2}
    return render(request, 'view_eligibiity_admin.html', context)

在我的template.py中,我这样使用它。

<tr>
                   <td>{{ forloop.counter }}</td>
                   <td>{{ i.Centre_code }} / {{ i.Serial_number }}</td>
                   <td>{{ i.Date_of_survey }}</td>
                   <td>{{ i.District }}</td>
                   <td>{{ i.Voter_id }}</td>
                   <td>{{ i.Ec }}</td>
                   <td>{{ form2.item.institute_code }}</td>               
                   <td class="text-center">
                       <a class="btn btn-primary" href="{% url 'view_eligibility_pid' i.pk %}"><i class="fa fa-eye" aria-hidden="true"></i> </a> 
                   </td>
               </tr>
               {% endfor %}```
But i am getting blank value in place of institute name.
u7up0aaq

u7up0aaq1#

从代码中我可以推断出form1是Eligibility_Check的对象列表您希望根据Eligibility_Check对象中的条件再追加一个值。
更好的方法是在现有对象本身中添加附加值。用这种方式修改代码,
views.py

def view_eligibility_admin(request):
    form1 = Eligibility_Check.objects.all() 
        for item in form1:
            institute_code = item.Centre_code
            try:
                register_entry = Register.objects.get(institute_code=institute_code) 
                institute_name = register_entry.institute_name
                item.institute_code = institute_name
            except Register.DoesNotExist:
                # Handle the case where the institute code doesn't exist in the Register model
                item.institute_code = "N/A"
        context = {'form1': form1}
    return render(request, 'view_eligibiity_admin.html', context)

template.py

<tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ i.Centre_code }} / {{ i.Serial_number }}</td>
            <td>{{ i.Date_of_survey }}</td>
            <td>{{ i.District }}</td>
            <td>{{ i.Voter_id }}</td>
            <td>{{ i.Ec }}</td>
            <td>{{ i.institute_code }}</td>
            <td class="text-center">
                <a class="btn btn-primary" href="{% url 'view_eligibility_pid' i.pk %}"><i class="fa fa-eye"
                        aria-hidden="true"></i> </a>
            </td>
        </tr>

相关问题