我试图动态显示对象的所有数据。 虽然它不能很好地工作,但它只显示我使用多对多关系的关键。
models.py
from django.db import models
from django.forms import ModelForm
class Web_application(models.Model):
name = models.CharField(max_length=200)
url = models.URLField()
def __str__(self):
return "%s (%s)" % (self.name, self.url)
class Web_vulnerability(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=500)
web_applications = models.ManyToManyField(Web_application, blank=True) #blank True : relation optional
def __str__(self):
return "%s (%s)" % (self.description, self.name)
urls.py
url(r'^list_view/([\w-]+)$', 'django_test.views.generic_list', name='generic_list'),
views.py
def generic_list(request, class_name):
template_name = 'django_test/generic_list.html'
model = apps.get_model(app_label='django_test', model_name=class_name)
data = model.objects.all()
context = {'object_list' : serializers.serialize( "python", data, use_natural_foreign_keys=True, use_natural_primary_keys=True)}
return render(request, 'django_test/generic_list.html', context)
generic_list.html
<table>
<thead>
<tr>
{% for field_name, field_value in object_list.0.fields.items %}
<td>{{ field_name }}</td>
{% endfor %}
</tr>
</thead>
<tbody>
{% for object in object_list %}
<tr>
{% for field_name, field_value in object.fields.items %}
<td>{{ field_value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
这是我在访问http://domain.com/list_view/Web_vulnerability时得到的HTML表格:
web_applications name description
[2L, 3L] SQLi Injection SQL
[1L, 3L] XSS Cross Site Scripting
[] Test test
我想要使用web_application名称而不是[1L,2L,...]