I am using a custom User model with an user profile using a OneToOneField
with this structure :
email
password
profile : {
username
avatar
}
It works pretty good for mobile because I just basically send json back and forth, but it's a problem whenever I am using my API with a website because there is no way in html to send json-like data, hence I can't fill the "profile" field without using ajax.
I would prefer to have the possibility to use plain html forms and to use javascript only for client validation and animation not using it for critic functionality such as registration.
I can also use the following structure and then reconstruct a dictionary for the profile server-side but I do feel that's it's not generic enough.
email
password
username
avatar
UserSerializer.py
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
profile = ProfileSerializer(required=True)
class Meta:
model = get_user_model()
fields = ('id', 'email', 'password', 'date_joined', 'profile')
def create(self, validated_data):
#profile_data = validated_data.pop('profile')
password = validated_data.pop('password')
user = get_user_model().objects.create_user(**validated_data)
user.set_password(password)
#user.save()
print(user)
#print(profile_data
ProfileSerializer.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('username',)
So no matter if I am using json or form data, obviously it's waiting for a profile (object) data. I would like to be able to do it using html form.
Any idea how I should approach this ?
If I correctly understood your problem, you may find the Django rest framework useful for this.
The django rest framework have Views that can handle both json and form data and feed them in the same validation mechanism. It basically uses the Content-Type header to choose a parser for the incoming data (more details here). Maybe you may look at what they did or use the library directly.
Hope this helps.