for domain in secondary_domains:
result += "<a href='http://%(d)s' target='_blank'>%(d)s</a>, " %
result = result[:-2] + ')' return result domain_names.allow_tags = True
This code fetches all VHostDirective objects that point to the ConfigDirective object whose name is either ' ServerName' or ' ServerAlias '. The value of such a VHostDirective object is then appended to the result string. In fact, this value is used to construct an HTML link, which should open in a new browser window when clicked. The intention here is that all the links of the Virtual Host are presented in the listing and are clickable, so you can immediately test them.
Let's take a closer look at the instruction that retrieves the VHostDirective objects (the highlighted lines in Listing 5-7). As you know from the model definition, the VirtualHost class, which we're modifying now, does not link to the VHostDirective class. The link is reversed; the VHostDirective class has a foreign key that points back to the VirtuaHost class. Django allows you to create reverse lookups as well by using the special attribute name <lowercase_class_name>_set. In our case the name is virtualhostdirective_set. This attribute implements standard object selection methods, such as filter() and all(). Now, using this virtualhostdirective_set attribute, we're actually accessing the instances of the VHostDirective class, and therefore we can specify a forward filter that matches the corresponding Directive object name against our search string:
Let's add another method that returns a link to the object representation URL. We are also going to display this in the listing, so that users can click on it and the code snippet just for this VirtualHost will appear in a new browser window. This VirtualHost class method is defined in the models. py file:
return "<a href='/%i/' target='_blank'>View code snippet</a>" % self.id code_snippet.allow_tags = True
Have you noticed that in both cases we modify the method's allow_tags property by setting it to True? This prevents Django from parsing the HTML codes and replacing them with "safe" characters. With the tags enabled, we can place any HTML code in the object listing; for example, we can include links to external URLs, or include images.
Finally, let's list all the properties that we want to see in the object list. This includes the class attributes as well as the names of the two functions that we've just created. Add the following property to the ModelAdmin class definition in the admin. py file:
list_display = ('description', 'is_default', 'is_template',
'bind_address', 'domain_names', 'code_snippet')
Now when you navigate to the Virtual Host object list, you should see something similar to Figure 5-2. It may not be obvious, but the listed domain names and the code snippet text are clickable and should open the URL in a new browser window.
Was this article helpful?