I want to create a button that deletes the selected row in the table (1 button per row)
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export.admin import ImportExportMixin
from .models import Applicant
class ApplicantAdmin(ImportExportModelAdmin, admin.ModelAdmin):
list_display = ('Name', 'DOB', 'PhoneNumber', 'Address', 'Batch',
'created_at', 'updated_at',)
list_filter = ('Name', 'Address', 'Batch', 'created_at', 'updated_at',)
list_per_page = 10
# actions = [transferdata, ]
# Register the admin class with the associated model
admin.site.register(Applicant, ApplicantAdmin)
models.py
from django.db import models
from django.utils import timezone
class Applicant(models.Model):
id = models.CharField(max_length=10).primary_key
Name = models.CharField(max_length=50)
DOB = models.CharField(max_length=10)
PhoneNumber = models.CharField(max_length=20)
Address = models.CharField(max_length=200)
Batch = models.CharField(max_length=200)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.Name
I already know django-jet that provides this facility a drop-down menu, but for the whole table (i.e. not for the each row)
This problem by creating a function inside the required admin class.
admin.py
import django.contrib import admin
import import_export.admin import ImportExportModelAdmin
import import_export.admin import ImportExportMixin
import .models import Applicant
class ApplicantAdmin(ImportExportModelAdmin, admin.ModelAdmin):
list_display = ('Name', 'DOB', 'PhoneNumber', 'Address', 'Batch',
'created_at', 'updated_at',)
list_filter = ('Name', 'Address', 'Batch', 'created_at', 'updated_at',)
list_per_page = 10
# actions = [transferdata, ]
#staticmethod
def action_button(self):
# assuming the url is saved as 'button_url'
# enter the url to be parsed when the button will be clicked and name the button
return format_html('<a class="button" href="%s">(name of the button)</a>' % button_url)
# Register the admin class with the associated model
admin.site.register(Applicant, AdminApplicant)
Create a function of the button in the views.py
In the urls.py enter the url (almost the same as in admin class) in urlpatterns of the app and call the function present in views.py
Related
I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value.
I would like to show all user in Django admin panel which role is couple only.
In admin.py:
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from users.forms import UserChangeForm, UserCreationForm
from users.models import EmailConfirmationToken
User = get_user_model()
#admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
I did manage to solve this problem, by defining a variable in my model.py file
called
#models.py
role_couple = models.CharField(max_length=7, default='couple')
role_vendor = models.CharField(max_length=7, default='vendor')
and then i changed the admin.py file to this
#admin.py
list_display = ('role_couple' , 'N1' , 'N2' , 'N3')
another solution is to add default_filters variable:
for example
#admin.py
list_filters = ('role',)
default_filters = { 'role':'couple'}
am sorry if the first one didn't helped you
BG
I got the solution by customizing the queryset in ModelAdmin Class.
#admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets
list_display = ["username", "name", "is_superuser", "is_active"]
search_fields = ["name", "subscription"]
def get_queryset(self, request):
qs = super(UserAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs.filter(role='couple')
return qs
I am trying to extend the User model to allow a user to add an image to their profile, however have no option to save an image in the admin for my page. The other extended fields are showing. I am not sure why this is..
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.TextField(default='', blank='')
last_name = models.TextField(default='', blank='')
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def user_image_upload_handler(instance, filename):
fpath = pathlib.Path(filename)
new_fname = str(uuid.uuid1()) # uuid1 -> uuid + timestamps
return f"request/{new_fname}{fpath.suffix}"
class ProfilePicture(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to=user_image_upload_handler, blank=True)
admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from .models import Profile, ProfilePicture
class ProfileAdmin(admin.ModelAdmin):
model = [Profile]
list_display = ['id']
class ProfilePictureAdmin(admin.ModelAdmin):
model = [ProfilePicture]
extra = 10
class UserAdmin(admin.ModelAdmin):
model = ProfileAdmin
model = ProfilePictureAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
from https://docs.djangoproject.com/en/4.0/ref/contrib/auth/
first_name, last_name and email are already part of the standard django User so there was no need to extend those. My accounts/admin.py was simply
from django.contrib import admin
from django.contrib.auth.models import User
from .models import ProfilePicture
class ProfilePictureAdmin(admin.StackedInline):
model = ProfilePicture
extra = 1
class ExtendedUserAdmin(admin.ModelAdmin):
inlines = [ProfilePictureAdmin]
list_display = ['id', 'username', 'first_name']
admin.site.unregister(User)
admin.site.register(User, ExtendedUserAdmin)
My Models
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
def no_of_ratings(self):
ratings = Rating.objects.filter(product=self)
return len(ratings)
def avg_rating(self):
ratings = Rating.objects.filter(product=self)
sum=0
for rating in ratings:
sum += rating.rating
if len(ratings)>0:
return sum/len(ratings)
else:
return None
def __str__(self):
return self.title
class Rating(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
class Meta:
unique_together = (('user', 'product'),)
index_together = (('user', 'product'),)
serializer.py
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from .models import Product, Rating
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
Token.objects.create(user=user)
return user
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields =('id', 'title', 'description', 'no_of_ratings', 'avg_rating')
class RatingSerializer(serializers.ModelSerializer):
class Meta:
model = Rating
fields = ('product', 'user', 'rating')
views.py
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from .models import Rating, Product
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.permissions import IsAuthenticated, AllowAny
from .serializers import ProductSerializer, RatingSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.filter(product__rating__gte = 4 )
serializer_class = ProductSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)
class RatingViewSet(viewsets.ModelViewSet):
queryset = Rating.objects.filter(rating__gte = 4)
serializer_class = RatingSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)
Hi, I'm new in Django Rest Framework, I want to filter my product on the bases of rating, but my filter doesn't work, I have two models classes Product and Rating every Product have a rating( Foreign key ), I want to list only +4 rated product, how can I achieve that, and can I filter results to get models with specific rating?
With queryset = Product.objects.filter(product__rating__gte = 4 ) you look up products and filter them by their field product but your product instances don't have this field or property.
In your views.ProducViewSet You should filter for something like
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.filter(rating_set__rating__gte = 4 )
# ...
instead. rating_set is the default name to access foreign keys in the other direction (from the model where it's not defined in) You can use the related_name parameter in the ForeignKey to set this to a custom name like product_rating. (Notice the use of single _, it wouldn't work with double __)
Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result.
in my model.py I have this
class Entry(models.Model):
TYPES_CHOICES = (
('none', 'not specified'),
('s', 'Series'),
('mb', 'Multiples Bar'),
('b', 'Bar suggestion'),
)
app_config = AppHookConfigField(HealthConfig)
code = models.CharField(blank=True, default='', max_length=250)
url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" )
health_placeholder = PlaceholderField('health_info')
objects = AppHookConfigManager()
def __unicode__(self):
return self.url
class Meta:
verbose_name_plural = 'entries'
and now in my form.py I have this
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['code'].widget.attrs={
'id': 'my_code',
'class': 'code_class',
}
finally my admin.py is like this
from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from .cms_appconfig import HealthConfig
from .models import Entry
from .forms import EntryForm
from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
class EntryAdmin(ModelAppHookConfig, PlaceholderAdminMixin, admin.ModelAdmin):
# pass
fieldsets = (
('General data', {
'fields':('app_config','chart', 'url',('count', 'code', 'start'))
}),
('Suggestion',{
'classes':('collapse', 'suggestion',),
'fields':('url_suggestion',('key1_suggestion_name','key1_suggestion'),('key2_suggestion_name','key2_suggestion'), 'primary_suggestions')
}),
)
list_display =('app_config' ,'url', 'chart');
list_filter = (
'app_config',
)
form = EntryForm
class Media:
js = ('health/js/admin/healthAdmin.js',)
css = {
'all': ('health/css/admin/admin_area.css',)
}
admin.site.register(Entry, EntryAdmin)
any idea is I missing something, after that, I do a migrate of the component again.
Thanks in advance!
You can specify a custom form for admin using the form attribute of ModelAdmin.
So using the example from the docs linked below, that would look like;
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
So in your admin.py you'd need something like;
from .forms import EntryForm
class EntryAdmin(admin.ModelAdmin):
form = EntryForm
I have a new project on django, in which im using Grappelli and filebrowser, and I have extended the User to have a UserProfile related to it, my question is, how can I modify my code to be able to show on the UserProfile information of a user the profile picture uploaded, and also show it on the Users list?
This is my code now, I dont see any image on the admin!
Admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
verbose_name_plural = 'User Profile'
list_display = ('city', 'tel', 'description', 'image_thumbnail',)
class MyUserAdmin(UserAdmin):
list_display = ('username','email','first_name','last_name','date_joined',
'last_login','is_staff', 'is_active',)
inlines = [ UserProfileInline ]
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _
from apps.common.utils.abstract_models import BaseModel
from apps.common.utils.model_utils import unique_slugify
from filebrowser.base import FileObject
from django.conf import settings
class UserProfile(BaseModel):
user = models.OneToOneField(User, related_name="profile")
city = models.CharField(_("City"), max_length=200)
tel = models.CharField(_("Phone Number"), max_length=50,
help_text=_("(Area Code) (Your phone number)"))
description = models.TextField(null=True, blank=True,
help_text = _("Small description about yourself."))
photo = models.ImageField(max_length=255, upload_to="profiles/",
null=True, blank=True, default="img/default_profile_image.png")
def image_thumbnail(self):
if self.photo:
return u'<img src="%s" width="80" height="80" />' % self.photo.version(ADMIN_THUMBNAIL).url
return u'<img src="/site_media/%s" width="80" height="80" />' % settings.DEFAULT_PROFILE_IMAGE
image_thumbnail.allow_tags = True
def __unicode__(self):
if self.user.first_name or self.user.last_name:
return "%s %s" % (self.user.first_name, self.user.last_name)
else:
return self.user.username
Well I got it, first I wanted to show the image chosen on the UserProfile inline section of the user model for the admin and also on the change list of the admin so heres what I
I changed the models.ImageField to sorl ImageField on the model.py of User profile like this
from sorl.thumbnail import ImageField
class UserProfile(BaseModel):
[...]
photo = ImageField(max_length=255, upload_to="profiles/",
null=True, blank=True, default="img/default_profile_image.png")
Then on the admin all I had to do was add sorl's AdminImageMixin on the UserProfileInline class, like this:
from sorl.thumbnail.admin import AdminImageMixin
class UserProfileInline(AdminImageMixin, admin.StackedInline):
model = UserProfile
verbose_name_plural = 'User Profile'
And that way you get an image on the UserProfile Inline section on the admin for that user, now for the change_list.
For the change list I had to do a small callable function inside the admin.py file on the UserAdmin class, heres what I did, using sorl's get_thumbnail:
from sorl.thumbnail import get_thumbnail
class MyUserAdmin(UserAdmin):
def image_thumbnail(self, obj):
im = get_thumbnail(obj.get_profile().photo, '80x80', quality=99)
return u"<img src='/site_media/%s' />" % im
image_thumbnail.allow_tags = True
list_display = ('image_thumbnail', 'username','email','first_name','last_name','date_joined',
'last_login','is_staff', 'is_active',)
And now I have a change list image of the user profile and also on the UserProfile Inline section.
Hope this works for everyone out there... and thanks #pastylegs for your previous answer!
list_display needs to be a callable:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
so you can do:
class UserProfileInline(admin.StackedInline):
def image_thumbnail(self, obj):
return obj.image_thumbnail()
image_thumbnail.short_description = 'Thumbnail'
model = UserProfile
verbose_name_plural = 'User Profile'
list_display = ('city', 'tel', 'description', 'image_thumbnail',)