Viewset create custom assign value in Django Rest Framework

2024/11/17 10:46:40

Would like to set a CustomUser's username by using the input email, but where to do the custom assigning, in view? At the same time it receiving a file as well.

Models.py

class CustomUser(AbstractUser):avatar = models.ImageField(max_length=None, upload_to='avatar', blank=True)

Serializers.py

class CustomUserSerializer(serializers.ModelSerializer):class Meta:model = CustomUserfields = ('id', 'first_name', 'last_name', 'email', 'password', 'avatar', 'groups')

Views.py

class CustomUserViewSet(viewsets.ModelViewSet):queryset = CustomUser.objects.all()serializer_class = CustomUserSerializer

thank you in advance.

Answer

What @Anzel said would work but if you want to do it in django-rest-framework you could override the create method of your CustomUserSerializer. Like:

class CustomUserSerializer(serializers.ModelSerializer):groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)def create(self, validated_data):user = CustomUser.objects.create_user(username    =validated_data['email'], # HEREemail       =validated_data['email'],password    =validated_data['password'],first_name  =validated_data['first_name'], last_name   =validated_data['last_name'],avatar      =validated_data['avatar'],)user.groups = validated_data['groups']return userclass Meta:model = CustomUserfields = ('id', 'first_name', 'last_name', 'email', 'password', 'avatar', 'groups')
https://en.xdnf.cn/q/71557.html

Related Q&A

Remove a relation many-to-many (association object) on Sqlalchemy

Im stuck with a SqlAlchemy problem.I just want to delete an relation. This relation is made by an association object.modelsclass User(db.Model, UserMixin):id = db.Column(db.Integer, pr…

Spark Dataframes: Skewed Partition after Join

Ive two dataframes, df1 with 22 million records and df2 with 2 million records. Im doing the right join on email_address as a key. test_join = df2.join(df1, "email_address", how = right).cach…

Caught TypeError while rendering: __init__() got an unexpected keyword argument use_decimal

While running the program i am getting the following error messageCaught TypeError while rendering: __init__() got an unexpected keyword argument use_decimalHere is my code i am using jquery 1.6.4 d…

How to get chunks of elements from a queue?

I have a queue from which I need to get chunks of 10 entries and put them in a list, which is then processed further. The code below works (the "processed further" is, in the example, just pr…

Receiving commandline input while listening for connections in Python

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this…

Passing a parameter through AJAX URL with Django

Below is my code. n logs correctly in the console, and everything works perfectly if I manually enter the value for n into url: {% url "delete_photo" iddy=2%}. Alas, when I try to use n as a …

WARNING: toctree contains reference to nonexisting document error with Sphinx

I used the sphinx-quickstart to set everything up. I used doc/ for the documentation root location. The folder containing my package is setup as: myfolder/doc/mypackage/__init__.pymoprob.py...After the…

Removing nan from list - Python

I am trying to remove nan from a list, but it is refusing to go. I have tried both np.nan and nan.This is my code:ztt = [] for i in z:if i != nan:ztt.append(i) zttor:ztt = [] for i in z:if i != np.nan…

Safely unpacking results of str.split [duplicate]

This question already has answers here:How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?(5 answers)Closed 6 years ago.Ive often been frustrated by the…

Get a structure of HTML code

Im using BeautifulSoup4 and Im curious whether is there a function which returns a structure (ordered tags) of the HTML code. Here is an example:<html> <body> <h1>Simple example</h…