How can I put a ForeignKey field in alphabetical order? - python

this is my code.
models.py
class Preventivo(models.Model):
prestazione1 = models.ForeignKey('Prestazione',on_delete=models.CASCADE, related_name="prestazione1")
form.py
class PreventivoForm(forms.ModelForm):
class Meta:
model = Preventivo
fields = ['cliente','prestazione1']

You can redefine the field to give it a custom queryset that's ordered how you want.
class PreventivoForm(forms.ModelForm):
prestazione1 = forms.ModelChoiceField(queryset=Prestazione.objects.order_by('name'))
class Meta:
model = Preventivo
fields = ['cliente','prestazione1']

You can change it in the __init__ method of your ModelForm.
This comes in handy if you need to pass other information to the Form, which you can then read from the kwargs.
class PreventivoForm(forms.ModelForm):
class Meta:
model = Preventivo
fields = ['cliente','prestazione1']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['prestazione1'].queryset = Preventivo.objects.order_by('<FIELDNAME>')

Related

Filter queryset for nested serializer in django rest framework

Here is my view:
class SectorListAPI(generics.ListAPIView):
queryset = SectorModel.objects.all()
serializer_class = SectorSerializer
Here is my serializers:
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = GroupProfile
fields = ('title','slug',)
class DepartmentSerializer(serializers.ModelSerializer):
organizations = OrganizationSerializer(many=True, read_only=True)
class Meta:
model = DepartmentModel
fields = ('title', 'organizations',)
class SectorSerializer(serializers.ModelSerializer):
# title = serializers.CharField()
departments = DepartmentSerializer(many=True, read_only=True)
class Meta:
model = SectorModel
fields = ('title','departments',)
Look, here 'SectorSerializer' is parent 'DepartmentSerializer' is children and 'OrganizationSerializer' is grand children serializer. Now in my view I can easily filter my queryset for 'SectorModel'. But how can i filter on 'GroupProfile' model.
You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.
You can do so by filtering based on the value of request.user.
For example:
from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
def get_queryset(self):
"""
This view should return a list of all the purchases
for the currently authenticated user.
"""
user = self.request.user
return Purchase.objects.filter(purchaser=user)
EDIT
You can subclass the ListSerializer and overwrite the to_representation method.
By default the to_representation method calls data.all() on the nested queryset. So you effectively need to make data = data.filter(**your_filters) before the method is called. Then you need to add your subclassed ListSerializer as the list_serializer_class on the meta of the nested serializer.
1- subclass ListSerializer, overwriting to_representation and then calling super
2- Add subclassed ListSerializer as the meta list_serializer_class on the nested Serializer.
Code relevant to yours:
class FilteredListSerializer(serializers.ListSerializer):
def to_representation(self, data):
data = data.filter(user=self.request.user, edition__hide=False)
return super(FilteredListSerializer, self).to_representation(data)
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class = FilteredListSerializer
model = GroupProfile
fields = ('title','slug',)
class DepartmentSerializer(serializers.ModelSerializer):
organizations = OrganizationSerializer(many=True, read_only=True)
class Meta:
model = DepartmentModel
fields = ('title', 'organizations',)
class SectorSerializer(serializers.ModelSerializer):
# title = serializers.CharField()
departments = DepartmentSerializer(many=True, read_only=True)
class Meta:
model = SectorModel
fields = ('title','departments',)
Thanks to #ans2human for the inspiration behind this answer.
Here's a new approach that is working great for me. I have several Models with is_active = BooleanField(...) that I need to filter out in nested relationships.
NOTE: this solution does not filter out results on non-list fields. for that, you should look to the primary queryset on your View
The core of the work is done by overloading the to_representation() function on a custom ListSerializer, and the many_init on an accompanying custom ModelSerializer:
class FilteredListSerializer(serializers.ListSerializer):
filter_params:dict
def __init__(self, *args, filter_params:dict={"is_active":True}, **kwargs):
super().__init__(*args, **kwargs)
self.filter_params = filter_params
def set_filter(self, **kwargs):
self.filter_params = kwargs
def to_representation(self, data):
data = data.filter(**self.filter_params)
return super().to_representation(data)
class FilteredModelSerializer(serializers.ModelSerializer):
LIST_SERIALIZER_KWARGS = serializers.LIST_SERIALIZER_KWARGS + ("filter_params",)
LIST_ONLY_KWARGS = ('allow_empty', 'filter_params')
#classmethod
def many_init(cls, *args, **kwargs):
list_kwargs = dict()
for arg in cls.LIST_ONLY_KWARGS:
value = kwargs.pop(arg, None)
if value is not None:
list_kwargs[arg] = value
child_serializer = cls(*args, **kwargs, **({"read_only":True} if "read_only" not in kwargs else dict()))
list_kwargs['child'] = child_serializer
list_kwargs.update({
key: value for key, value in kwargs.items()
if key in cls.LIST_SERIALIZER_KWARGS
})
meta = getattr(cls, 'Meta', None)
list_serializer_class = getattr(meta, 'list_serializer_class', FilteredListSerializer)
return list_serializer_class(*args, **list_kwargs)
Then, your custom ModelSerializer for whatever view would instead just extend FilteredModelSerializer instead.
class ChildSerializer(FilteredModelSerializer):
is_active = BooleanField() # not strictly necessary, just for visibilty
... # the rest of your serializer
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True)
...# the rest of your parent serializer
Now, the children field on the ParentSerializer will filter for is_active = True.
If you have a custom query that you wanted to apply, you can do so by providing a dict of filter params in the standard queryset format:
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True, filter_params={"my_field":my_value, "my_datetime__gte": timezone.now()})
...# the rest of your parent serializer
Alternatively, one could also utilize the set_filter(...) method on the FilteredListSerializer after instantiating the field, like so. This will yield a more familiar format to the original QuerySet.filter(...) style:
class ParentSerializer(serializers.ModelSerializer):
children = ChildSerializer(many=True)
children.set_filter(my_field=my_value, my_datetime__gte=timezone.now())
...# the rest of your parent serializer

