What is the preferred way to declare a form in django? - django-forms

What is the preferred way to declare a form in django? And why 1 way verse the other way?
I've seen this:
class MyForm(forms.ModelForm):
name = forms.CharField(label='My Name', help_text='My help text.')
class Meta:
model = MyModel
fields = ['name']
And I’ve seen this:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name']
labels = {'name': 'My Name'}
help_texts= {'name': 'My help text'}

Related

How to have an object's json inside inside another using Django Rest

I have 2 models:
class User(AbstractUser):
pass
class Post(models.Model):
likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts')
Post model has a manytomany field to User model. I serialize them separately using rest like this:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = '__all__'
Post model's json, displays the user object's id in 'likers': 'likers': 1. Is there a way to send the user's json instead of it's id? Something like:
{
'likers': [
'1':
'username': foo
]
}
You can use the UserSerializer for the likers:
class PostSerializer(serializers.ModelSerializer):
likers = UserSerializer(many=True)
class Meta:
model = Post
fields = '__all__'

Filter data on related object in Django Rest Framework

I have next ModelSerializers.
I need the statistics data display at 6 days range by default (see date field in StatisticSerializer). User can to change this date range (from frontend get two parameters: start_date and end_date, which not is in Models and Serializers.
How can I make this functional?
serializers
class StatisticSerializer(serializers.ModelSerializer):
class Meta:
model = Statistic
fields = ['date', 'clicks', 'page_views']
class UserStatisticSerializer(serializers.ModelSerializer):
statistics = StatisticSerializer(many=True)
class Meta:
model = User
fields = [
'first_name', 'last_name', 'gender', 'ip_address', 'statistics',
]
views
class UserStatisticApiView(RetrieveAPIView):
serializer_class = UserStatisticSerializer
queryset = User.objects.all()
you can use SerializerMethodField(), docs enter link description here
there just some Pseudocode
class StatisticSerializer(serializers.ModelSerializer):
class Meta:
model = Statistic
fields = ['date', 'clicks', 'page_views']
class UserStatisticSerializer(serializers.ModelSerializer):
filtered_statistc = serializers.SerializerMethodField()
class Meta:
model = User
fields = [
'first_name', 'last_name', 'gender', 'ip_address', 'filtered_statistc',
]
def get_filtered_statistc(self,obj):
result = Statistic.objects.filter('filter there by your params')
serialized_result = StatisticSerializer(data=result, many=True)
return serialized_result

How to show details of a model that is related with other one?

I need that when the URL for example, localhost:8000/apirest/customers
Customers is a table that is asigned a table Role and I need to show all fields of Role
class Customer(models.Model):
Id = models.AutoField(primary_key=True)
Name = models.CharField(max_length=60)
Address = models.CharField(max_length=60)
Phone = models.CharField(max_length=60)
Role = models.ForeignKey(Role, on_delete=models.CASCADE)
class Role(models.Model):
Id = models.AutoField(primary_key=True)
Description = models.CharField(max_length=60)
Premium = models.BooleanField()
This is only an example, what I need that the Json show something like this
{
"Id":1,
"Name":"Jhon Carter",
"Adress": "Lombard Street"
"Phone": "25 56592552",
"Role":{
"Id":1,
"Description":"Description 1"
"Premium": true
}
}
Welcome to SO Jorge.
First of all does your models compiles successfully? because in this line:
Role = models.ForeignKey(Role, on_delete=models.CASCADE)
I get Undefined Role which is because Role definition is in the next lines. So I changed the model definitions to this:
class Customer(models.Model):
class MyRole(models.Model):
Id = models.AutoField(primary_key=True)
Description = models.CharField(max_length=60)
Premium = models.BooleanField()
Id = models.AutoField(primary_key=True)
Name = models.CharField(max_length=60)
Address = models.CharField(max_length=60)
Phone = models.CharField(max_length=60)
Role = models.ForeignKey(MyRole, on_delete=models.CASCADE)
What you want to do is serializing relations which for your case would be something like this:
from rest_framework import serializers
from core.models import Customer
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = Customer.MyRole
fields = ['Id', 'Description', 'Premium']
class CustomerSerializer(serializers.ModelSerializer):
Role = RoleSerializer(many=False, read_only=True)
class Meta:
model = Customer
fields = ['Id', 'Name', 'Address', 'Phone', 'Role']

How to get the name of a foreign key in Django rest framework

Get the foreign key value of category instead of id when fetching data from pet Model with Django Rest Framework. I am not sure where to put the Slug Related Field.
class PetSerializer(serializers.ModelSerializer):
selected_category = serializers.SlugRelatedField(slug_field='selected_category',queryset=categoryType.objects.all())
class Meta:
model = pet
fields = '__all__'
Model
class pet(models.Model):
title = models.CharField(max_length=50)
category = models.ForeignKey(
"categoryType", on_delete=models.CASCADE, null=True, related_name='selected_category')
class categoryType(models.Model):
categoryName = models.CharField(max_length=50)
Serializer
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = pet
fields = '__all__'
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = categoryType
fields = '__all__'
What i get if i do a get request
{
"id": 1,
"title": "dog",
"category": 2
},
what i want to get
{
"id": 1,
"title": "dog",
"category": "Pet"
},
I believe two way you can achieve this.
First Possible Solution
You need to overwrite the __str__() method of categoryType and response your desire model_str() response, in this case which is categoryName name.
class categoryType(models.Model):
categoryName = models.CharField(max_length=50)
def __str__(self):
return self.categoryName
related link
Second Possible Solution
Another possible solution is to use serailizerMethodField and return your desire response for category field.
class PetSerializer(serializers.ModelSerializer):
category = serializers.SerializerMethodField()
class Meta:
model = pet
fields = ('id', 'title', 'category')
def get_category(self, obj):
return obj.category.categoryName

How do I return a count of linked objects in a GenericRelation field in a DRF Serializer?

There are a number of questions about serializing GenericRelations in Django Rest Framework however I have a use case where I want to simply return the count of objects in the GenericRelation field only and not serialize them. The documentation and existing questions I can find do not cover this.
I thought it might be as simple as returning the len(value) in a custom Serializer, however that produces the following throw:
object of type 'GenericRelatedObjectManager' has no len()
My failed attempt:
class ObjectCountSerializer(serializers.RelatedField):
"""
Return the count of related objects.
"""
def to_representation(self, value):
return len(value)
class PostListSerializer(serializers.ModelSerializer):
"""
Main serializers for the writings module
"""
author = MemberListSerializer(many=False, read_only=True)
comments = ObjectCountSerializer(read_only=True)
class Meta:
model = Post
fields = (
'id',
'slug',
'url',
'title',
'description',
'created',
'edited',
'author',
'comments'
)
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
How do I simply return the count of objects in the relation?
I would say a SerializerMethodField would solve this, e.g.
class PostListSerializer(serializers.ModelSerializer):
"""
Main serializers for the writings module
"""
author = MemberListSerializer(many=False, read_only=True)
comments = serializers.SerializerMethodField()
def get_comments(self, instance):
return instance.comments.count()
class Meta:
model = Post
fields = (
'id',
'slug',
'url',
'title',
'description',
'created',
'edited',
'author',
'comments'
)
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
SerializerMethodField is a read-only field that returns the result of a method, generally named get_<field_name>.

Resources