У меня есть выпадающий компонент на моем интерфейсе. То, что я пытаюсь сделать, это.
Каждый раз, когда происходит событие onChange, я хочу добавить значение выбранного параметра в качестве роли в моем бэкэнде. Это прекрасно работает в первый раз, когда выбирается значение параметра.
Что я хочу сделать, это увеличить имя роли, если она будет выбрана еще раз. Если я дважды выберу «Разработчик», я хочу, чтобы во второй раз данные публиковались как «Разработчик 1» и т. Д.
Как мне это сделать?
Я гуглял это часами, иЯ еще не понял это. Я попытался создать валидаторы для моих сериализаторов, проверить, существует ли объект, затем увеличивает его на 1 и другими способами.
Модель
class Role(models.Model):
address1 = models.TextField(name="address1", max_length=150, null=True)
address2 = models.TextField(name="address2", max_length=150, null=True)
vat = models.CharField(max_length=100, null=True)
categoryname = models.CharField(max_length = 100)
date_created = models.DateField(null=True)
is_active = models.BooleanField(null=True)
is_passive = models.BooleanField(null=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='roles', on_delete=models.CASCADE)
def get_owner_full_name(self):
return self.owner.get_full_name()
Serializers
from rest_framework import serializers
from .models import Role
from core.serializers import DynamicFieldsModelSerializer, BasicSerializer
from user.serializers import CustomUserSimpleSerializer
class RoleSerializerBasic(DynamicFieldsModelSerializer ,BasicSerializer,):
owner = serializers.ReadOnlyField(source='owner.username') #
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = ('address1', 'address2','vat','categoryname','date_created', 'owner')
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerDepth(DynamicFieldsModelSerializer ,BasicSerializer):
owner = serializers.ReadOnlyField(source='owner.username') #
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = '__all__'
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerInvestor(DynamicFieldsModelSerializer ,BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role # Model to serialize
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0 # How deep we want to serialize fk connections
class RoleSerializerAuditor(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
class RoleSerializerDeveloper(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
class RoleSerializerEducationalInstitution(DynamicFieldsModelSerializer, BasicSerializer):
class Meta(BasicSerializer.Meta):
model = Role
fields = ('address1', 'address2','vat','categoryname','date_created','owner')
depth = 0
import json
from django.views.generic import ListView
from rest_framework import generics, permissions, status
#from django_weasyprint import WeasyTemplateResponseMixin
#Redis
from django.conf import settings
#Own
from .models import Role
from .serializers import RoleSerializerBasic, RoleSerializerDepth, RoleSerializerDeveloper, RoleSerializerAuditor, RoleSerializerInvestor, RoleSerializerEducationalInstitution
from core.permissions import HasGroupPermission, HasObjectPermission
from core.mail import send_mail
from core.views import PBListViewMixin, PBDetailsViewMixin
# Views
class RoleList(PBListViewMixin, generics.ListCreateAPIView):
#permission_classes = (permissions.IsAuthenticated, HasGroupPermission, HasObjectPermission,)
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':100,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'):
return RoleSerializerDepth
return RoleSerializerBasic
def perform_create(self, serializer):
"""Save the post data when creating a new bucketlist."""
serializer.save(owner=self.request.user) # Add
class RoleDetails(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':500,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'):
return RoleSerializerDepth
return RoleSerializerBasic
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class RoleInvestor(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':100,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerInvestor
return RoleSerializerBasic
class RoleAuditor(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerAuditor
return RoleSerializerBasic
class RoleDeveloper(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerDeveloper
return RoleSerializerBasic
class RoleEducator(PBDetailsViewMixin, generics.RetrieveUpdateDestroyAPIView):
model = Role
table_name = "Roles" # For search and filter options (Redis key)
required_groups= {
'GET':['__all__'],
'POST':['__all__'],
}
required_permissions={
'GET':['__all__'],
'POST':['__all__'],
}
DEFAULT_QUERY_SETTINGS={
'pageSize':10,
'current':1,
'sortOrder':[],
'sortField':[],
'visibleFields':['id', 'address1','address2','categoryname','owner','vat','date_created'],
'filters':{}
}
def get_serializer_class(self):
if self.request.method == 'GET' and self.request.user.has_perm('user_view.user'):
return RoleSerializerEducationalInstitution
return RoleSerializerBasic
Мой код реакции
onChange = (e,i) => {
console.log("values", e.target.value+1)
this.props.AddRole(e.target.value);
}
render(){
const roles = [
{ label: "Investor", value:"Investor"},
{ label: "Auditor", value:"Auditor" },
{ label: "Developer", value:"Developer"},
{ label: "Educational Institution", value:"Educational Institution"}
]
return (
<>
<div className="SelectOptionKlasa1">
<Select
name="roleSelect"
options={ roles}
label="Create new role"
onChange={this.onChange}
/>
</div>
</>
)
}
}
export const AddRole = (categoryname, owner) => async dispatch =>{
dispatch({ type: types.ADD_ROLE});
const address = `/roles/`;
const bodyFormData = new FormData();
bodyFormData.set("categoryname", categoryname);
console.log("username ")
apiCon.post( address, bodyFormData)
.then(res => {
dispatch(RoleAddedSuccessfuly(res.data));
console.log("Added role", res.data);
})
.catch(err => {
dispatch(RoleFailToAdd("Role could not be added. "+err));
})
}
Я ожидаю каждый раз, когда я публикую роль из моего внешнего интерфейса, если уже есть роль, созданная с таким именем, новая роль, которая будет создана с тем же именем, но плюс 1. Как Разработчик 1, Аудитор 1. Я получаю имя категории: ["роль с этим именем категории уже существует."], Когда я отправляю запрос на публикацию.