Django additional fields in TabularInline - python

I have such structure:
#admin.py
class OrderProductInline(admin.TabularInline):
model = OrderProduct
extra = 0
template = "admin/edit_inline/tabular_order.html"
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
...
inlines = [
OrderProductInline
]
#models.py
class OrderProduct(models.Model):
...
order_id = models.ForeignKey(Order, on_delete=models.CASCADE, blank=False,
null=False)
to_product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=False,
null=True, verbose_name=_('Product'))
On the attached image I show some custom inputs (red rectangles) for each product item in inline form. This inputs depends on additional queryset based on Foreign Key, but I cant`t find the correct way how to display this fields there.

Related

Django admin reverse foregin key relationship

I have a number of different models connected to the User model through a foregin key relationship. I would now like to display all the attributes from the objects connected to the User model in the main admin overview.
models.py
class User(AbstractBaseUser):
username = models.CharField(max_length=60)
lastname = models.CharField(max_length=60, blank=True)
class UserProfile(models.Model):
user_id = models.OneToOneField(
User,
on_delete=models.CASCADE,
primary_key=True,
)
address = models.CharField(max_length=60, blank=True)
admin.py
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user_firstname', 'user_lastname', 'address')
def user_firstname(self, instance):
return instance.user_id.username
def user_lastname(self, instance):
return instance.user_id.lastname
admin.site.register(UserProfile, UserProfileAdmin)
The code above works perfectly well to display attributes from "User" in "Userprofile", but how do I do this the other way around? In my code I currently have 4 different objects connected to the User object so keen to find a way to display all the data there.
use inlines
models.py
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
admin.py
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
more info read https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects

Django API ManyToMany on existing databse not working

at the moment I try to get recipes from my API. I have a Database with two tables one is with recipes and their ids but without the ingredients, the other table contains the ingredients and also the recipe id. Now I cant find a way that the API "combines" those. Maybe its because I added in my ingredient model to the recipe id the related name, but I had to do this because otherwise, this error occurred:
ERRORS:
recipes.Ingredients.recipeid: (fields.E303) Reverse query name for 'Ingredients.recipeid' clashes with field name 'Recipe.ingredients'.
HINT: Rename field 'Recipe.ingredients', or add/change a related_name argument to the definition for field 'Ingredients.recipeid'.
Models
from django.db import models
class Ingredients(models.Model):
ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True)
recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='recipeid', blank=True, null=True, related_name='+')
amount = models.CharField(blank=True, null=True, max_length=100)
unit = models.CharField(blank=True, null=True, max_length=100)
unit2 = models.CharField(blank=True, null=True, max_length=100)
ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255)
class Meta:
managed = False
db_table = 'Ingredients'
class Recipe(models.Model):
recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase.
title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase.
preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase.
images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase.
#ingredients = models.ManyToManyField(Ingredients)
ingredients = models.ManyToManyField(Ingredients, related_name='recipes')
class Meta:
managed = True
db_table = 'Recipes'
When there is no issue it has to be in the serializer or in the view.
Serializer
class IngredientsSerializer(serializers.ModelSerializer):
# ingredients = serializers.CharField(source='ingredients__ingredients')
class Meta:
model = Ingredients
fields = ['ingredient','recipeid']
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientsSerializer(many=True)
class Meta:
model = Recipe
fields = ['title','ingredients']
View
class FullRecipesView(generics.ListCreateAPIView):
serializer_class = FullRecipeSerializer
permission_classes = [
permissions.AllowAny
]
queryset = Recipe.objects.all()
This is at the moment my output
But I want e.g. the recipe with id 0 and all the ingredients which have also recipe id 0.
I really hope that you can help me. Thank you so much!
Rename ingredients to some other name in FullRecipeSerializer. It conflicts with ingredients in Recipe model. This should solve your issue. For example
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients_recipe = IngredientsSerializer(many=True, source= 'ingredientid')
class Meta:
model = Recipe
fields = ['title','ingredients_recipe']

Display a model field as readonly in Django admin

I want to display a model field ie module_name as read only in django user profile edit page. The model Category has a manytomany relationship with Profile model.
Category
id category_name module_name
1 A X
2 B Y
profile_category
id profile_id category_id
1 2 1
So for eg. when I am on the admin page to editing a user id of 2 then I would like to display the module name X if category id 1 is assigned to the user id 2
models.py
class Category(models.Model):
category_name = models.CharField(max_length=150, blank=False, null=True, default="", unique=True)
module_name = models.TextField(blank=False, null=True)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile')
phone_number = PhoneNumberField( blank=True, null=True)
organisation = models.CharField(max_length=30, blank=True)
category = models.ManyToManyField(Category)
admin.py
class ProfileInline(admin.StackedInline):
model = Profile
filter_horizontal = ('category',)
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_select_related = ( 'profile', )
Please suggest if this is possible or not.
Any help/suggestion is highly appreciated. Thanks in advance.
Method 1
Use readonly_fields which is inherited from admin.BaseModelAdmin.
class ProfileInline(admin.StackedInline):
model = Profile
readonly_fields = ('module_names',)
def module_names(self, instance):
# Write a get-method for a list of module names in the class Profile
# return HTML string which will be display in the form
return format_html_join(
mark_safe('<br/>'),
'{}',
((line,) for line in instance.get_module_names()),
) or mark_safe("<span>The user belongs to no category</span>")
# short_description functions like a model field's verbose_name
module_names.short_description = "Module names"
Method 2
For older versions of admin site, you can hook the get_fieldsets method of admin.StackedInline. This method was posted here with a nice example.

Categories and sub-categories in django

I have an entity of Products, category and sub-category. A category can have many products and also a category can have many sub-categories. For example a product called Iphone-4 can fall on smart phone subcategories of Electronics & Gadgets Category. Similiary samsung product can fall on same smart-phone sub-categories of Electronics&Gadgets Category. How could i show this relation effectively?
Here is what i did
class Category(models.Model):
name = models.CharField(max_length=80, null=True)
parent = models.ForeignKey('self', blank=True, null=True, related_name="children")
class Meta:
unique_together = ('parent',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Product(models.Model):
token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False)
category = models.ForeignKey(Category)
company = models.ForeignKey(Company, related_name="company_product")
name = models.CharField(max_length=200, null=True)
model = models.CharField(max_length=100, blank=True, null=True)
specification = models.TextField(null=True, blank=True)
price = models.PositiveIntegerField(default=0)
admin.py
class ProductAdmin(admin.ModelAdmin):
list_select_related = ('category', 'company',)
class Meta:
model = Product
class CategoryAdmin(admin.ModelAdmin):
list_select_related = ('parent',)
list_display = ('name', 'parent', )
class Meta:
model = Category
This way in my admin, the categories and sub-categories are shown so vaguely. Category Electronics & Gadgets is shown multiple times. It is shown as per the number of sub-category that falls under this category.
Is this expected behavior or has to handle this other effective way?
Here is the code snippet to list nested Category and Sub-Category inside the Admin Panel. Please register the Category model in the admin.py of your application first.
# Category Model.
class Category(models.Model):
name = models.CharField(blank=False, max_length=200)
slug = models.SlugField(null=False)
parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL)
class Meta:
db_table = "dj_categories"
# Add verbose name
verbose_name = 'Category'
verbose_name_plural = "Categories"
unique_together = ('slug', 'parent',)
def __str__(self):
return self.name

django autofill manytomany field in admin

Good day, not so long ago, working with Django.
Encountered the following problem.
There are two models
class Product(models.Model):
productID = models.AutoField(primary_key=True)
brandID = models.ForeignKey(Brand, verbose_name=u'Бренд')
categoryID = models.ForeignKey(Category, verbose_name=u'Категория')
productPhotos = models.ManyToManyField("ProductPhoto", verbose_name = "Фотографии товара", related_name="photos", blank=True)
class ProductPhoto(models.Model):
productPhotoID = models.AutoField(primary_key=True)
productID = models.ForeignKey(Product)
imageFile = models.FileField(u'Путь к изображение', upload_to=makeUploadPath)
dateModified = models.DateField(auto_now=True)
For admin use the following TabularInline
class ProductPhotoInline(admin.TabularInline):
model = ProductPhoto
verbose_name = u"Фото"
verbose_name_plural = u"Фотографии"
class ProductAdmin(admin.ModelAdmin):
list_display = ('title')
search_fields = ...
fieldsets = ...
)
inlines = [ ProductPhotoInline, ]
The problem when you add a product in the table ProdcutPhoto productId field is filled, and the field in the table Products productPhotos is empty. How best to do to fill both fields.
You should remove the productPhotos ManyToMany field, it's redundant. If each photo is only attached to one product, then the productID ForeignKey is all you need.
To access the photos from a product instance, you can use productphoto_set, e.g.
product = Product.objects.get(pk=1)
photos = product.productphoto_set.all()

Categories