django rest framework abstract class serializer

I have some models like these:
class TypeBase(models.Model):
name = models.CharField(max_length=20)
class Meta:
abstract=True
class PersonType(TypeBase):
pass
class CompanyType(TypeBase):
pass
Having this, I want to create just one serializer that holds all these field types (serialization, deserialization, update and save).
To be more specific, I want only one serializer (TypeBaseSerializer) that print the Dropdown on the UI, serialize the json response, deserialize it on post and save it for all my based types.
Something like this:
class TypeBaseSerializer(serializers.Serializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
Is it possible?
I think the following approach is more cleaner. You can set "abstract" field to true for the base serializer and add your common logic for all child serializers.
class TypeBaseSerializer(serializers.ModelSerializer):
class Meta:
model = TypeBase
fields = ('id', 'name')
abstract = True
def func(...):
# ... some logic
And then create child serializers and use them for data manipulation.
class PersonTypeSerializer(TypeBaseSerializer):
class Meta:
model = PersonType
fields = ('id', 'name')
class CompanyTypeSerializer(TypeBaseSerializer):
class Meta:
model = CompanyType
fields = ('id', 'name')
Now you can use the both of these serializers normally for every model.
But if you really want to have one serializers for both the models, then create a container model and a serializer for him too. That is much cleaner :)
You can't use a ModelSerializer with an abstract base model.
From restframework.serializers:
if model_meta.is_abstract_model(self.Meta.model):
raise ValueError(
'Cannot use ModelSerializer with Abstract Models.'
)
I wrote a serializer_factory function for a similar problem:
from collections import OrderedDict
from restframework.serializers import ModelSerializer
def serializer_factory(mdl, fields=None, **kwargss):
""" Generalized serializer factory to increase DRYness of code.
:param mdl: The model class that should be instanciated
:param fields: the fields that should be exclusively present on the serializer
:param kwargss: optional additional field specifications
:return: An awesome serializer
"""
def _get_declared_fields(attrs):
fields = [(field_name, attrs.pop(field_name))
for field_name, obj in list(attrs.items())
if isinstance(obj, Field)]
fields.sort(key=lambda x: x[1]._creation_counter)
return OrderedDict(fields)
# Create an object that will look like a base serializer
class Base(object):
pass
Base._declared_fields = _get_declared_fields(kwargss)
class MySerializer(Base, ModelSerializer):
class Meta:
model = mdl
if fields:
setattr(Meta, "fields", fields)
return MySerializer
You can then use the factory to produce serializers as needed:
def typebase_serializer_factory(mdl):
myserializer = serializer_factory(
mdl,fields=["id","name"],
#owner=HiddenField(default=CurrentUserDefault()),#Optional additional configuration for subclasses
)
return myserializer
Now instanciate different subclass serializers:
persontypeserializer = typebase_serializer_factory(PersonType)
companytypeserializer = typebase_serializer_factory(CompanyType)
As already mentioned in Sebastian Wozny's answer, you can't use a ModelSerializer with an abstract base model.
Also, there is nothing such as an abstract Serializer, as some other answers have suggested. So setting abstract = True on the Meta class of a serializer will not work.
However you need not use use a ModelSerializer as your base/parent serializer. You can use a Serializer and then take advantage of Django's multiple inheritance. Here is how it works:
class TypeBaseSerializer(serializers.Serializer):
# Need to re-declare fields since this is not a ModelSerializer
name = serializers.CharField()
id = serializers.CharField()
class Meta:
fields = ['id', 'name']
def someFunction(self):
#... will be available on child classes ...
pass
class PersonTypeSerializer(TypeBaseSerializer, serializers.ModelSerializer):
class Meta:
model = PersonType
fields = TypeBaseSerializer.Meta.fields + ['another_field']
class CompanyTypeSerializer(TypeBaseSerializer, serializers.ModelSerializer):
class Meta:
model = CompanyType
fields = TypeBaseSerializer.Meta.fields + ['some_other_field']
So now since the fields name and id are declared on the parent class (TypeBaseSerializer), they will be available on PersonTypeSerializer and since this is a child class of ModelSerializer those fields will be populated from the model instance.
You can also use SerializerMethodField on the TypeBaseSerializer, even though it is not a ModelSerializer.
class TypeBaseSerializer(serializers.Serializer):
# you will have to re-declare fields here since this is not a ModelSerializer
name = serializers.CharField()
id = serializers.CharField()
other_field = serializers.SerializerMethodField()
class Meta:
fields = ['id', 'name', 'other_field']
def get_other_field(self, instance):
# will be available on child classes, which are children of ModelSerializers
return instance.other_field
Just iterating a bit over #adki's answer:
it is possible to skip model for TypeBaseSerializer;
derived serializers can refer to TypeBaseSerializer.Meta, so you would change them in a single place.
class TypeBaseSerializer(serializers.Serializer):
class Meta:
fields = ('id', 'name', 'created')
abstract = True
def func(...):
# ... some logic
class PersonTypeSerializer(TypeBaseSerializer):
class Meta:
model = PersonType
fields = TypeBaseSerializer.Meta.fields + ('age', 'date_of_birth')
class CompanyTypeSerializer(TypeBaseSerializer):
class Meta:
model = CompanyType
fields = TypeBaseSerializer.Meta.fields

