Django multiple Admin Model - django

I Wanna use 2 Admin apps such as :
django-admin-sortable
django-import-export
Is there a way to use both in Admin Form ?
I mean my code is using SortableAdmin:
class RuleAdminForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = Rule
fields = '__all__'
class RuleAdmin(SortableAdmin):
list_display = ('title', 'section', 'subsection',)
readonly_fields = ('author', 'date_posted')
fields = ('title', 'section', 'subsection', 'content', 'author', 'date_posted')
form = RuleAdminForm
with .register(Rule, RuleAdmin)
If I want to use import-export I need to create this :
class RuleResource(resources.ModelResource):
class Meta:
model = Rule
class RuleResourceAdmin(ImportExportModelAdmin):
resource_class = RuleResource
But I can't register with .register(Rule, RuleResourceAdmin) since Rule is already registered
Is there a way to have both options ? Using sortable admin to sort my rules, and the possibility to import CSV etc.
Many thanks !

Using of proxy model.
class RuleProxyModel(Rule):
class Meta:
proxy = True
admin.site.register(RuleProxyModel,RuleResourceAdmin)
How to use proxy model

Related

two unrelated models in one serializer django rest framework

I have tried a few different ways to include two unrelated models in one serializer to use in DRF api response. This is the latest of tries below, which doesn't work. I'm trying to include those two values (enable_hourly_rate / vacancy_number) from Tenant model which are under TenantAppUnitExpandedSerializer to TenantAppUnitSerializer. How to do this the proper way?
Thank you in advance for any help.
Code so far:
class TenantAppUnitExpandedSerializer(serializers.ModelSerializer):
class Meta:
model = Tenant
fields = (
'enable_hourly_rate',
'vacancy_number',
)
class TenantAppUnitSerializer(TenantAppUnitExpandedSerializer):
enable_hourly_rate = serializers.SerializerMethodField()
vacancy_number = serializers.SerializerMethodField()
class Meta:
model = Unit
fields = (
'id',
'unit_name',
'city',
'phone',
'enable_hourly_rate',
'vacancy_number'
)
Include it as a field in the serializer you desire to work with.
Then field_name = ThatParticularSerializer() which you want to include.
Here is how your serializer should be.
class TenantAppUnitSerializer(TenantAppUnitExpandedSerializer):
tenant_extended_unit = TenantAppUnitExpandedSerializer(many=False) # <-- here
# similarly you can set many=True if you are expecting multiple instances of it
enable_hourly_rate = serializers.SerializerMethodField()
vacancy_number = serializers.SerializerMethodField()
class Meta:
model = Unit
fields = (
'id',
'unit_name',
'city',
'phone',
'enable_hourly_rate',
'vacancy_number',
'tenant_extended_unit`, # <-- here
)

How to customize Django ModelForm fields?

Hi I am trying to customize my ModelForm in Django. The form looks like this:
class RegistrationForm(forms.ModelForm):
class Meta:
model = Registration
fields = ['name', 'age', 'details'......]
I am trying to add different classes to different fields, along with placeholders and no labels. How do I do that? Is there a way to carry this out in the templates?
You can add class and other parameters to a field using widget
class RegistrationForm(forms.ModelForm):
name = forms.CharField(label=' ',widget=forms.TextInput(attrs={'class':'textClass','placeholder':'Enter Name'}))
details = forms.CharField(widget=forms.Textarea(attrs={'class':'special','maxlength':'100'}))
class Meta:
model = Registration
fields = ['name', 'age', 'details'......]
For brief explanation: Documentation

Add Serializer on Reverse Relationship - Django Rest Framework

