Skip to content

Commit ddc9999

Browse files
committed
[fix] Admin: fixed template ordering bug in preview config
The order of templates was not always retained when generating the preview of a config object.
1 parent d25bf51 commit ddc9999

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

openwisp_controller/config/admin.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,11 +230,14 @@ def preview_view(self, request):
230230
template_ids = request.POST.get('templates')
231231
if template_ids:
232232
template_model = config_model.get_template_model()
233+
template_ids = template_ids.split(',')
233234
try:
234-
templates = template_model.objects.filter(
235-
pk__in=template_ids.split(',')
236-
)
235+
templates = template_model.objects.filter(pk__in=template_ids)
237236
templates = list(templates) # evaluating queryset performs query
237+
# ensure the order of templates is maintained
238+
templates.sort(
239+
key=lambda template: template_ids.index(str(template.id))
240+
)
238241
except ValidationError as e:
239242
logger.exception(error_msg, extra={'request': request})
240243
return HttpResponse(str(e), status=400)

openwisp_controller/config/tests/test_admin.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -701,10 +701,17 @@ def test_preview_device_jsonerror(self):
701701

702702
def test_preview_device_showerror(self):
703703
t1 = Template.objects.get(name='dhcp')
704-
t2 = Template(name='t', config=t1.config, backend='netjsonconfig.OpenWrt')
705-
t2.full_clean()
706-
t2.save()
707-
templates = [t1, t2]
704+
t2 = Template(name='t2', config=t1.config, backend=t1.backend)
705+
t3 = Template(name='t3', config=t1.config, backend=t1.backend)
706+
t4 = Template(
707+
name='t4',
708+
config={"interfaces": [{"name": "eth0", "type": "bridge", "stp": "WRONG"}]},
709+
backend='netjsonconfig.OpenWrt',
710+
)
711+
# skip validating config to raise error later
712+
t4.save()
713+
# adding multiple templates to ensure the order is retained correctly
714+
templates = [t1, t2, t3, t4]
708715
path = reverse(f'admin:{self.app_label}_device_preview')
709716
data = {
710717
'name': 'test-device',

0 commit comments

Comments
 (0)