我的前端有下拉菜单组件。我想做的是。
每次发生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。像Developer 1,Auditor 1一样。我将获得categoryname: [“具有该类别名称的角色已经存在。”]我发送帖子请求时。