Django - replace form widget for fields in list

I'm trying to change the widget to fields in a form which have a string in the name, I'm trying to do something like the following:
class CI_tableForm(ModelForm):
class Meta:
model = CI_table
fields = report_query_values
for field in report_query_values:
if "_id" in field:
field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
Not sure if it's possible or not.
At the moment it doesn't error, but doesn't change the widget either.
Thanks,
Isaac
You should do it in the __init__ constructor:
class CI_tableForm(ModelForm):
class Meta:
model = CI_table
fields = report_query_values
def __init__(self, *args, **kwargs):
super(CI_tableForm, self).__init__(*args, **kwargs)
for field in report_query_values:
if "_id" in field:
choices = self.fields[field].widget.choices
self.fields[field].widget = forms.CheckboxSelectMultiple(
choices=choices)

Setting 'required=True' for ModelForms that have been overridden

Say I have to override a ModelForm (in forms.py) to set labels or widgets differently. i.e:
class SomeForm(ModelForm):
def __init__(self,*args,**kwargs):
super(someForm, self).__init__(*args, **kwargs)
self.fields['someVal'].label = ...
self.fields['someVal'].widget = ...
How do I then set required=True?
I know I can do this before the __init__ like so:
class SomeForm(ModelForm):
someVal = CharField(required=True) # << here
def __init__(self,*args,**kwargs):
super(someForm, self).__init__(*args, **kwargs)
self.fields['someVal'].label = ...
self.fields['someVal'].widget = ...
But I'm doing some dynamic stuff and I'd like to set the required in the __init__
self.fields['someVal'].required = True
yes, it's just as simple as this :) you have the same attributes available to the Class in your fields dictionary
You need to override the fields in the form. Just use the same field names as in the model:
class SomeForm(forms.ModelForm):
field_a = forms.CharField(
'My new label', max_length=30, required=True) # << here
def __init__(self,*args,**kwargs):
super(someForm, self).__init__(*args, **kwargs)
class Meta:
model = MyModel
Why this approach?
I think overriding the fields directly by defining a new field is a good way if you want to override many attributes e.g. required, label, widget

how to show a django ModelForm field as uneditable

