There is a class named Employees in models.py
class Employees(models.Model):
employee_id = models.CharField(verbose_name = _("Employee ID"), max_length=20, primary_key=True)
employee_name = models.CharField(verbose_name = _("Employee Name"), max_length=20)
department = models.CharField(verbose_name = _("Department"), max_length=100)
post = models.CharField(verbose_name = _("Post"), max_length=100)
Then I wrote some code in admin.py
class EmployeesAdmin(admin.ModelAdmin):
list_display = ('employee_id', 'employee_name', 'department', 'post')
According to the tutorial, there should be four fields in the Employee branch. But in my situation, there is only one field named Employees, just like I didn't add EmployeesAdmin class in admin.py. What's wrong with it? Did I miss something?
admin.py:
from django.contrib import admin
from .models import Employees, Purchase, ProductsOut
# Register your models here.
admin.site.register(Employees)
admin.site.register(Purchase)
admin.site.register(ProductsOut)
Register your admin in admin.site like:-
admin.site.register(ModelName, AdminName)
Try the following after declaring your EmployeesAdmin class in admin.py:
admin.site.register(Employees, EmployeesAdmin)
Related
I'm trying fill automatically my list_display on my admin Django, apparently the code works correctly, but it doesn't show nothing. This is my code
Model
class Pacient(models.Model):
name = models.CharField(
max_length=50
)
last_name = models.CharField(
max_length=50
)
id_identification = models.IntegerField()
age= models.PositiveSmallIntegerField()
gender = models.ForeignKey(
Gender,
on_delete=models.CASCADE
)
blood_type = models.ForeignKey(
BloodType,
on_delete=models.CASCADE
)
def __str__(self):
return self.name
Admin.py
from django.contrib import admin
from .models import Pacient
class PacientAdmin(admin.ModelAdmin):
list_display=()
x = Pacient.objects.values()
def some(self):
for k in self.x:
k = k.keys()
self.list_display=(tuple(k))
print (self.list_display)
return self.list_display
admin.site.register(Pacient,PacientAdmin)
You need to call the some function in list_display - also the method of the class is used differently. This code snipped should work and show your Pacient data in the list_display and also "test" in every line:
from django.contrib import admin
from .models import Pacient
#admin.register(Pacient)
class PacientAdmin(admin.ModelAdmin):
list_display=["name", "last_name", "age", "some",]
def some(self, obj):
return "test"
so I have these two models
class Recipe(models.Model):
short_description = HTMLField(max_length=400)
likes = models.ManyToManyField(User, blank=True, related_name='recipe_likes')
slug = models.SlugField(blank=True, unique=True)
published_date = models.DateTimeField(blank=True, default=datetime.now)
ratings = GenericRelation(Rating, related_query_name='recipes')
class Ingredient(models.Model):
name = models.CharField(max_length=20)
amount = models.FloatField()
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='recipe_ingredients')
In the admin panel from the recipes section, if I choose a recipe I want to be able to add ingredients for that recipe, what do I need? I think I don't know the right searchterms to use, hope you understand what I mean.
Thanks for the help.
EDIT
This is the solution:
from django.contrib import admin
from .models import Recipe, Ingredient
class IngredientInline(admin.TabularInline):
model = Ingredient
extra = 3
#admin.register(Recipe)
class RecipeAdmin(admin.ModelAdmin):
list_display = ('title',)
search_fields = ('title', )
inlines = [IngredientInline,]
from django.contrib import admin
from .models import Recipe, Ingredient
class IngredientInline(admin.TabularInline):
model = Ingredient
extra = 3
#admin.register(Recipe)
class RecipeAdmin(admin.ModelAdmin):
list_display = ('title',)
search_fields = ('title', )
inlines = [IngredientInline,]
You'll want to read up on InlineModelAdmins:
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects
When you register your models with a model admin class, add an inlines list.
The documentation is good on this, so please expand your question if you have more detailed questions!
I have two models in my application. Here is my code in models.py:
from django.db import models
class TblDivision(models.Model):
strdivisionname = models.CharField(db_column='strDivisionName', max_length=35, blank=True, null=True) # Field name made lowercase.
class Meta:
db_table = 'Tbl_Division'
class TblPosition(models.Model):
strpositionname = models.CharField(db_column='strPositionName', max_length=30, blank=True, null=True) # Field name made lowercase.
class Meta:
db_table = 'Tbl_Position'
class TblEmployee(models.Model):
strname = models.CharField(db_column='strName', max_length=70, blank=True, null=True) # Field name made lowercase.
stremployeeid = models.CharField(db_column='strEmployeeID', max_length=10, blank=True, null=True) # Field name made lowercase.
bitactive = models.BooleanField(db_column='bitActive', blank=True, null=True) # Field name made lowercase.
intdivision = models.ForeignKey(TblDivision, db_column='intDivision',related_name='division', on_delete=models.CASCADE)
intposition = models.ForeignKey(TblPosition, db_column='intPosition',related_name='position', on_delete=models.CASCADE)
class Meta:
db_table = 'Tbl_Employee'
This is my code in serializer.py:
from rest_framework import serializers
from .models import TblEmployee,TblDivision
class DivisionSerializer(serializers.ModelSerializer):
class Meta:
model = TblDivision
fields=['id','strDivisionName']
class EmployeeSerializer(serializers.ModelSerializer):
division = DivisionSerializer(many=True, read_only=True)
class Meta:
model = TblEmployee
fields=['id','strname','stremployeeid','intdivision','division']
And this my views.py:
from .models import TblEmployee
from .serializer import EmployeeSerializer,DivisionSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
#api_view(["GET", ])
def api_list_employee_view(request):
try:
employee_list = TblEmployee.objects.all()
except TblEmployee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer = EmployeeSerializer(employee_list, many="true")
dataEmployee = serializer.data
return Response(dataEmployee)
I want to create a simple API that shows data from Employee model and its division name in JSON Format. But the API doesn't show the strDivisionName field. It shows only field from Employee model. Can Anyone explain my problem and its solution? I'm still new in Django Rest Framewrok. Thank you before
Update your serializer with this code:
from rest_framework import serializers
from .models import TblEmployee,TblDivision
class DivisionSerializer(serializers.ModelSerializer):
class Meta:
model = TblDivision
fields=['id','strdivisionname']
In the fields, you showing the wrong field name. It's strdivisionname not strDivisionName.
my friend you made a mistake in your serializer code! you must provide exact same name you entered in your models (in models you wrote : 'strdivisionname' and in serializer : 'strDivisionName')
because you serialize your TblEmployee instance with EmployeeSerializer! and in your EmployeeSerializer there is not any strdivisionname fields! you must make a foreignKey from that in your models, am I right?
I have a Django app with the following models.py
from django.db import models
class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
delivered = models.BooleanField(default=False)
class OrderItem(models.Model):
order = models.ForeignKey(Order,
related_name='items',
on_delete=models.CASCADE)
product = models.ForeignKey(Product,
related_name='order_items',
on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
And in my admin.py, I have this
from django.contrib import admin
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['id', 'first_name', 'last_name', 'email',
'paid', 'delivered']
list_filter = ['paid', 'delivered']
This only shows the Order table.
I would like to join the Order with the OrderItem table and display it in the Django admin. I am not sure this is relevant but for one Order, there could be many OrderItem(s).
As far as I know, you can't show OrderItems in OrderAdmin directly. But you can show Order in OrderItemAdmin, or use InLineModelAdmin to show OrderItems in Order Detail page. Like this:
class OrderItemInline(admin.TabularInline):
model = OrderItem
class OrderAdmin(admin.ModelAdmin):
inlines = [
OrderItemInline,
]
If you still want to display OrderItems (or parts of order item) in admin page, then you can add a method in list_display field, and use that method to fetch OrderItems. Like this:
class OrderAdmin(admin.ModelAdmin):
list_display = (..., 'get_order_items')
def get_order_items(self, obj):
return return ", ".join(obj.items.values_list("pk", flat=True))
get_order_items.short_description = 'Order Items'
In my Django project I have a model:
class Category(MPTTModel):
name = models.CharField(default='',
max_length=50,
verbose_name='Название')
slug = models.SlugField(default='')
parent = TreeForeignKey('self',
related_name='children',
null=True,
blank=True,
verbose_name='Родительская категория'
)
order = models.PositiveSmallIntegerField(blank=False,
null=False,
default=0,
verbose_name='Порядок')
is_active = models.BooleanField(default=True,
db_index=True,
verbose_name='Отображать на сайте')
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'категории'
class MPTTMeta:
order_insertion_by = ['order']
If I add the main categories first (one, two, three), and then add subcategories (four in one, five in two, six in three), I would like to see it in the admin panel like this:
-one
--four
-two
--five
-three
--six
But I have this ordering:
-one
-two
-three
--four
--five
--six
What am I doing wrong?
You need to register Category model with MPTTModelAdmin
In your admin.py
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from .models import Category
admin.site.register(Category, MPTTModelAdmin)
Reference: https://django-mptt.github.io/django-mptt/admin.html
Thanx! It seems that SortableModelAdmin from suit.admin broke an order.
My admin.py was:
from suit.admin import SortableModelAdmin
from mptt.admin import MPTTModelAdmin
from .models import Category, Good
class CategoryAdmin(MPTTModelAdmin, SortableModelAdmin):
mptt_level_indent = 20
list_display = ('name', 'slug', 'is_active', 'order')
list_editable = ('is_active',)
prepopulated_fields = {"slug": ("name",)}
# Specify name of sortable property
sortable = 'order'
admin.site.register(Category, CategoryAdmin)