Added a 'Print Labels' action to the Library Admin Page.
[htsworkflow.git] / htsworkflow / frontend / samples / admin.py
1 from django.contrib import admin
2 from django.contrib.admin import widgets
3 from django.contrib.admin.models import User
4 from django.contrib.auth.admin import UserAdmin
5 from django.contrib.auth.forms import UserCreationForm, UserChangeForm
6 from django.template import Context, Template
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9
10 from htsworkflow.frontend.samples.models import Antibody, Cellline, Condition, ExperimentType, HTSUser, LibraryType, Species, Affiliation, Library, Tag
11 from htsworkflow.frontend.experiments.models import Lane
12 from htsworkflow.frontend.inventory.models import PrinterTemplate
13 from htsworkflow.frontend.bcmagic.utils import print_zpl_socket
14
15 class AffiliationOptions(admin.ModelAdmin):
16     list_display = ('name','contact','email')
17     fieldsets = (
18       (None, {
19           'fields': (('name','contact','email','users'))
20       }),
21     )
22
23     # some post 1.0.2 version of django has formfield_overrides 
24     # which would replace this code with:
25     # formfield_overrids = {
26     #   models.ManyToMany: { 'widget': widgets.FilteredSelectMultiple }
27     # }
28     def formfield_for_dbfield(self, db_field, **kwargs):
29       if db_field.name == 'users':
30         kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
31       rv = super(AffiliationOptions, self).formfield_for_dbfield(db_field, **kwargs)
32     #  print db_field.name, kwargs
33       return rv
34
35 class AntibodyOptions(admin.ModelAdmin):
36     search_fields = ('antigene','nickname','catalog','antibodies','source','biology','notes')
37     list_display = ('antigene','nickname','antibodies','catalog','source','biology','notes')
38     list_filter = ('antibodies','source')
39     fieldsets = (
40       (None, {
41           'fields': (('antigene','nickname','antibodies'),('catalog','source'),('biology'),('notes'))
42       }),
43      )
44
45 class CelllineOptions(admin.ModelAdmin):
46     list_display = ('cellline_name', 'nickname', 'notes')
47     search_fields = ('cellline_name', 'nickname', 'notes')
48     fieldsets = (
49       (None, {
50           'fields': (('cellline_name'),('notes'),)
51       }),
52      )
53
54 class ConditionOptions(admin.ModelAdmin):
55     list_display = (('condition_name'), ('notes'),)
56     fieldsets = (
57       (None, {
58           'fields': (('condition_name'),('nickname'),('notes'),)
59       }),
60      )
61
62 class ExperimentTypeOptions(admin.ModelAdmin):
63   model = ExperimentType
64   #list_display = ('name',)
65   #fieldsets = ( (None, { 'fields': ('name',) }), )
66
67 class HTSUserCreationForm(UserCreationForm):
68     class Meta:
69         model = HTSUser
70         fields = ("username",'first_name','last_name')
71
72 class HTSUserChangeForm(UserChangeForm):
73     class Meta:
74         model = HTSUser
75         
76 class HTSUserOptions(UserAdmin):
77     form = HTSUserChangeForm
78     add_form = HTSUserCreationForm
79
80 class LaneLibraryInline(admin.StackedInline):
81   model = Lane
82   extra = 0
83
84 class Library_Inline(admin.TabularInline):
85   model = Library
86
87 class LibraryTypeOptions(admin.ModelAdmin):
88     model = LibraryType
89
90 class LibraryOptions(admin.ModelAdmin):
91     class Media:
92         css = {
93             "all": ("css/wide_account_number.css",)
94             }
95         
96     date_hierarchy = "creation_date"
97     save_as = True
98     save_on_top = True
99     search_fields = (
100         'id',
101         'library_name',
102         'cell_line__cellline_name',
103         'library_species__scientific_name',
104         'library_species__common_name',
105     )
106     list_display = (
107         'id',
108         #'aligned_reads',
109         #'DataRun',
110         'library_name',
111         'public',
112         #'experiment_type',
113         #'organism',
114         #'antibody_name',
115         #'cell_line',
116         #'libtags',
117         #'made_for',
118         'affiliation',
119         #'made_by',
120         'undiluted_concentration',
121         'creation_date',
122         'stopping_point',
123         #'condition',
124
125     )
126     list_filter = (
127         'experiment_type', 
128         'library_species', 
129         'tags',
130         #'made_for',
131         'affiliations',
132         'made_by', 
133         'antibody',
134         'cell_line',
135         'condition',
136         'stopping_point',
137         'hidden')
138     list_display_links = ('id', 'library_name',)
139     fieldsets = (
140       (None, {
141         'fields': (
142           ('id','library_name','hidden'),
143           ('library_species'),
144           ('library_type', 'experiment_type', 'replicate'),
145           ('cell_line','condition','antibody'),)
146          }),
147          ('Creation Information:', {
148              'fields' : (('made_for', 'made_by', 'creation_date'), ('stopping_point', 'amplified_from_sample'), ('avg_lib_size','undiluted_concentration', 'ten_nM_dilution', 'successful_pM'), 'account_number', 'notes',)
149          }),
150          ('Library/Project Affiliation:', {
151              'fields' : (('affiliations'), ('tags'),)
152          }),
153          )
154     inlines = [
155       LaneLibraryInline,
156     ]
157     actions = ['action_print_library_labels']
158     
159     
160     def action_print_library_labels(self, request, queryset):
161         """
162         Django action which prints labels for the selected set of labels from the
163         Django Admin interface.
164         """
165         
166         #Probably should ask if the user really meant to print all selected
167         # libraries if the count is above X. X=10 maybe?
168         
169         # Grab the library template
170         #FIXME: Hardcoding library template name. Not a good idea... *sigh*.
171         EVIL_HARDCODED_LIBRARY_TEMPLATE_NAME = "Library"
172         
173         try:
174             template = PrinterTemplate.objects.get(item_type__name=EVIL_HARDCODED_LIBRARY_TEMPLATE_NAME)
175         except PrinterTemplate.DoesNotExist:
176             self.message_user(request, "Could not find a library template with ItemType.name of '%s'" % \
177                               (EVIL_HARDCODED_LIBRARY_TEMPLATE_NAME))
178             return
179         
180         # ZPL Template
181         t = Template(template.template)
182         
183         #Iterate over selected labels to print
184         for library in queryset.all():
185             
186             # Django Template Context
187             c = Context({'library': library})
188             
189             # Send rendered template to the printer that the template
190             #  object has been attached to in the database.
191             print_zpl_socket(t.render(c), host=template.printer.ip_address)
192     
193         self.message_user(request, "%s labels printed." % (len(queryset)))
194                           
195     action_print_library_labels.short_description = "Print Labels"
196
197
198
199     # some post 1.0.2 version of django has formfield_overrides 
200     # which would replace this code with:
201     # formfield_overrids = {
202     #    models.ManyToMany: { 'widget': widgets.FilteredSelectMultiple }
203     #}
204     def formfield_for_dbfield(self, db_field, **kwargs):
205       if db_field.name in ('affiliations', 'tags'):
206         kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name,
207                                                           (db_field.name in self.filter_vertical))
208       rv = super(LibraryOptions, self).formfield_for_dbfield(db_field, **kwargs)
209       return rv
210
211 class SpeciesOptions(admin.ModelAdmin):
212     fieldsets = (
213       (None, {
214           'fields': (('scientific_name', 'common_name'),)
215       }),
216     )
217
218 class TagOptions(admin.ModelAdmin):
219     list_display = ('tag_name', 'context')
220     fieldsets = ( 
221         (None, {
222           'fields': ('tag_name', 'context')
223           }),
224         )
225
226 admin.site.register(Affiliation, AffiliationOptions)
227 admin.site.register(Antibody, AntibodyOptions)
228 admin.site.register(Cellline, CelllineOptions)
229 admin.site.register(Condition, ConditionOptions)
230 admin.site.register(ExperimentType, ExperimentTypeOptions)
231 admin.site.register(HTSUser, HTSUserOptions)
232 admin.site.register(LibraryType, LibraryTypeOptions)
233 admin.site.register(Library, LibraryOptions)
234 admin.site.register(Species, SpeciesOptions)
235 admin.site.register(Tag, TagOptions)