I want to show in the app/model admin the columns of the model but with some customization. These 3 'tar', 'per_hor','per_tar' have choices in their modelfield.
First I wrote this code:
class ValoresAdmin(admin.ModelAdmin):
list_display = ('fecha', 'tar', 'per_hor','per_tar')
list_filter = ('fecha','tar','per_tar','per_hor')
date_hierarchy = 'fecha'
fieldsets = (
(None, {
'fields': ('fecha',('tar', 'per_hor', 'per_tar'))
}),
(None, {
'fields': ('feu', 'coef_perf','sah', 'pmh','carg_cap')
}),
)
I shows the verbose name of the column but the values is always "(nothing)" on the filter page but if I enter the change form they display correctly their value (their choide).
I read some and decided to create methods like these ones and call them in the list_display:
def get_tar(Self):
return self.get_tar_display()
def get_per_hor(Self):
return self.get_per_hor_display()
def get_per_tar(Self):
return self.get_per_tar_display()
get_tar_display.short_description = 'Tarifa'
get_per_hor_display.short_description = 'Periodo horario'
get_per_tar_display.short_description = 'Periodo tarifario'
Now the filter page will display columns named as the short description BUT with the real value of the field instead of theirs "choice value".
Addiotionally if I mark 'per_tar' as non editable it will show also "(nothing)" in the change from instead of it´s stored value.
What am I doing wrong?
Diving in internet I found the answer here:
http://thinkingnectar.com/2009/django-get_foo_display-behaviour-with-characters-and-integer-fields/
The post comment that when the field is char type, the choice key should be a string but when it´s an integer field it should be an interger!
Here was my problem! Changing strings to integer made it work.
Related
How can I display the count of related objects after each filter in list_filter in django admin?
class Application(TimeStampModel):
name = models.CharField(verbose_name='CI Name', max_length=100, unique=True)
description = models.TextField(blank=True, help_text="Business application")
class Server(TimeStampModel):
name = models.CharField(max_length=100, verbose_name='Server Name', unique=True)
company = models.CharField(max_length=3, choices=constants.COMPANIES.items())
online = models.BooleanField(default=True, blank=True, verbose_name='OnLine')
application_members = models.ManyToManyField('Application',through='Rolemembership',
through_fields = ('server', 'application'),
)
class Rolemembership(TimeStampModel):
server = models.ForeignKey(Server, on_delete = models.CASCADE)
application = models.ForeignKey(Application, on_delete = models.CASCADE)
name = models.CharField(verbose_name='Server Role', max_length=50, choices=constants.SERVER_ROLE.items())
roleversion = models.CharField(max_length=100, verbose_name='Version', blank=True)
Admin.py
#admin.register(Server)
class ServerAdmin(admin.ModelAdmin):
save_on_top = True
list_per_page = 30
list_max_show_all = 500
inlines = [ServerInLine]
list_filter = (
'region',
'rolemembership__name',
'online',
'company',
'location',
'updated_on',
)
i.e After each filter in list filter, I want to show the count of related objects.
Now it only shows the list of filter
i.e location filter list
Toronto
NY
Chicago
I want the filter to show the count like below:
Toronto(5)
NY(3)
Chicago(2)
And if the filter has 0 related objects, don't display the filter.
This is possible with a custom list filter by combining two ideas.
One: the lookups method lets you control the value used in the query string and the text displayed as filter text.
Two: you can inspect the data set when you build the list of filters. The docs at https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter shows examples for a start decade list filter (always shows «80s» and «90s») and a dynamic filter (shows «80s» if there are matching records, same for «90s»).
Also as a convenience, the ModelAdmin object is passed to the lookups
method, for example if you want to base the lookups on the available
data
This is a filter I wrote to filter data by language:
class BaseLanguageFilter(admin.SimpleListFilter):
title = _('language')
parameter_name = 'lang'
def lookups(self, request, model_admin):
# Inspect the existing data to return e.g. ('fr', 'français (11)')
# Note: the values and count are computed from the full data set,
# ignoring currently applied filters.
qs = model_admin.get_queryset(request)
for lang, name in settings.LANGUAGES:
count = qs.filter(language=lang).count()
if count:
yield (lang, f'{name} ({count})')
def queryset(self, request, queryset):
# Apply the filter selected, if any
lang = self.value()
if lang:
return queryset.filter(language=lang)
You can start from that and adapt it for your cities by replacing the part with settings.LANGUAGES with a queryset aggregation + values_list that will return the distinct values and counts for cities.
Éric's code got me 80% of what I needed. To address the comment he left in his code (about ignoring currently applied filters), I ended up using the following for my use case:
from django.db.models import Count
class CountAnnotatedFeedFilter(admin.SimpleListFilter):
title = 'feed'
parameter_name = 'feed'
def lookups(self, request, model_admin):
qs = model_admin.get_queryset(request).filter(**request.GET.dict())
for pk, name, count in qs.values_list('feed__feed_id', 'feed__feed_name').annotate(total=Count('feed')).order_by('-total'):
if count:
yield pk, f'{name} ({count})'
def queryset(self, request, queryset):
feed_id = self.value()
if feed_id:
return queryset.filter(feed_id=feed_id)
And then, in the admin model:
class FeedEntryAdmin(admin.ModelAdmin):
list_filter = (CountAnnotatedFeedFilter,)
Note: As Éric also mentioned, this can impact the speed of the admin panel quite heavily, as it may have to perform expensive queries.
So, I have a form that collects a bunch of radio selections and checkboxes and I need to build a series of objects based on what gets returned, which might look like this:
[thingid:1, 13:30,14:33, 11:26, 12:78, action:save, controller:userThing]
One object is created from the thingid, and the integer value pairs are ids of 2 other objects that are used to create n additional objects, so right now I'm looping through the params with an each() and filtering the non integer pairs with a long if expression, and then saving the object I need :
params.each {
key, value ->
if (key=="submit" | key=="action" | key=="thingid" | key=="controller"){}else{
def prop = ThingProperty.find(){
id == key
}
def level = ThingLevel.find(){
id == value
}
new UserThingScore(userthing: userthing,thingproperty: prop ,thinglevel: level).save(flush:true)
}
}
It works, in that it creates all the necessary objects correctly, but this just seems ridiculous to me, and I know there must be a better way... is there someway I can group form elements so they get returned like this?:
[thingid:1, integerpairs:[13:30,14:33, 11:26, 12:78],action:save,controller:userThing]
An alternative might be:
def userThingList = params.keySet().grep( Integer ).collect { it ->
new UserThingScore( userthing: userthing,
thingproperty: ThingProperty.get( it ),
thinglevel: ThingLevel.get( params[ it ] ) )
}
userThingList*.save()
I want to display a previous value on Min Miles and that should not be editable. I want like
Default value of Min Miles is 0.
When I click on Add More Range then In the new form - Min Value should be Max Value of Previous Form.
I am using semantic form for. Please Help Me. How can I do this...
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the
field value with javascript and use it as the default value for the
new field. The "add new range"
Something Like
function getvalue(){
var inputTypes_max = [],inputTypes_min = [],inputTypes_amount = [];
$('input[id$="max_miles"]').each(function(){
inputTypes_max.push($(this).prop('value'));
});
$('input[id$="amount"]').each(function(){
inputTypes_amount.push($(this).prop('value'));
});
var max_value_of_last_partition = inputTypes_max[inputTypes_max.length - 2]
var amount_of_last_partition = inputTypes_amount[inputTypes_amount.length - 2]
if (max_value_of_last_partition == "" || amount_of_last_partition == "" ){
alert("Please Fill Above Details First");
}else{
$("#add_more_range_link").click();
$('input[id$="min_miles"]').each(function(){
inputTypes_min.push($(this).prop('id'));
});
var min_id_of_last_partition=inputTypes_min[inputTypes_min.length - 2]
$("#"+min_id_of_last_partition).attr("disabled", true);
$("#"+min_id_of_last_partition).val(parseInt(max_value_of_last_partition) + 1)
}
}
I have Used Jquery's End Selector In a loop to get all value of max and amount field as per your form and get the ids of your min_miles field and then setting that value of your min_miles as per max_miles
It worked For me hope It works For You.
Default value of a field can just be passed in the form builder as a second parameter:
...
f.input :min_miles, "My default value"
Of course I do not know your model structure but you get the idea.
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the field value with javascript and use it as the default value for the new field. The "add new range" click will be the triggerer for the value capture.
Something like (with jQuery):
var temp_value = '';
$('#add_more_range').click(function(){
temp_value = $('#my_form1 #min_miles').value();
$('#my_form2 #max_miles').value(temp_value);
});
Again I am just guessing the name of the selectors, but the overall approach should work.
If you are also adding dinamically to the page the "Add new range" buttons/links, then you should delegate the function in order to be inherited also for the so new added buttons:
$('body').on('click', '#add_more_range', function(){...});
I have a Grails command object with a list of maps. The map key is intended to be a numeric domain object ID.
class MyCommand {
def grid = [].withDefault { [:] }
}
Data binding to the list/map is working in general because of the dynamic list expansion.
However, in the POST, the map keys are being bound as Strings and I want them to be Longs, as they are when the form is initially populated. I want foo[123] in my map, not foo['123'].
Alternatively I would be satisfied if the [] operators found the correct value given a numeric ID key to look up. In other words, if I could get foo[123] to return the same value as foo['123'], that would work too.
Any way to get this to work the way I want to? Maybe strongly type the map?
Or a better approach?
You can inject the property into the map to convert a String key to Long. For example:
def myMap = [:] << ['1': "name"] << ['Test': "bobo"]
def result = myMap.inject([:]){map, v ->
def newKey = v.key.isNumber() ? v.key.toLong() : v.key
map[newKey] = v.value
map
}
assert myMap['1'] == 'name'
assert result[1L] == 'name'
assert result['Test'] == 'bobo'
Using JIRA version 4.2. With Python 2.7 and suds 0.4, how can I update an issue's custom cascading select's field (both parent and child)?
There is a SOAPpy example available under "Python (SOAPPy) client".
I was unable to perform this type of update using the Python JIRA CLI.
Example:
When updating the cascading select custom child of parent field, customfield_10, one would want to update the field customfield_10_1.
Update
Code to display cascading field's original value:
issue = client.service.getIssue(auth, "NAHLP-33515")
for f in fields:
if f['customfieldId'] == 'customfield_10050' or f['customfieldId'] == 'customfield_10050_1':
print f
This results in:
(RemoteCustomFieldValue){
customfieldId = "customfield_10050"
key = None
values[] =
"10981",
}
After manually setting the cascading field's child, the above code results in:
(RemoteCustomFieldValue){
customfieldId = "customfield_10050"
key = None
values[] =
"10981",
}
(RemoteCustomFieldValue){
customfieldId = "customfield_10050"
key = "1"
values[] =
"11560",
}
The above values is what I hope to achieve via suds.
Note the key = "1" field. The key value designates that this object is the child of customfield_10050.
Documentation reference:
parentKey - Used for multi-dimensional custom fields such as Cascading select lists. Null in other cases
Let's try sending a key field value:
client.service.updateIssue(auth, "NAHLP-33515", [
{"id":"customfield_10050", "values":["10981"]},
{"id":"customfield_10050_1", "key":"1", "values":["11560"]}
])
This results in an error because the updateIssue accepts a RemoteFieldValue[] parameter, not a RemoteCustomFieldValue[] parameter (thanks Matt Doar):
suds.TypeNotFound: Type not found: 'key'
So how do we pass a RemoteCustomFieldValue parameter to update an issue?
Update 2, mdoar's answer
Ran following code via suds:
client.service.updateIssue(auth, "NAHLP-33515", [
{"id":"customfield_10050", "values":["10981"]},
{"id":"customfield_10050_1", "values":["11560"]}
])`
After value:
(RemoteCustomFieldValue){
customfieldId = "customfield_10050"
key = None
values[] =
"10981",
}
Unfortunately, this does not update the child of customfield_10050. Verified manually.
Resolution:
Thank you mdoar! To update a parent and child of a cascading select field, use the colon (':') to designate the child filed.
Working example:
client.service.updateIssue(auth, "NAHLP-33515", [
{"id":"customfield_10050", "values":["10981"]},
{"id":"customfield_10050:1", "values":["11560"]}
])