I have a Cart model and a CartItem model. The CartItem model has a ForeignKey to the Cart model.
Using Django Rest Framework I have a view where the API user can display the Cart, and obviously then I want to include the CartItem in the respone.
I set up my Serializer like this:
class CartSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
cartitem_set = CartItemSerializer(read_only=True)
class Meta:
model = Cart
depth = 1
fields = (
'id',
'user',
'date_created',
'voucher',
'carrier',
'currency',
'cartitem_set',
)
My problem is the second line, cartitem_set = CartItemSerializer(read_only=True).
I get AttributeErrors saying 'RelatedManager' object has no attribute 'product'. ('product' is a field in the CartItem model. If I exclude product from the CartItemSerializer I just get a new AttributeError with the next field and so on. No matter if I only leave 1 or all fields in the Serializer, I will get a error.
My guess is that for some reason Django REST Framework does not support adding Serializers to reverse relationships like this. Am I wrong? How should I do this?
PS
The reason why I want to use the CartItemSerializer() is because I want to have control of what is displayed in the response.
Ahmed Hosny was correct in his answer. It required the many parameter to be set to True to work.
So final version of the CartSerializer looked like this:
class CartSerializer(serializers.ModelSerializer):
cartitem_set = CartItemSerializer(read_only=True, many=True) # many=True is required
class Meta:
model = Cart
depth = 1
fields = (
'id',
'date_created',
'voucher',
'carrier',
'currency',
'cartitem_set',
)
It's important to define a related name in your models, and to use that related name in the serializer relationship:
class Cart(models.Model):
name = models.CharField(max_length=500)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, related_name='cart_items')
items = models.IntegerField()
Then in your serializer definition you use those exact names:
class CartSerializer(serializers.ModelSerializer):
cart_items = CartItemSerializer(read_only=True)
class Meta:
model = Cart
fields = ('name', 'cart_items',)
It would be wise to share your whole code, that is model and serializers classes. However, perhaps this can help debug your error,
My serializer classes
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = CartItem
fields = ('id')
class CartSerializer(serializers.ModelSerializer):
#take note of the spelling of the defined var
_cartItems = CartItemSerializer()
class Meta:
model = Cart
fields = ('id','_cartItems')
Now for the Models
class CartItem(models.Model):
_cartItems = models.ForeignKey(Subject, on_delete=models.PROTECT)
#Protect Forbids the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
class Meta:
ordering = ('id',)
class Cart(models.Model):
class Meta:
ordering = ('id',)
For a detailed overview of relationships in django-rest-framework, please refer their official documentation

Restricted set of nested fields in a django REST framework ModelSerializer

Consider the following serializer
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'account')
depth = 1
The field account refers to a ForeignKey in MyModel and I want to expose some of the Account fields with this serializer but not all of them.
How do I specify that only account.name and account.email should be serialized?
You can do this by creating your own serializer to use as the nested serializer.
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('name', 'email', )
You are better off with creating specialized serializers instead of relying on Django REST Framework to create them for you. By default, serializers that are automatically created contain all fields defined on the model.
class MyModelSerializer(serializers.ModelSerializer):
account = AccountSerializer()
class Meta:
model = MyModel
fields = ('id', 'account', )
You can find out more about nested serializers in the Django REST Framework documentation.

Django Rest Framework - image url on reverse foreignkey

I am trying to access the url of an ImageField on a model related through a reverse-ForeignKey. I have attempted various possible options based on examples in the docs, but have had no luck. Any help would be appreciated.
models.py
class Car(models.Model):
name = models.CharField(... )
#property
def default_image(self):
... ...
return image # <=== returns from the CarImage model
class CarImage(models.Model):
car = models.ForeignKey(Car) # <=== no related_name set, but technically we could use carimage_set
image = models.ImageField(... ...)
serializers.py (attempt)
class CarSerializer(serializers.ModelSerializer):
... ...
image = fields.SerializerMethodField('get_image')
class Meta:
mode = Car
def get_image(self, obj):
return '%s' % obj.default_image.url
exception
'SortedDictWithMetadata' object has no attribute 'default_image'
The new DRF 2.3 seems to be helpful with reverse relationships and has solved my issues.
DRF 2.3 Announcement
For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
class BlogSerializer(serializers.ModelSerializer):
comments = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Blog
fields = ('id', 'title', 'created', 'comments')
As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
class BlogSerializer(serializers.ModelSerializer):
"""Don't need to specify the 'comments' field explicitly anymore."""
class Meta:
model = Blog
fields = ('id', 'title', 'created', 'comments')