Django. Where to put custom methods in models.py? - django

I put some logic into custom methods in my model.
I did it for using those methods in views
My model:
class Quiz(models.Model):
# Some fields..
# And some example methods that contain a logic
def get_manage_questions_url(self):
return reverse('manage-questions', kwargs={'slug': self.slug})
def get_likes_count(self):
return self.likes.count()
def get_completed_count(self):
return QuizManager.objects.filter(quiz=self, completed=True).count()
def like_quiz(self, quiz, user):
data = {}
if user in quiz.likes.all():
quiz.likes.remove(user)
data['liked'] = False
else:
quiz.likes.add(user)
data['liked'] = True
data['likes'] = quiz.get_likes_count()
return data
def increase_views(self):
self.views += 1
self.save(update_fields=('views',))
I have a question:
Do I need to write all custom methods in the model or I need to put methods like these into a manager kind of QuizManager(models.Manager) and define "objects" attribute in the quiz model?

Related

Django - calling custom update behaviour when overriding its behavour

What I am trying to do is best described by example. Consider the following:
class QuerySetManager(models.Manager):
def get_queryset(self):
result = self.model.QuerySet(self.model)
try:
result = result.filter(is_deleted=False)
except FieldError:
pass
return result
class MyModel(model.Models):
# core fields
objects = QuerySetManager()
class Meta:
managed = False
db_table = 'my_model'
class QuerySet(QuerySet):
def update(self, *args, **kwargs):
if something_special:
# handle that special case
else:
# call custom update
In effect, I am trying to override the update method of QuerySet's superclass. If something special happens, I would like to implement update process myself, and otherwise - call the standard update method of the superclass.
Any help on what the correct syntax is?
UPDATE
Let me provide a bit detailed background.
I am using the pattern found here.
The entire architecture looks like this:
class DeleteMixin(models.Model):
is_deleted = models.BooleanField(default=False)
class Meta:
abstract = True
class QuerySetManager(models.Manager):
def get_queryset(self):
result = self.model.QuerySet(self.model)
try:
result = result.filter(is_deleted=False)
except FieldError:
pass
return result
class Sms(DeleteMixin):
# core fields
objects = QuerySetManager()
class Meta:
managed = False
db_table = 'sms'
class QuerySet(QuerySet):
def inbox(self, user):
return self.filter(sms_type_id = 1)
def outbox(self, user):
return self.filter(sms_type_id = 2)
def update(self, *args, **kwargs):
if something_special:
# handle that special case
else:
# the issue in question - call custom update
This architecture enables me to:
exclude records with is_deleted field equal to 1 (for those tables where there is such field)
use chainable filters like sms.objects.inbox().outbox()
It's not enitrely clear what you are asking. IF you are trying to add a custom update method to a Queryset's superclass update method like this:
class MyQuerySet(QuerySet):
def update(self, *args, **kwargs):
....
super(MyQuerySet,self).update(*args,**kwargs)
if you are trying to override the save method in the model
class MyModel(model.Models):
def save(self,*args,**kwargs):
...
super(MyModel,self).save(*args,**kwargs)
Update (pun intended)
The code sample I have posted above is correct. The QuerySet class definitely as an update method. as can be seen here:
https://github.com/django/django/blob/master/django/db/models/query.py#L630
And if you have sub classed QuerySet correctly you will not get the error. But you haven't
class QuerySet(QuerySet):
This is incorrect.
Eventually, I got it work this way:
def update(self, *args, **kwargs):
if something_special:
# handle that special case
else:
super(self.model.QuerySet, self).update(*args,**kwargs)

How to set a custom queryset class for Django admin actions?

