Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache permissions overriding Django function for authorization check
I built an app where users can upload their files and only the user who uploaded the file can view it. This was working while I was developing the application but now after I hosted in on a VPS with Apache, it doesn't work. I gave permissions to www-data to create and read files and folders inside of /file which is a folder where I save all of the files. A folder inside of file is created for each user when he uploads his first file and the name of that folder is the username of the user i.e. if TestUser uploads his first file, then a folder will be created at /file/TestUser. I wrote a function that checks if the URL which the user opens, has /file in it. If it does, it check if it has the user's username and then opens the file. I have no clue why is this not working now, and anyone can open any file. def auth_file_check(request): url = request.build_absolute_uri() if not '//' in url: url = 'http://' + url o = urlparse(url) user = o.path.split("/") if str(request.user) == user[2].split("_", 1)[1] or request.user.is_superuser: # Change link to path where files will be stored … -
display category and sub category in django
I am Working on the Web Application and it needs to show the categories and sub catgories to the side bar. Here is the screenshot of the database.please take a look and hep enter image description here def home(request): return render(request,"myApp/index.html") def info(request): ac = REFERENCE_DATA_LOOKUP.objects.all() L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_C_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_U_S = 0 or 1 elif (int(row.kpi_delta_ind) < 0): L_C_U_S = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_A = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_A = -1 elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_W_U_S = 0 elif (int(row.kpi_delta_ind) < 0): L_W_U_S = -1 elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): L_C_P_S = 0 elif (int(row.kpi_delta_ind) < 0): … -
Djagno Rest Framework, updating multiple objects in one
I am trying to update using PATCH to my Django backend. This is the request I am sending: [ { "pk":78, "weekday":1, "from_hour":"21:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":79, "weekday":2, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":80, "weekday":3, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":true, "lunch_start":null, "lunch_end":null, "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, { "pk":81, "weekday":4, "from_hour":"09:00:00", "to_hour":"12:00:00", "closed":false, "lunch":false, "lunch_start":"14:59:50", "lunch_end":"14:59:51", "lunch2":false, "lunch_start2":null, "lunch_end2":null, "appointment_interval":15, "num_appointments_interval":4, "office":79 }, ] I send this to a custom view where I am trying to serialize and update the data. @api_view(['PATCH']) @parser_classes((JSONParser,)) def updateOfficeHours(request): office_id = request.data[0]['office'] qs = OfficeHour.objects.filter(office__pk=office_id) office_hours = OfficeHoursSerializer(qs, data=request.data, many=True, partial=True) if not office_hours.is_valid(): print(":(") return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: office_hours.save() return Response(status=status.HTTP_200_OK) I only end up getting this error: AttributeError: 'QuerySet' object has no attribute 'pk' It seems like this error comes up when you are looking for one object, but I have many=True. What am I doing wrong? -
Can't submit a csrf token using javascript in Django
I'm using the following code to submit a csrf token purely in js since I want to cache the pages with the form. axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.withCredentials = true This works locally (localhost, 127.0.0.1) without a problem. This is to get rid of the 403 errors that happen when I login into the app and try to submit a form that no longer has a csrf token embedded in the dom. The issue is I can't get this run in our development environment. The development environment uses CloudFront but i don't think that's an issue. Here is my dev config for Wagtail + Django: #Important for CloudFront USE_X_FORWARDED_HOST = True # Security Headers SECURE_HSTS_SECONDS = 63072000 SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = False CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True UPGRADE_INSECURE_REQUESTS = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True PREPEND_WWW = False All my API views have csrf_exempt on them, but i still need the token when i try to submit after a login. My middleware is: MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "app.site_translation.middleware.TranslationMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "app.base.middleware.AdditionalSecurityHeadersMiddleware", "app.base.middleware.CookieMiddleware", "app.base.middleware.DomainRedirectMiddleware", "app.base.middleware.CustomRedirectMiddleware", "app.base.middleware.LegacyURLsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] I don't know what is going on I keep getting CSRF Failed: CSRF … -
Django assign a task to many users
I want to create a task for many users(students) but I want every student to have his own "copy" of this task so students can't edit each other's tasks. E.g.: I, as a teacher, creates a task and assign 4 students to that task. Every student get exactly the same task and can change it's progress etc. Does anyone has any idea how to achieve that? I've stucked. Thanks in advance. models.py class Task(Timestamp): STATUSES = ( ("new", "new"), ("in-progress", "in-progress"), ("done", "done") ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True, editable=False) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField() status = models.CharField(choices=STATUSES, max_length=50, default="new") students = models.ManyToManyField(CustomUser, related_name='students') def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Task fields = [ 'id', 'owner', 'created_at', 'updated_at', 'title', 'description', 'status', 'attachments', 'students' ] -
Understanding order_by of multi-valued fields (Django)
Having read the django docs on order_by there is a note/warning that (if I have understood correctly) says that: If you are ordering a queryset using a multi-valued field, then every element in that queryset that has multiple related items, will be added multiple times to the resulting queryset created by order_by. I tried testing this out with a basic example: Minimal Reproducible Example class Pizza(models.Model): name = models.CharField(max_length=100) toppings = models.ManyToManyField('Topping', through='PizzaToppings') class PizzaToppings(models.Model): pizza = models.ForeignKey('Pizza', on_delete=models.CASCADE, related_name="pizza_toppings") topping = models.ForeignKey('Topping', on_delete=models.CASCADE, related_name="pizzas_with_topping") amount = models.IntegerField() class Meta: ordering = ["amount",] class Topping(models.Model): ingredient = models.CharField(max_length=100) then >>> p1 = Pizza.objects.create(name="Cheese and Tomato") >>> p2 = Pizza.objects.create(name="Pepperoni") >>> cheese = Topping.objects.create(ingredient="Cheese") >>> tomato = Topping.objects.create(ingredient="Tomato puree") >>> p1.toppings.add(cheese, through_defaults={"amount":4}) >>> p1.toppings.add(tomato, through_defaults={"amount":3}) >>> p2.toppings.add(cheese, through_defaults={"amount":2}) >>> p2.toppings.add(tomato, through_defaults={"amount":1}) So far, so normal. But this is where things get confusing: >>> q1 = Topping.objects.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q2 = p1.toppings.all() <QuerySet [<Topping: Topping object (1)>, <Topping: Topping object (2)>]> >>> q1.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>, <Topping: Topping object (2)>, <Topping: Topping object (1)>]> >>> q2.order_by("pizzas_with_topping") <QuerySet [<Topping: Topping object (2)>, <Topping: Topping object (1)>]> The problem As … -
ModuleNotFoundError: No module named 'crud.core' in python 3 and windows 10
Researched a bit and haven't found any solution whatsoever. My application name is CRUD. Whenever I try to run my application using the: python manage.py runserver I get the following error: ModuleNotFoundError: No module named 'crud.core' I used the following commands: python -m venv crud pip install django pip install djangorestframework python manage.py startapp rental And the file that's causing trouble (api.py): from rest_framework import routers from .core import views as myapp_views router = routers.DefaultRouter() router.register(r'friends', myapp_views.FriendViewset) router.register(r'belongings', myapp_views.BelongingViewset) router.register(r'borrowings', myapp_views.BorrowedViewset) I'm on windows and running python 3.9.0 -
How to determine Django version of a given code?
I have a site in Django. How to know (by watching at code), which version of Django it requires and which Python it requires? -
How to access individual form objects from a modelformset_factory?
I've deployed a formset using modelformset_factory. However rather than saving the entire formset, I need to loop through the forms in the formset, perform some logic on them, and save each one individually. At the moment I'm having to use the ID from each form in the formset to get the object it represents. Is there a cleaner way of doing this? def accounts_import(request,pk): account = get_object_or_404(Account, pk=pk) # Create transactions queryset for use in formset transactions = Transaction.objects.filter(account=account.monzo_account, import_type=None).order_by('-id') FormSet = modelformset_factory(Transaction, form=TransactionsImportForm, extra=0) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): for form in formset: object = Transaction.objects.get(id=form.cleaned_data['id']) # Do some stuff on the object object.save() -
How make users own their data in django
Currently, if you’re logged in, you’ll be able to see all the products, no matter which user you’re logged in as.how can i show merchants only the products that belongs to them. i try this views.py def users_homepage(request): product=Product.objects.filter(merchant=request.user).order_by('date_added') and i get this error " Cannot query "mustapha": Must be "Merchant" instance" my models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Product(models.Model): merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) -
Django Rest Framework Custom Permission does not recognize user
I am trying to enforce a custom permission in DRF. Specifically, I am trying to see whether a user is authorized to access an object. I adapted this solution from another post here but it does not quite work for me. The permission class always assumes that request.user is an Anonymous user. What am I missing? permissions.py class CanSeeWishlist(permissions.BasePermission): def has_permission(self, request, view): try: wishlist = Wishlist.objects.get( pk=view.kwargs['pk']) except: return False if wishlist.private: print(request.user) # Prints Anonymous User if request.user.id == wishlist.owner.id or request.user.id in wishlist.members.all(): return True return False return True api.py class WishlistViewset(viewsets.ModelViewSet): serializer_class = WishlistSerializer queryset = Wishlist.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] def get_permissions(self): if self.request.method == 'GET': self.permission_classes = (CanSeeWishlist,) return super(WishlistViewset, self).get_permissions() -
I had written some css code but it is not appearing on my server
This is my css file This is html file where i loaded the css file -
I have tried python manage.py makemigrations and end up with this error
from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/home/khurshid/Documents/git/uzedi2/lib/python3.8/site-packages/django/db/models/fields/init.py) -
Generate authtoken through consumer or middleware in Django
I have searched quite a lot, can't find anything regarding the authtoken generation using Django Channels, and how to return it. As routes are protected through the use of TokenAuthMiddlewareStack() like specified here i can't just create a consumer with a specific route to the consumer itself So, what are my options? Ask for the client to generate the token via http request Send user's password and username once through json request (Over a TLS connection) and if TokenAuthMiddlewareStack can't find an authorization header, it'll look for the username and password fields in order to generate and return a token Option number one makes things bureaucratic. Option number 2 is more a band-aid solution. Is there a more practical solution? Thank you. -
How do I attribute different color for each of the django model choices
Following is my models.py: class Table(models.Model): choices = ( ("BUY", "Buy"), ("HOLD", "Hold"), ("SELL", "Sell"), ) remarks = models.CharField(max_length=200, choices=choices, default="HOLD", null=True) Is there some way to attribute different color for each of the choices? For instance, if i choose "BUY" it is displayed in a color, say blue, on my html page. Thanks! -
Issue with inheriting from the django-graphene default GraphQLView
I have the need to do the following: path( '<uuid:uuid>/graphql', csrf_exempt( viewsets.MyCustomGraphQLView.as_view() ) ), That is, to pass in a uuid which can reference a different graphql schema dynamically. I'm attempting to do something like the following: from django.views.generic import View from django.shortcuts import get_object_or_404 from graphql.type.schema import GraphQLSchema from graphene_django.views import GraphQLView class MyCustomGraphQLView( GraphQLView ): def __init__( self, *args, **kwargs ): super(MyCustomGraphQLView, self).__init__(*args, **kwargs) self.schema = self.get_object().get_schema() assert isinstance( self.schema, GraphQLSchema ), "A Schema is required to be provided to GraphQLView." def get_queryset(self, *args, **kwargs): return MyObject.objects.all() def get_object(self, *args, **kwargs): print(self.uuid) // None print(MyObject.objects.get(uuid=self.uuid)) // None queryset = self.get_queryset() obj = get_object_or_404(queryset, uuid=self.uuid) return obj However, I'm, not seeing that the uuid kwarg from path() is not being passed into the class ... that is, self.kwargs is None, and self.uuid is also None ... Would anyone be able to help with understand how I can get MyCustomGraphQLView to inherit the setup() from from django.views.generic import View ?? -
Keyczar: ModuleNotFoundError: No module named 'errors' in Python 3.8
I'm using django-encrypted-fields to encrypt models in the database, but I'm getting the ModuleNotFoundError: No module named 'errors' from keyczar, is there any solvations? -
django template, using {% with %} to set a list var
I need to hard set a list in django template. I know that I have to pass variables to the template, instead of creating them in the template, but I only have access to the template file. I'm using sendinblue with a custom template, and the only way to use custom params injected to the template is to use their api. I only need to hardcode some content in a list, and the content will dynamically appear depending on contact, I think that using an api only for this is overkill. -
image : None while successfully upload Django
I'm getting image url None while successfully uploading the image, i expected to get the image url which i sent to my server, but i'm getting the None value instead. Any help, would be much appreciated. thank you so much in advance. serializers.py class BulkImageSerializer(ModelSerializer): image1 = ImageField(required=True) image2 = ImageField(required=False) user_id = CharField(read_only=True) class Meta: model = BulkImage fields = "__all__" def create(self, validated_data): image1 = validated_data['image1'] image2 = validated_data['image2'] validated_data['user_id'] = User.objects.get(email=self.context['request'].user.email) img_obj = BulkImage.objects.create( image1 = image1, image2 = image2 if image2 else None, user_id = validated_data['user_id'] ) return validated_data views.py class BulkImageAPIView(APIView): permission_classes = (IsAuthenticated,) def post(self,request,*args,**kwargs): user = request.user data = request.data serializer = BulkImageSerializer(data=data, context = {'request': request}) if serializer.is_valid(): serializer.save() return Response({ 'message' : 'Image upload successfully', 'data' : serializer.data, },status=200) return Response(serializer.errors,status=400) output: { "message": "Image upload successfully", "data": { "image1": null, "image2": null, "user_id": "employee01gmailcom" }, } -
How to insert multiple foreign key values in django?
i've tried using bulk_create but i couldn't insert the foreign key value, i want to add 100 bikes with about 20 stations class Bike(models.Model): ID_Bike = models.CharField(primary_key=True, max_length=120) Belong_Station = models.ForeignKey( Station, on_delete=models.CASCADE, related_name='listBike') def __str__(self): return self.ID_Bike class Station(models.Model): name_Station = models.CharField(max_length=120) latitude = models.FloatField(max_length=120) longitude = models.FloatField(max_length=120) address = models.CharField(max_length=120, default="") def __str__(self): return self.name_Station -
Initialize base class with data from derived class with django Model
Is there any way to inherit a django model and initialize a base class field with data in the derived class, like this : class InitialModel(models.Model): evolution_list = ('1', '2', '3') version = models.CharField(max_length=2, choices=evolution_list) # choices will be : '1', '2', '3' class Meta: abstract = True class NextModel(InitialModel): evolution_list = ('4', '5', '6') # version : choices will be : '1', '2', '3' # wanted version choices are : '4', '5', '6' Thanks in advance! -
Iterate over django m2m through model objects
I have the following ManyToMany relationship in my project: class Borrador(models.Model): nombre = models.CharField( max_length=40, help_text=_('Nombre para identificar al borrador.') ) productos = models.ManyToManyField( Producto, through=Articulo, ) class Articulo(models.Model): producto = models.ForeignKey( Producto, on_delete=models.SET_NULL, null=True ) borrador = models.ForeignKey( 'Borrador', on_delete=models.SET_NULL, null=True ) unidades = models.IntegerField( default=1 ) class Producto(models.Model): nombre_amistoso = models.CharField( max_length=40, help_text=_('Nombre corto para identificarlo facilmente.'), verbose_name=_('Pseudónimo') ) nombre_fabricante = models.CharField( max_length=60, help_text=_( 'Nombre largo que le da el fabricante al producto.' ), verbose_name=_('Nombre real') ) fabricante = models.ForeignKey( 'Fabricante', on_delete=models.SET_NULL, blank=True, null=True ) # etc... As you can see, Articulo model acts as a through intermediary model to retrieve additional info. I'm trying to iterate over all the Articulo objects associated with a given Borrador object. At the moment I got it working by doing this: class Borrador(models.Model): # [...] def tramitar(self, usuario, solicitar=False): articulos = self.productos.through.objects.filter( borrador=self ) for articulo in articulos: # do stuff My first attempt was the one below, but it returns all Articulo objects in the database articulos = self.productos.through.objects.all() for articulo in articulos: # do stuff Is there a better way to do this? I imagined a simple self.productos.through shoul work, but it isn't the case... Thanks in advance! J. -
Expected a list of items but got dict djangorestframework
I am making a quiz application using DjangoRestFramework and ReactJS and I am coding my serializers for my Create quiz page. In my application, I have a Question model, a Game model which is the Quiz, and an Option model. The Problem My data Here is the data I have that I am deserializing: data = { 'name': 'Quiz Name', 'questions': { 'text': 'Question 1', 'options':[ {'text': 'option 1', 'is_correct':False}, {'text': 'option 1', 'is_correct':True}, ] } } I run this in the shell: >>> serializer = CreateGameSerializer(data=data) >>> serializer.is_valid() False >>> serializer.errors {'questions': {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "dict".', code='not_a_list')]}} As you can see, I am getting Expected a list of items but got type "dict". I am not sure what this error means and I searched SO but didn't find anything relevant. My Files I have included some of my models and serializers to help solve the problem. models.py class Game(models.Model): name = models.CharField(max_length=100, default='') code = models.CharField(max_length=100, default=generate_unique_code, unique=True) host = models.CharField(max_length=50, unique=True) def __str__(self): return self.code class Question(models.Model): text = models.CharField(max_length=100) order = models.IntegerField(default=0) game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.text class Option(models.Model): text = models.CharField(max_length=100) is_correct = models.BooleanField(default=False) question = … -
How to set the room availability to False after I selected a room in django
Im currently developing a Hotel Management System and I would like to set the availability of room to False after i choose it on reservations form. Here is my codes : models.py class Room(models.Model): room = ( ('Standard Room' , 'Standard Room'), ('Deluxe Room', 'Deluxe Room'), ('VIP Room', 'VIP Room') ) id = models.AutoField(primary_key=True) room_type = models.CharField(max_length=100, choices=room , verbose_name = 'Type of Room') room_no = models.PositiveIntegerField(verbose_name = 'Room No', unique=True, help_text = "Should be unique and not existing room no") rates = models.DecimalField(max_digits=10, decimal_places=2, verbose_name = "Rates per Room") available = models.BooleanField(default=False, verbose_name="Available") def __str__(self): return f"{self.room_type}" + " | " + "Room " + f"{self.room_no}" class Reservations(models.Model): room = ( ('Standard Room' , 'Standard Room'), ('Deluxe Room', 'Deluxe Room'), ('VIP Room', 'VIP Room') ) customer = models.ForeignKey(User, on_delete = models.CASCADE, related_name="reservation_user" ) name = models.CharField(max_length = 255, verbose_name = 'Customer Name') address = models.CharField(max_length = 255, verbose_name = 'Address') email_address = models.EmailField(verbose_name = 'Email Address') contact = models.CharField(max_length = 255, verbose_name = 'Contact No') type_of_id = models.CharField(max_length = 255, verbose_name = 'Type of ID') id_no = models.CharField(max_length = 255, verbose_name = 'ID No') no_of_days = models.CharField(max_length = 255, verbose_name = 'No of Days') check_in_datetime = models.DateTimeField(auto_now_add=False, verbose_name = … -
Почему PUT и PATCH в данном случае дают одинаковый результат?
Необходимо реализовать PUT и PATCH методы. именно и то и другое. Прочел, что PUT должен очистить не переданные ему аргументы, а PATCH именно внесет изменения в указанное поле. Данный метод работает как PATCH. **serializers.py** class ReadOnlyUserSerializer(serializers.ModelSerializer): first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=150) is_active = serializers.BooleanField() class Meta: model = CustomUser fields = [ 'id', 'username', 'is_active', 'first_name', 'last_name', 'last_login', 'is_superuser', ] def update(self, instance, validated_data): instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_active = validated_data.get('is_active', instance.is_active) instance.save() return instance **views.py** class UserViewSet(ListAPIView): # Allow only authenticated users to access this urls permission_classes = [IsAuthenticated, ] serializer_class = ReadOnlyUserSerializer def patch(self, request, **kwargs): saved_user = CustomUser.objects.get(pk=kwargs['pk']) data = request.data serializer = ReadOnlyUserSerializer(instance=saved_user, data=data, partial=True) if serializer.is_valid(raise_exception=True): saved_user = serializer.save() return Response({ "success": f"User with username '{saved_user}' updated successfully"}) Как написать метод для PUT ? как я понял, если передать Postman-ом PUT http://127.0.0.1:8000/api/v1/users/6/ {"first_name": "Lama"} , остальные поля, не указанные в теле запроса, должны очиститься...