taking my initial lessons with django ModelForm ,I wanted to give the user ,ability to edit an entry in a blog.The BlogEntry has a date,postedTime, title and content.I want to show the user an editform which shows all these fields,but with only title and content as editable. The date and postedTime should be shown as uneditable.
class BlogEntry(models.Model):
title = models.CharField(unique=True,max_length=50)
description = models.TextField(blank=True)
date = models.DateField(default=datetime.date.today)
postedTime = models.TimeField(null=True)
...
For adding an entry ,I use a ModelForm in the normal way..
class BlogEntryAddForm(ModelForm):
class Meta:
model = BlogEntry
...
But how do I create the edit form?I want it to show the date,postedTime as uneditable (but still show them on the form) and let the user edit the title and description.
if I use,exclude in class Meta for date and postedTime,that will cause them not to appear on the form.So,how can I show them as uneditable?
class BlogEntryEditForm(ModelForm):
class Meta:
model = BlogEntry
...?...
In the form object, declare the attribute of the field as readonly:
form.fields['field'].widget.attrs['readonly'] = True
Is date field represent a date when the entry first created or when it was modified last time? If first then use auto_now_add option else use auto_now. That is:
date = models.DateField(auto_now_add=True)
will set date to now when entry will be created.
auto_now_add makes field uneditable. For other cases use editable option to make any field uneditable. For example
postedDate = models.TimeField(null=True, editable=False)
Also, likely you will add posted boolean field to Entry model, so it is convinient to set auto_now on postedDate. It will set postedDate to now every time you modify a Entry including one when you set posted to True.
I implemented it this way: https://djangosnippets.org/snippets/10514/
this implementation uses the data of model instance for all read-only fields and not the data obtained while processing the form
below the same code but using his example
from __future__ import unicode_literals
from django.utils import six
from django.utils.encoding import force_str
__all__ = (
'ReadOnlyFieldsMixin',
'new_readonly_form_class'
)
class ReadOnlyFieldsMixin(object):
"""Usage:
class MyFormAllFieldsReadOnly(ReadOnlyFieldsMixin, forms.Form):
...
class MyFormSelectedFieldsReadOnly(ReadOnlyFieldsMixin, forms.Form):
readonly_fields = ('field1', 'field2')
...
"""
readonly_fields = ()
def __init__(self, *args, **kwargs):
super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
self.define_readonly_fields(self.fields)
def clean(self):
cleaned_data = super(ReadOnlyFieldsMixin, self).clean()
for field_name, field in six.iteritems(self.fields):
if self._must_be_readonly(field_name):
cleaned_data[field_name] = getattr(self.instance, field_name)
return cleaned_data
def define_readonly_fields(self, field_list):
fields = [field for field_name, field in six.iteritems(field_list)
if self._must_be_readonly(field_name)]
map(lambda field: self._set_readonly(field), fields)
def _all_fields(self):
return not bool(self.readonly_fields)
def _set_readonly(self, field):
field.widget.attrs['disabled'] = 'true'
field.required = False
def _must_be_readonly(self, field_name):
return field_name in self.readonly_fields or self._all_fields()
def new_readonly_form_class(form_class, readonly_fields=()):
name = force_str("ReadOnly{}".format(form_class.__name__))
class_fields = {'readonly_fields': readonly_fields}
return type(name, (ReadOnlyFieldsMixin, form_class), class_fields)
Usage:
class BlogEntry(models.Model):
title = models.CharField(unique=True,max_length=50)
description = models.TextField(blank=True)
date = models.DateField(default=datetime.date.today)
postedTime = models.TimeField(null=True)
# all fields are readonly
class BlogEntryReadOnlyForm(ReadOnlyFieldsMixin, forms.ModelForm):
class Meta:
model = BlogEntry
# selected fields are readonly
class BlogEntryReadOnlyForm2(ReadOnlyFieldsMixin, forms.ModelForm):
readonly_fields = ('date', 'postedTime')
class Meta:
model = BlogEntry
or use the function
class BlogEntryForm(forms.ModelForm):
class Meta:
model = BlogEntry
BlogEntryFormReadOnlyForm = new_readonly_form_class(BlogEntryForm, readonly_fields=('description', ))
This will prevent any user from hacking the request:
self.fields['is_admin'].disabled = True
Custom form example:
class MemberShipInlineForm(forms.ModelForm):
is_admin = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
super(MemberShipInlineForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs and kwargs['instance'].is_group_creator:
self.fields['is_admin'].disabled = True
class Meta:
model = MemberShip
fields = '__all__'
From the documentation,
class BlogEntryEditForm(ModelForm):
class Meta:
model = BlogEntry
readonly_fields = ['date','postedTime']

Categories