In an application I'm building, I've created a series of custom model managers and querysets to have a higher level api.
The problem comes when I execute an admin action. The queryset passed to it seems to be a generic one, and I would like to have access to my custom queryset to be able to use the filtering functions I created in it.
This is the action:
def mark_payment_as_sent_action():
''' Admin action to mark payment as sent '''
def mark_payment_as_sent(modeladmin, request, queryset):
# #####################################################################
# This is what I currently do
payments = queryset.filter(status=models.Payment.S_PENDING)
# This is what I want to do
payments = queryset.pending()
# #####################################################################
# Do stuff with filtered payments
return HttpResponseRedirect("...")
mark_payment_as_sent.short_description = "Mark as sent"
return mark_payment_as_sent
These are the custom model manager an query set:
class PaymentQuerySet(models.query.QuerySet):
def pending(self):
return self.filter(status=self.model.S_PENDING)
class PaymentManager(models.Manager):
use_for_related_fields = True
def get_query_set(self):
return PaymentQuerySet(self.model)
def pending(self, *args, **kwargs):
return self.get_query_set().pending(*args, **kwargs)
And finally the model and admin classes:
class Payment(models.Model):
status = models.CharField(
max_length=25,
choices=((S_PENDING, 'Pending'), ...)
)
objects = managers.PaymentManager()
#admin.register(models.Payment)
class PaymentsAdmin(admin.ModelAdmin):
actions = (
admin_actions.mark_payment_as_sent_action(),
)
Any hint on how can I tell Django to use my queryset when calling an admin action?
Thanks a lot.
As noamk noted, the problem was the method name. Django renamed the get_query_set method to get_queryset.
Now it's working petectly.
class PaymentQuerySet(models.query.QuerySet):
def pending(self):
return self.filter(status=self.model.S_PENDING)
class PaymentManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
return PaymentQuerySet(self.model)
def pending(self):
return self.get_queryset().pending()

How to properly group mixins in Django app?

Initial situation
I have one app, 'devices' with some views:
class DeviceUpdateView(LoginRequiredMixin, UpdateView):
model = Device
form_class = DeviceEditForm
def get_form(self, form_class=None):
form = super(DeviceUpdateView, self).get_form(form_class=None)
form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
return form
class DeviceCreateView(LoginRequiredMixin, CreateView):
model = Device
form_class = DeviceEditForm
def get_initial(self):
initial = super(DeviceCreateView, self).get_initial()
initial['customer_account'] = self.request.user.default_customer_account
return initial
def get_form(self, form_class=None):
form = super(DeviceCreateView, self).get_form(form_class=None)
form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
return form
I have another app ('buildings') vith this view:
class BuildingCreateView(LoginRequiredMixin, UserFormKwargsMixin, CreateView):
model = Building
form_class = BuildingEditModelForm
def get_initial(self):
initial = super(BuildingCreateView, self).get_initial()
initial["customer_account"] = self.request.user.default_customer_account
return initial
DRY Mixin
Now, I want to factorize my code in order to be more "DRY".
I then create this mixin, in my devices/views.py:
class BeaconFilterMixin(object):
def get_form(self, form_class=None):
form = super(BeaconFilterMixin, self).get_form(form_class=None)
form.fields['beacon'].queryset=Beacon.objects.filter(customer_account=self.request.user.default_customer_account)
return form
And my views become:
class DeviceUpdateView(LoginRequiredMixin, BeaconFilterMixin, UpdateView):
model = Device
form_class = DeviceEditForm
class DeviceCreateView(LoginRequiredMixin, BeaconFilterMixin, CreateView):
model = Device
form_class = DeviceEditForm
def get_initial(self):
initial = super(DeviceCreateView, self).get_initial()
initial['customer_account'] = self.request.user.default_customer_account
return initial
Nice and sweet!
Now the question
I want to do exact same thing and create a "InitialCustomerAccountMixin" that could be used by both 'buildings' and 'devices' apps.
The code will be:
class InitialCustomerAccountMixin(object):
def get_initial(self):
initial = super(InitialCustomerAccountMixin, self).get_initial()
initial['customer_account'] = self.request.user.default_customer_account
return initial
The question is: where do I put my mixins code?
For an 'app-scope' mixin, I get that I should put the code in the views.py or in a mixins.py file in the app.
But for a 'multi-app' mixin, I don't know the design principle to follow.
You should follow functional grouping principle (or whatever you call it).
If you have a UI layer in your app, it should have Mixins module (package, namespace or whatever). This module should have categories for all mixins use: Auth, Filter, View,... etc. Each category should contain respected mixins.
This is for single-app mixins.
Mixins, you have to share between your applications should be encapsulated into their own module (or whatever Python reusable packages are called). This module should be private to you, should be called appropriately and should be split into sensible categories.

Django rest framework, use different serializers in the same ModelViewSet

