Hii I am new to django rest framework i am able to perform put delete and get operations but unable to perform post operations
models.py
JavaScript
x
10
10
1
class User(auth.models.User, auth.models.PermissionsMixin):
2
def __str__(self):
3
return "@{}".format(self.username)
4
class User_log(models.Model):
5
user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE,related_name='user_logs')
6
fullname=models.CharField(max_length=255)
7
fb_login=models.BooleanField(default=False)
8
def __str__(self):
9
return self.fullname
10
serializers.py
JavaScript
1
21
21
1
class userSerializers(serializers.ModelSerializer):
2
password1=serializers.CharField(source="user.password1",write_only=True)
3
password2=serializers.CharField(source="user.password2",write_only=True)
4
fullname=serializers.CharField(source='user_logs.fullname')
5
fb=serializers.BooleanField(source='user_logs.fb_login')
6
class Meta:
7
model = User
8
fields=('id','username','email','password1','password2','fullname','fb')
9
related_fields = ['user_logs']
10
def update(self, instance, validated_data):
11
# Handle related objects
12
for related_obj_name in self.Meta.related_fields:
13
data = validated_data.pop(related_obj_name)
14
related_instance = getattr(instance, related_obj_name)
15
16
# Same as default update implementation
17
for attr_name, value in data.items():
18
setattr(related_instance, attr_name, value)
19
related_instance.save()
20
return super(userSerializers,self).update(instance, validated_data)
21
urls.py
JavaScript
1
35
35
1
from django.urls import path,include
2
from django.contrib.auth import views as auth_views
3
from . import views
4
from rest_framework import routers
5
router=routers.DefaultRouter()
6
router.register('accounts',views.Userview,basename='user')
7
app_name = 'accounts'
8
9
urlpatterns = [
10
path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'),
11
path('logout/', auth_views.LogoutView.as_view(), name="logout"),
12
path('signup/', views.SignUp.as_view(), name="signup"),
13
path('password-reset/',
14
auth_views.PasswordResetView.as_view(
15
template_name='accounts/password_reset_email.html'
16
),
17
name='password_reset'),
18
path('password-reset/done/',
19
auth_views.PasswordResetDoneView.as_view(
20
template_name='accounts/password_reset_done.html'
21
),
22
name='password_reset_done'),
23
path('password-reset-confirm/<uidb64>/<token>/',
24
auth_views.PasswordResetConfirmView.as_view(
25
template_name='accounts/password_reset_confirm.html'
26
),
27
name='password_reset_confirm'),
28
path('password-reset-complete/',
29
auth_views.PasswordResetCompleteView.as_view(
30
template_name='accounts/password_reset_complete.html'
31
),
32
name='password_reset_complete'),
33
path('',include(router.urls)),
34
]
35
views.py
JavaScript
1
11
11
1
class Userview(viewsets.ModelViewSet):
2
def get_serializer_class(self):
3
return userSerializers
4
def get_queryset(self):
5
return User.objects.all()
6
def list(self,request):
7
queryset = User.objects.all()
8
serializer=userSerializers(queryset,many=True)
9
if serializer.is_valid:
10
return Response(serializer.data)
11
this is the json format when i perform get request
JavaScript
1
10
10
1
[
2
{
3
"id": 1,
4
"username": "karm",
5
"email": "karm@gmail.com",
6
"fullname": "ss",
7
"fb": false
8
}
9
]
10
As mentioned earliew whenever i perform put delete or get its working but its not a case with post the error i get is this:
JavaScript
1
2
1
AssertionError at /accounts/accounts/
2
The .create()
method does not support writable dotted-source fields by default.
Write an explicit .create()
method for serializer accounts.serializers.userSerializers
, or set read_only=True
on dotted-source serializer fields.
Advertisement
Answer
Two points to consider here:
- DRF Serializers do not support
write_only
. Instead, useextra_kwargs
in the serializer’sMeta
block. - Write a
create
method in your serializer. Rough example below.
See this from the docs for more information about write-only fields in DRF serializers.
JavaScript
1
24
24
1
class userSerializers(serializers.ModelSerializer):
2
password1=serializers.CharField(source="user.password1")
3
password2=serializers.CharField(source="user.password2")
4
fullname=serializers.CharField(source='user_logs.fullname')
5
fb=serializers.BooleanField(source='user_logs.fb_login')
6
class Meta:
7
model = User
8
fields
9
fields=['id','username','email','password1','password2','fullname','fb']
10
related_fields = ['user_logs']
11
extra_kwargs = {
12
'password1': {'write_only': True},
13
'password2': {'write_only': True},
14
}
15
16
def create(self, validated_data): // adjust to fit your actual User model
17
user = User(
18
email=validated_data['email'],
19
username=validated_data['username']
20
)
21
user.set_password(validated_data['password'])
22
user.save()
23
return user
24