9π
β
If you make a model field blank, you can set a default value that will be filled in if you donβt supply a value on the POST
:
class Foo(models.Model):
bar = models.IntegerField(blank=True, default=42)
#^^^^^^^^^^ ^^^^^^^^^^
Then, when you POST
use {}
as the data
π€Ross Rogers
21π
age = serializers.IntegerField(default=12, initial=12)
initial to pre populate html form.
See the docs
π€Satyajeet
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
- [Django]-Does django with mongodb make migrations a thing of the past?
- [Django]-Django: show raw html (from database) as html, not rendered
17π
do you want to set in serializers?
class PersonSerializer(serializers.ModelSerializer):
age = serializers.SerializerMethodField()
def get_age(self, obj):
return getattr(obj, 'age', 12)
class Meta:
model = Person
field = ('id', 'name', 'age')
π€third9
- [Django]-Django β how to unit test a post request using request.FILES
- [Django]-Difference between reverse() and reverse_lazy() in Django
- [Django]-How to chain Django querysets preserving individual order
15π
As you said, you donβt have a model
1.serializer.py
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField()
age = serializers.IntegerField(default=12) #if key age is missing, value of age become 12
def validate(self,data):
#other wise you can set default value of age here,
if data.get('age',None)==None: #this conditon will be true only when age = serializer.IntergerField(required=False)
data['age']=12
return data
views.py
serializer = UserSerializer(data={'id': 1, 'name': 'cc', 'age': 14})
serializer.is_valid()
# True
serializer.validated_data
# {'id': 1, 'name': 'cc', 'age': 14}
or if you miss specifying age in views.py
serializer = UserSerializer(data={'id': 1, 'name': 'cc'})
serializer.is_valid()
# True
serializer.validated_data
# {'id': 1, 'name': 'cc', 'age': 12}
Hope this help someone π
π€vijay
- [Django]-Django β use template tag and 'with'?
- [Django]-In a Django QuerySet, how to filter for "not exists" in a many-to-one relationship
- [Django]-PyCharm code inspection complains template file not found, how to fix?
Source:stackexchange.com