How can we NOT display certain rows in a flask-admin view? - flask

I have been searching and trying for a while but could not find any answer so any help is appreciated.
I have a flask admin-view, say the following:
class testViewMain():
column_list = [
'first_name',
'last_name',
'email',
'phone',
]
How can I exclude certain values on this flask view?
For example, display only rows from the database where first_name != John and last_name != Doe.
I thought the function I was looking for is on_form_prefill, but according to the documentation, this is only on the edit view.

I found an answer:
class testViewMain():
column_list = [
'first_name',
'last_name',
'email',
'phone',
]
def get_query(self):
return self.session.query(self.model).filter(
self.model.first_name != 'John' \
and self.model.last_name != 'Doe')

Related

fields except the id field is not getting imported using Django import export

These are my codes and csv file
class UserResource(ModelResource):
class Meta:
model = User
fields = ('username', 'email', 'is_member')
import_id_fields = ('username',)
class UserAdmin(ImportMixin, admin.ModelAdmin):
resource_class = UserResource
admin.site.register(User, UserAdmin)
username, email, is_member, id
abc, abc#mail.com, True,
When you set:
fields = ('username', 'email', 'is_member')
you are restricting the fields you want to show from all to only the ones you declare.
The above statement means:
import only these fields I'm telling you to import
But if you do:
fields = ('username', 'email', 'is_member', 'id')
I'm guessing you're going to get what you need

DRF : how to add user permissions to user detail api?

So I am writing a UserDetails view as follows.
class UserDetailsView(RetrieveUpdateAPIView):
serializer_class = AuthUserSerializer
def get_object(self):
return self.request.user
My Serializers are as follows.
class PermissionSerializer(serializers.ModelSerializer):
class Meta:
model = Permission
fields = ('id', 'name', 'codename')
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name')
class AuthUserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
# permissions = PermissionSerializer(many=True)
# permissions = serializers.PrimaryKeyRelatedField(many=True, queryset=Permission.objects.all())
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email',
'is_staff', 'is_active', 'is_superuser', 'last_login',
'date_joined', 'groups', 'user_permissions')
groups = GroupSerializer(many=True) gives me following.
"groups": [
{
"id": 2,
"name": "A"
},
{
"id": 1,
"name": "B"
},
{
"id": 3,
"name": "C"
}
],
I expect the similar from permissions = PermissionSerializer(many=True) but I get the following error.
Got AttributeError when attempting to get a value for field `permissions` on serializer `AuthUserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'permissions'.
but instead, if add user_permissions to the fields directly without adding related reference it gives me all ids of permissions. I want to have id, name, codename also. And, Of course, UserPermissions model is not found. ;-(
How do I fix this?
You can use source parameter on the Serializer.
class AuthUserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
permissions = PermissionSerializer(many=True, source='user_permissions')
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email',
'is_staff', 'is_active', 'is_superuser', 'last_login',
'date_joined', 'groups', 'user_permissions', 'permissions')

Generate Row numbers for Django Admin Listview for an App

I want to generate row numbers for the Author list based on pagination. The following code displays the row number. But there is a flaw in this code:
For Example:
I have 100 records on the list and I set the pagination to 25 & now I have 4 Pages. Then I visited all the 4 pages. Then I tried to visit the first page but it counts from 101 and so on. Is there any way to change the code based on pagination value?
What I want is to reset the counter to 1 if I visit the page one and then increment it for all the rows.
class AuthorAdmin(admin.ModelAdmin):
indexCnt = 0
# If you enable fields variable then you will see only these fields in the editable form
# fields = ['first_name', 'last_name', 'email']
exclude = ['created_date'] # it will exclude this field in the editable field
list_display = ['index_counter', 'first_name', 'last_name', 'gender', 'website', 'email', 'phone_number']
list_display_links = ['first_name', 'last_name']
list_filter = ['gender']
search_fields = ['first_name', 'last_name', 'email', 'summary']
ordering = ['id', 'first_name', 'last_name', 'gender']
list_per_page = 25
def index_counter(self, obj):
self.indexCnt += 1
return self.indexCnt
index_counter.short_description = '#'
Try this:
count = Author.objects.all().count()
if self.indexCnt < count:
self.indexCnt += 1
else:
self.indexCnt = 1

Django query taking too much time

I'm using django and django rest framework to make a query from all users in data that have a permission sent as a url parameter but this query is taking too long.
I'm user pycharm debugger how can I try to check why is it taking to long, this is the function:
#list_route(url_path='permission/(?P<permission>.+)')
def read_permission(self, request, *args, **kwargs):
serializer = self.get_serializer_class()
qs = get_user_model().objects.filter_by_permission(self.kwargs.get('permission'))
qs = qs.order_by(Lower('username'))
return Response(serializer(qs, many=True).data)
Update
Adding the serializer
class UserSerializer(UserLabelMixin):
user_permissions = serializers.SlugRelatedField(many=True, read_only=True, slug_field='codename')
class Meta:
model = get_user_model()
fields = ['id', 'email', 'is_superuser', 'is_staff', 'label',
'full_name', 'first_name', 'last_name', 'username',
'teams', 'date_joined', 'last_login',
'user_permissions', 'groups', 'ui_preferences', 'internal_project',
'staff_id', 'oem_id', 'oem_email', 'oem_department', 'comment']
read_only_fields = fields
This may help you
get_user_model().objects.prefetch_related("user_permissions", "groups").filter_by_permission...

Username still required in custom user model

I am trying to use the new functionality in Django 1.5 to make use of an email address as the username.
Everything is working fine, bar the admin site to update users, which I have had to fiddle with to make passwords not appear raw (and use the password change form etc.) using this code:-
class PlayerChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = Player
class PlayerCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = Player
class PlayerAdmin(auth.admin.UserAdmin):
form = PlayerChangeForm
add_form = PlayerCreationForm
ordering = ['first_name', 'last_name']
list_display = ('primkey', 'email', 'mobile')
list_editable = ('email', 'mobile')
list_filter = ()
fieldsets = ((None, {'fields': ('username', 'first_name', 'last_name', 'email', 'password', 'mobile')}),
('Permissions', {'fields': ('is_active', 'is_admin')}),
('Important dates', {'fields': ('last_login', )}),
)
add_fieldsets = ((None, {
'classes': ('wide',),
'fields': ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')}
),
)
filter_horizontal = ()
def primkey(self, obj):
return ("%s" % (obj.get_full_name()))
primkey.short_description = 'Player'
This makes the admin page look fine but when I actually try and update a Player, it tells me there is an error on the form but doesn't indicate where.
After a bit of messing around, it turns out that it wants the username field to be set (if I add that into the admin form, it says this field is required) but surely this isn't the case as I have set my USERNAME_FIELD to be 'email'?
If I set the field to something, I can then save any changes I've made to the other fields but it doesn't save my update to the username field. But really, I don't want to have to set the username at all - I'm using the email as the username.
Any ideas about this or is this a bug in Django?
The Django Documentation states that the forms must be rewritten:
UserCreationForm
Depends on the User model. Must be re-written for any custom user model.
UserChangeForm
Depends on the User model. Must be re-written for any custom user model.
There is a related ticket: https://code.djangoproject.com/ticket/19353 but the code still expect a username field to be present.