问题
I've got user records that have related(ish) course and enrollment records. I want to click on a user and see raw data from the user table, course table, and enrollment table in the same page.
The process breaks down when I attempt to render the tables.
views.py:
def explore_related(request, client_id, user_id):
client = get_object_or_404(Client, pk=client_id)
users = Users.objects.filter(pk=user_id)
enrollments = Enrollments.objects.filter(client_id=client_id).filter(userID__in=users.values_list('userID', flat=True)).all()
courses = Courses.objects.filter(client_id=client_id).filter(sectionSchoolCode__in=enrollments.values_list('sectionSchoolCode', flat=True)).all()
userTable = UserTable(users, prefix='u_')
courseTable = CourseTable(courses, prefix='c_')
enrollmentTable = EnrollmentTable(enrollments, prefix='e_')
payload = {
'userTable': userTable,
'enrollmentTable': enrollmentTable,
'courseTable': courseTable,
}
return render(request, 'importer/explore_related.html', payload)
explore_related.html:
{% load render_table from django_tables2 %}
<html>
<body>
{% render_table userTable %}
<br>
{% render_table courseTable %}
<br>
{% render_table enrollmentTable %}
</body>
</html>
tables.py
class UserTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='userID', orderable=False)
errors = tables.Column()
User_ID = tables.LinkColumn(
'importer:explore_related',
text=lambda record: record.userID,
kwargs={
'client_id': tables.A('client_id'),
'file_kind': 'user',
'object_id': tables.A('id'),
},
empty_values='NULL',
)
class Meta:
model = Users
attrs = {'class': 'paleblue'}
exclude = ['id', 'client', 'userID']
sequence = (
'selection',
'...',
'errors'
)
class CourseTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', orderable=False)
errors = tables.Column()
class Meta:
model = Courses
attrs = {'class': 'paleblue'}
exclude = ['id', 'client']
sequence = (
'selection',
'...',
'errors'
)
class EnrollmentTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk', orderable=False)
errors = tables.Column()
class Meta:
model = Enrollments
attrs = {'class': 'paleblue'}
exclude = ['id', 'client']
sequence = (
'selection',
'...',
'errors'
)
回答1:
If you use custom table classes, you need to use a RequestConfig object to properly set-up the table.
In your example, it should be enough to add
RequestConfig(request, paginate=False).configure(userTable)
RequestConfig(request, paginate=False).configure(courseTable)
RequestConfig(request, paginate=False).configure(enrollmentTable)
before adding them to payload.
来源:https://stackoverflow.com/questions/39619369/django-tables2-display-multiple-tables