I would like to provide two different serializers and yet be able to benefit from all the facilities of ModelViewSet:
When viewing a list of objects, I would like each object to have an url which redirects to its details and every other relation appear using __unicode __ of the target model;
example:
{
"url": "http://127.0.0.1:8000/database/gruppi/2/",
"nome": "universitari",
"descrizione": "unitn!",
"creatore": "emilio",
"accesso": "CHI",
"membri": [
"emilio",
"michele",
"luisa",
"ivan",
"saverio"
]
}
When viewing the details of an object, I would like to use the default HyperlinkedModelSerializer
example:
{
"url": "http://127.0.0.1:8000/database/gruppi/2/",
"nome": "universitari",
"descrizione": "unitn!",
"creatore": "http://127.0.0.1:8000/database/utenti/3/",
"accesso": "CHI",
"membri": [
"http://127.0.0.1:8000/database/utenti/3/",
"http://127.0.0.1:8000/database/utenti/4/",
"http://127.0.0.1:8000/database/utenti/5/",
"http://127.0.0.1:8000/database/utenti/6/",
"http://127.0.0.1:8000/database/utenti/7/"
]
}
I managed to make all this work as I wish in the following way:
serializers.py
# serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
membri = serializers.RelatedField(many = True)
creatore = serializers.RelatedField(many = False)
class Meta:
model = models.Gruppi
# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Gruppi
views.py
class DualSerializerViewSet(viewsets.ModelViewSet):
"""
ViewSet providing different serializers for list and detail views.
Use list_serializer and detail_serializer to provide them
"""
def list(self, *args, **kwargs):
self.serializer_class = self.list_serializer
return viewsets.ModelViewSet.list(self, *args, **kwargs)
def retrieve(self, *args, **kwargs):
self.serializer_class = self.detail_serializer
return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)
class GruppiViewSet(DualSerializerViewSet):
model = models.Gruppi
list_serializer = serializers.ListaGruppi
detail_serializer = serializers.DettaglioGruppi
# etc.
Basically I detect when the user is requesting a list view or a detailed view and change serializer_class to suit my needs. I am not really satisfied with this code though, it looks like a dirty hack and, most importantly, what if two users request a list and a detail at the same moment?
Is there a better way to achieve this using ModelViewSets or do I have to fall back using GenericAPIView?
EDIT:
Here's how to do it using a custom base ModelViewSet:
class MultiSerializerViewSet(viewsets.ModelViewSet):
serializers = {
'default': None,
}
def get_serializer_class(self):
return self.serializers.get(self.action,
self.serializers['default'])
class GruppiViewSet(MultiSerializerViewSet):
model = models.Gruppi
serializers = {
'list': serializers.ListaGruppi,
'detail': serializers.DettaglioGruppi,
# etc.
}
Override your get_serializer_class method. This method is used in your model mixins to retrieve the proper Serializer class.
Note that there is also a get_serializer method which returns an instance of the correct Serializer
class DualSerializerViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == 'list':
return serializers.ListaGruppi
if self.action == 'retrieve':
return serializers.DettaglioGruppi
return serializers.Default # I dont' know what you want for create/destroy/update.
You may find this mixin useful, it overrides the get_serializer_class method and allows you to declare a dict that maps action and serializer class or fallback to the usual behavior.
class MultiSerializerViewSetMixin(object):
def get_serializer_class(self):
"""
Look for serializer class in self.serializer_action_classes, which
should be a dict mapping action name (key) to serializer class (value),
i.e.:
class MyViewSet(MultiSerializerViewSetMixin, ViewSet):
serializer_class = MyDefaultSerializer
serializer_action_classes = {
'list': MyListSerializer,
'my_action': MyActionSerializer,
}
#action
def my_action:
...
If there's no entry for that action then just fallback to the regular
get_serializer_class lookup: self.serializer_class, DefaultSerializer.
"""
try:
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super(MultiSerializerViewSetMixin, self).get_serializer_class()
This answer is the same as the accepted answer but I prefer to do in this way.
Generic views
get_serializer_class(self):
Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute.
May be overridden to provide dynamic behavior, such as using different serializers for reading and write operations or providing different serializers to the different types of users.
the serializer_class attribute.
class DualSerializerViewSet(viewsets.ModelViewSet):
# mapping serializer into the action
serializer_classes = {
'list': serializers.ListaGruppi,
'retrieve': serializers.DettaglioGruppi,
# ... other actions
}
default_serializer_class = DefaultSerializer # Your default serializer
def get_serializer_class(self):
return self.serializer_classes.get(self.action, self.default_serializer_class)
Regarding providing different serializers, why is nobody going for the approach that checks the HTTP method? It's clearer IMO and requires no extra checks.
def get_serializer_class(self):
if self.request.method == 'POST':
return NewRackItemSerializer
return RackItemSerializer
Credits/source: https://github.com/encode/django-rest-framework/issues/1563#issuecomment-42357718
Based on #gonz and #user2734679 answers I've created this small python package that gives this functionality in form a child class of ModelViewset. Here is how it works.
from drf_custom_viewsets.viewsets.CustomSerializerViewSet
from myapp.serializers import DefaltSerializer, CustomSerializer1, CustomSerializer2
class MyViewSet(CustomSerializerViewSet):
serializer_class = DefaultSerializer
custom_serializer_classes = {
'create': CustomSerializer1,
'update': CustomSerializer2,
}
Just want to addon to existing solutions. If you want a different serializer for your viewset's extra actions (i.e. using #action decorator), you can add kwargs in the decorator like so:
#action(methods=['POST'], serializer_class=YourSpecialSerializer)
def your_extra_action(self, request):
serializer = self.get_serializer(data=request.data)
...
Although pre-defining multiple Serializers in or way or another does seem to be the most obviously documented way, FWIW there is an alternative approach that draws on other documented code and which enables passing arguments to the serializer as it is instantiated. I think it would probably tend to be more worthwhile if you needed to generate logic based on various factors, such as user admin levels, the action being called, perhaps even attributes of the instance.
The first piece of the puzzle is the documentation on dynamically modifying a serializer at the point of instantiation. That documentation doesn't explain how to call this code from a viewset or how to modify the readonly status of fields after they've been initated - but that's not very hard.
The second piece - the get_serializer method is also documented - (just a bit further down the page from get_serializer_class under 'other methods') so it should be safe to rely on (and the source is very simple, which hopefully means less chance of unintended side effects resulting from modification). Check the source under the GenericAPIView (the ModelViewSet - and all the other built in viewset classes it seems - inherit from the GenericAPIView which, defines get_serializer.
Putting the two together you could do something like this:
In a serializers file (for me base_serializers.py):
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Adding this next line to the documented example
read_only_fields = kwargs.pop('read_only_fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
# another bit we're adding to documented example, to take care of readonly fields
if read_only_fields is not None:
for f in read_only_fields:
try:
self.fields[f].read_only = True
exceptKeyError:
#not in fields anyway
pass
Then in your viewset you might do something like this:
class MyViewSet(viewsets.ModelViewSet):
# ...permissions and all that stuff
def get_serializer(self, *args, **kwargs):
# the next line is taken from the source
kwargs['context'] = self.get_serializer_context()
# ... then whatever logic you want for this class e.g:
if self.action == "list":
rofs = ('field_a', 'field_b')
fs = ('field_a', 'field_c')
if self.action == “retrieve”:
rofs = ('field_a', 'field_c’, ‘field_d’)
fs = ('field_a', 'field_b’)
# add all your further elses, elifs, drawing on info re the actions,
# the user, the instance, anything passed to the method to define your read only fields and fields ...
# and finally instantiate the specific class you want (or you could just
# use get_serializer_class if you've defined it).
# Either way the class you're instantiating should inherit from your DynamicFieldsModelSerializer
kwargs['read_only_fields'] = rofs
kwargs['fields'] = fs
return MyDynamicSerializer(*args, **kwargs)
And that should be it! Using MyViewSet should now instantiate your MyDynamicSerializer with the arguments you'd like - and assuming your serializer inherits from your DynamicFieldsModelSerializer, it should know just what to do.
Perhaps its worth mentioning that it can makes special sense if you want to adapt the serializer in some other ways …e.g. to do things like take in a read_only_exceptions list and use it to whitelist rather than blacklist fields (which I tend to do). I also find it useful to set the fields to an empty tuple if its not passed and then just remove the check for None ... and I set my fields definitions on my inheriting Serializers to 'all'. This means no fields that aren't passed when instantiating the serializer survive by accident and I also don't have to compare the serializer invocation with the inheriting serializer class definition to know what's been included...e.g within the init of the DynamicFieldsModelSerializer:
# ....
fields = kwargs.pop('fields', ())
# ...
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
# ....
NB If I just wanted two or three classes that mapped to distinct actions and/or I didn't want any specially dynamic serializer behaviour, I might well use one of the approaches mentioned by others here, but I thought this worth presenting as an alternative, particularly given its other uses.
With all other solutions mentioned, I was unable to find how to instantiate the class using get_serializer_class function and unable to find custom validation function as well. For those who are still lost just like I was and want full implementation please check the answer below.
views.py
from rest_framework.response import Response
from project.models import Project
from project.serializers import ProjectCreateSerializer, ProjectIDGeneratorSerializer
class ProjectViewSet(viewsets.ModelViewSet):
action_serializers = {
'generate_id': ProjectIDGeneratorSerializer,
'create': ProjectCreateSerializer,
}
permission_classes = [IsAuthenticated]
def get_serializer_class(self):
if hasattr(self, 'action_serializers'):
return self.action_serializers.get(self.action, self.serializer_class)
return super(ProjectViewSet, self).get_serializer_class()
# You can create custom function
def generate_id(self, request):
serializer = self.get_serializer_class()(data=request.GET)
serializer.context['user'] = request.user
serializer.is_valid(raise_exception=True)
return Response(serializer.validated_data, status=status.HTTP_200_OK)
def create(self, request, **kwargs):
serializer = self.get_serializer_class()(data=request.data)
serializer.context['user'] = request.user
serializer.is_valid(raise_exception=True)
return Response(serializer.validated_data, status=status.HTTP_200_OK)
serializers.py
import random
from rest_framework import serializers
from project.models import Project
class ProjectIDGeneratorSerializer(serializers.Serializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
pass
projectName = serializers.CharField(write_only=True)
class Meta:
fields = ['projectName']
def validate(self, attrs):
project_name = attrs.get('projectName')
project_id = project_name.replace(' ', '-')
return {'projectID': project_id}
class ProjectCreateSerializer(serializers.Serializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
pass
projectName = serializers.CharField(write_only=True)
projectID = serializers.CharField(write_only=True)
class Meta:
model = Project
fields = ['projectName', 'projectID']
def to_representation(self, instance: Project):
data = dict()
data['projectName'] = instance.name
data['projectID'] = instance.projectID
data['createdAt'] = instance.createdAt
data['updatedAt'] = instance.updatedAt
representation = {
'message': f'Project {instance.name} has been created.',
}
return representation
def validate(self, attrs):
print('attrs', dict(attrs))
project_name = attrs.get('projectName')
project_id = attrs.get('projectID')
if Project.objects.filter(projectID=project_id).first():
raise serializers.ValidationError(f'Project with ID {project_id} already exist')
project = Project.objects.create(projectID=project_id,
name=project_name)
print('user', self.context['user'])
project.user.add(self.context["user"])
project.save()
return self.to_representation(project)
urls.py
from django.urls import path
from .views import ProjectViewSet
urlpatterns = [
path('project/generateID', ProjectViewSet.as_view({'get': 'generate_id'})),
path('project/create', ProjectViewSet.as_view({'post': 'create'})),
]
models.py
# Create your models here.
from django.db import models
from authentication.models import User
class Project(models.Model):
id = models.AutoField(primary_key=True)
projectID = models.CharField(max_length=255, blank=False, db_index=True, null=False)
user = models.ManyToManyField(User)
name = models.CharField(max_length=255, blank=False)
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
You can map your all serializers with the action using a dictionary in class and then get them from "get_serializer_class" method. Here is what I am using to get different serializers in different cases.
class RushesViewSet(viewsets.ModelViewSet):
serializer_class = DetailedRushesSerializer
queryset = Rushes.objects.all().order_by('ingested_on')
permission_classes = (IsAuthenticated,)
filter_backends = (filters.SearchFilter,
django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter)
pagination_class = ShortResultsSetPagination
search_fields = ('title', 'asset_version__title',
'asset_version__video__title')
filter_class = RushesFilter
action_serializer_classes = {
"create": RushesSerializer,
"update": RushesSerializer,
"retrieve": DetailedRushesSerializer,
"list": DetailedRushesSerializer,
"partial_update": RushesSerializer,
}
def get_serializer_context(self):
return {'request': self.request}
def get_serializer_class(self):
try:
return self.action_serializer_classes[self.action]
except (KeyError, AttributeError):
error_logger.error("---Exception occurred---")
return super(RushesViewSet, self).get_serializer_class()

get_readonly_fields in a TabularInline class in Django?

I'm trying to use get_readonly_fields in a TabularInline class in Django:
class ItemInline(admin.TabularInline):
model = Item
extra = 5
def get_readonly_fields(self, request, obj=None):
if obj:
return ['name']
return self.readonly_fields
This code was taken from another StackOverflow question:
Django admin site: prevent fields from being edited?
However, when it's put in a TabularInline class, the new object forms don't render properly. The goal is to make certain fields read only while still allowing data to be entered in new objects. Any ideas for a workaround or different strategy?
Careful - "obj" is not the inline object, it's the parent. That's arguably a bug - see for example this Django ticket
As a workaround to this issue I have associated a form and a Widget to my Inline:
admin.py:
...
class MasterCouponFileInline(admin.TabularInline):
model = MasterCouponFile
form = MasterCouponFileForm
extra = 0
in Django 2.0:
forms.py
from django import forms
from . import models
from feedback.widgets import DisablePopulatedText
class FeedbackCommentForm(forms.ModelForm):
class Meta:
model = models.MasterCouponFile
fields = ('Comment', ....)
widgets = {
'Comment': DisablePopulatedText,
}
in widgets.py
from django import forms
class DisablePopulatedText(forms.TextInput):
def render(self, name, value, attrs=None, renderer=None):
"""Render the widget as an HTML string."""
if value is not None:
# Just return the value, as normal read_only fields do
# Add Hidden Input otherwise the old fields are still required
HiddenInput = forms.HiddenInput()
return format_html("{}\n"+HiddenInput.render(name, value), self.format_value(value))
else:
return super().render(name, value, attrs, renderer)
older Django Versions:
forms.py
....
class MasterCouponFileForm(forms.ModelForm):
class Meta:
model = MasterCouponFile
def __init__(self, *args, **kwargs):
super(MasterCouponFileForm, self).__init__(*args, **kwargs)
self.fields['range'].widget = DisablePopulatedText(self.instance)
self.fields['quantity'].widget = DisablePopulatedText(self.instance)
in widgets.py
...
from django import forms
from django.forms.util import flatatt
from django.utils.encoding import force_text
class DisablePopulatedText(forms.TextInput):
def __init__(self, obj, attrs=None):
self.object = obj
super(DisablePopulatedText, self).__init__(attrs)
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_text(self._format_value(value))
if "__prefix__" not in name and not value:
return format_html('<input{0} disabled />', flatatt(final_attrs))
else:
return format_html('<input{0} />', flatatt(final_attrs))
This is still currently not easily doable due to the fact that obj is the parent model instance not the instance displayed by the inline.
What I did in order to solve this, was to make all the fields, in the inline form, read only and provide a Add/Edit link to a ChangeForm for the inlined model.
Like this
class ChangeFormLinkMixin(object):
def change_form_link(self, instance):
url = reverse('admin:%s_%s_change' % (instance._meta.app_label,
instance._meta.module_name), args=(instance.id,))
# Id == None implies and empty inline object
url = url.replace('None', 'add')
command = _('Add') if url.find('add') > -1 else _('Edit')
return format_html(u'%s' % command, url)
And then in the inline I will have something like this
class ItemInline(ChangeFormLinkMixin, admin.StackedInline):
model = Item
extra = 5
readonly_fields = ['field1',...,'fieldN','change_form_link']
Then in the ChangeForm I'll be able to control the changes the way I want to (I have several states, each of them with a set of editable fields associated).
As others have added, this is a design flaw in django as seen in this Django ticket (thanks Danny W). get_readonly_fields returns the parent object, which is not what we want here.
Since we can't make it readonly, here is my solution to validate it can't be set by the form, using a formset and a clean method:
class ItemInline(admin.TabularInline):
model = Item
formset = ItemInlineFormset
class ItemInlineFormset(forms.models.BaseInlineFormSet):
def clean(self):
super(ItemInlineFormset, self).clean()
for form in self.forms:
if form.instance.some_condition:
form.add_error('some_condition', 'Nope')
You are on the right track. Update self.readonly_fields with a tuple of what fields you want to set as readonly.
class ItemInline(admin.TabularInline):
model = Item
extra = 5
def get_readonly_fields(self, request, obj=None):
# add a tuple of readonly fields
self.readonly_fields += ('field_a', 'field_b')
return self.readonly_fields