Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validate Password In Reset Django View
**Iam using the built-in django view to reset password so my Question is how can i validate the password to make it have 1 capital letter and 1 symbol at least?? -
Resolve Django/DRF ImageField URL from F() function
I have a use case where I'm attempting to override an Image URL if it exists in our database. Here is the section of the queryset that is grabbing the ImageField from via an F() query. preferred_profile_photo=Case( When( # agent not exists Q(agent__id__isnull=False), then=F("agent__profile__profile_photo"), ), default=Value(None, output_field=ImageField()), ) The Case-When is resolving correctly, but the issue is the value returns from F("agent__profile__profile_photo") is not the URL than can be used by the UI. Instead it is something like: "agentphoto/09bd7dc0-62f6-49ab-blah-6c57b23029d7/profile/1665342685--77e51d9c5asdf345364f774d0b2def48.jpeg" Typically, I'd retrieve the URL via agent.profile.profile_photo.url, but I receive the following when attempting to perform preferred_profile_photo.url: AttributeError: 'str' object has no attribute 'url'. I've tried wrapping in Value(..., output_field=ImageField()) with no luck. The crux here is retrieving the url from the ImageField after resolving from F() For reference, I'm using storages.backends.s3boto3.S3Boto3Storage. Appreciate any help! -
DJango error: 'MercanciasForm' object is not callable
I'm building a CRUD, for insert and delete I use a modal (works perfect in both cases), but not for edit, I redirect or render to a create.html page. In all cases I use the current View (ListView, CreateView, UpdateView and DeleteView). In the especific case of UpdateView named MercanciasUpdateView I got this 'MercanciasForm' object is not callable error. MercanciasForm is the form that I use in all cases. In MercanciasListView I have to set this line context['form'] = MercanciasForm() becasue it ws the only way of Modal recognize the form, not recognize the form_class. The Form code class MercanciasForm(ModelForm): codigo = CharField(label='Code',widget=TextInput(attrs={'class':'form-control','placeholder':'Código'})) nombremercancia = CharField(label='Nombre',widget=TextInput(attrs={'class':'form-control', 'placeholder':'Nombre'})) um = CharField(label='UM',widget=TextInput(attrs={'class':'form-control', 'placeholder':'UM'})) clasificacion = ClasificacionesModelChoiceField(label='Clasificación',queryset=Clasificaciones.objects.order_by('id'), empty_label='Seleccione: ', widget=Select(attrs={'style':'width: 100%', 'class':'form-control select2bs4'}), to_field_name='clasificacion') descripcion = CharField(label='Descripción',widget=Textarea(attrs={'style':'height:150px', 'class':'form-control', 'placeholder':'Descripción'})) class Meta: model = Mercancia fields='__all__' The views.py code class MercanciasListView(ListView): model = Mercancia template_name = 'mercancia/index.html' form_class = MercanciasForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Lista de mercancias" print(reverse_lazy('mercancias')) context['form'] = MercanciasForm() return context class MercanciasCreateView(SuccessMessageMixin, CreateView): model = Mercancia form_class = MercanciasForm success_url = reverse_lazy('mercancias') success_message = "Insertado correctamente!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class MercanciasUpdateView(SuccessMessageMixin, UpdateView): model = Mercancia form_class = MercanciasForm() template_name = 'mercancia/edit.html' success_url … -
cookiecutter-django production deploy with Gunicorn / uWSGI and Nginx
Why would I not be able to access port 8000 through Gunicorn, if I can through Django's development server. The docs mentioned that production deploy with Gunicorn / uWSGI and Nginx has been successfully done, although no steps. I have been looking at external guides to do a production deploy of Django. I can run this Gunicorn command and starts listening. I am not able to access the port 8000 for some reason. I can access port 8000 publicly when I do ./manage.py runserver 0.0.0.0:8000 gunicorn config.wsgi:application --bind 0.0.0.0:8000 --name project_django_cookie_cutter --user=$NON_ROOT_USER --group=$NON_ROOT_USER --log-level=debug I am using the Django Stack application packaged by Bitnami. -
Count Django objects where two fields are equals
Let's say I have the following Django model: class Point(models.Model): x = models.IntegerField() y = models.IntegerField() I want a count of objects where x == y. I know I can do it in Python: count = 0 for point in Point.objects.all(): if point.x == point.y: count += 1 However, my table contains millions of records so I want to do this in the database. Is this possible? -
Migrating MySQL to SQLite for Django Site
(Migrate may not be the correct term I'm unsure) I'm trying to figure out how to change my Django site to register SQLite. Originally SQLite is the default for Django however I changed to MySQL because the original site I was going to host on (GoDaddy) was compatible with it. The only solution I thought of so far is changing the DATABASES info in my Settings.py. After changing my Settings to the defaults of DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', I ran into this error, (env) PS C:\Users\kayak\New Work\google athentication\mysite> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\kayak\New Work\google athentication\mysite\manage.py", line 22, in <module> main() File "C:\Users\kayak\New Work\google athentication\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\kayak\New Work\google athentication\env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\kayak\New Work\google athentication\env\lib\site-packages\django\core\management\__init__.py", line 386, in execute settings.INSTALLED_APPS File "C:\Users\kayak\New Work\google athentication\env\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "C:\Users\kayak\New Work\google athentication\env\lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "C:\Users\kayak\New Work\google athentication\env\lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\kayak\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in … -
requests.post(url, data)error `Response`, `HttpResponse` or `HttpStreamingResponse` but received a `<class 'tuple'>`
I am doing my first Django MongoDB project and trying to save the data set in the database here is the create method that I'm using def create(self, request, *args, **kwargs): try: client = MongoClient('srv13.absolute.ag:27017') collection = client.farmos.device header = request.headers['Authorization'] req = json.loads(request.body) resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header) device_id = resp.headers['Location'][8:] req['device_token'] = device_id collection.insert_one(req) return {'data': 'Success'}, 200 except Exception as e: return {'data': str(e)}, 400 But it showing an error and the error is File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 511, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 426, in finalize_response % type(response) AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'tuple'>` I think there is a problem in this line resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header) I have tried different thing changing the type of req and header to solve it but couldn't do it -
Filter Django rest framework get request by foreign key (MultipleObjectsReturned)
I have a database table called Supplier that has a foreign key of User, each User has their own Suppliers. I got the get request working so that it returns all Suppliers in the entire table, but I can not find a way to filter it so I only receive the Suppliers associated with the User requested. I am accessing this request by this URL: http://localhost:8000/pm/getsuppliers/primary-key-of-user/ models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=200) email = models.CharField(max_length=200) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.IntegerField() email = models.EmailField(max_length=200) views.py: class getsuppliers(viewsets.ModelViewSet): queryset = Supplier.objects.all() serializer_class = GetSuppliersSerializer lookup_field = 'user' serializers.py: class GetSuppliersSerializer(serializers.ModelSerializer): class Meta: model=Supplier fields=['pk','user','name','email','phone'] The error I am receiving: ERROR: pm.models.Supplier.MultipleObjectsReturned: get() returned more than one Supplier -- it returned 10! I have done some searching on this error and they are saying to use .filter instead of .all in the view, but I am not sure how to make it return ALL Suppliers for the requested User, this seems like it would only return 1. Maybe I am wrong, hopefully someone has an easy solution! -
DJANGO Read data in EXCEL file that uploaded to model
My objective is to read the contents of a worksheet uploaded by the user and apply a function to it. So far the uploading works perfect and i see the file in the server. However every time i try to select the file from the list i keep getting this error: Invalid file path or buffer object type: <class 'django.db.models.query.QuerySet'> Right here is the view that handles the file selection the the template and returns an excel file where the data was processed to be downloaded (for example if i want to filter out all duplicates and return clean data so i upload the excel sheet and return the filtered excel file.): # get file run func on it and return new excel file, view needs to handle url def dataprocess(self, pk): data = Worksheet.objects.filter(pk=pk) df = pd.read_excel(data, engine='xlrd') #finishdata = dataprocessor(df) // ignore this part for now. print("HERE---------------------->", df.url) # return excel file response = HttpResponse(content_type='application/vnd.ms-excel') # tell the browser what the file is named response['Content-Disposition'] = 'attachment;filename="ezpassreport.xlsx"' # put the spreadsheet data into the response response.write(df.getvalue()) return response This is the HTML Page: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select Report </button> <div … -
Get data from a request using Django
I have this middleware built with Node.js. Its function is sending a continuous data to a provided URL (to my Python project). In my Node JavaScript: const payload = {dictionary data}; var obj = { data: payload }; jsonobj = JSON.stringify(obj);; var XMLHttpRequest = require("xhr2"); var xhr = new XMLHttpRequest(); xhr.open("POST", "mypythonURL/", true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(jsonobj); I'm receiving it, my terminal is reacting it says that [07/Sep/2022 22:20:28] "POST /mypythonURL/ HTTP/1.1" 200 353 Any idea how I can fetch the data from that request POST? -
close django db connections after ThreadPoolExecutor shutdown
I want to use ThreadPoolExecutor in django and reuse db connection in a thread in order to avoid create db connection for each sub_task. but db connections won't be closed after ThreadPoolExecutor is shutdown. I know that i can close connection at the end of the sub_task. but with this solution, we are creating connection for each task and connection is not reused. there's a initializer params in ThreadPoolExecutor but there isn't something like on_destroy which can be called when thread is destroyed. main_task runs with the celery in my setup. def sub_task(): #some db operations def main_task(max_workers): with ThreadPoolExecutor(max_workers=max_workers) as executor: for i in range(10): executor.submit(sub_task) -
I don't understand why the function set in apscheduler is unintentionally executed 3 times in Django
I am creating a web app with Django. I wrote the following codes to add 1 data per minute to the table using APScheduler. When I checked the data generated by APScheduler on the Django admin panel, I found that 3 data were generated per minute for some reason. why does this happen? and how can i solve it? # models.py from django.db import models class Test(models.Model): test = models.CharField(max_length=8) created_at = models.DateTimeField(auto_now_add=True) # admin.py from django.contrib import admin from .models import Test class TestAdmin(admin.ModelAdmin): list_display = ('test', 'created_at') admin.site.register(Test, TestAdmin) # ap_scheduler.py from apscheduler.schedulers.background import BackgroundScheduler from .models import Test def myfunc(): Test.objects.create(test='test') def start(): scheduler = BackgroundScheduler() scheduler.add_job(myfunc, 'cron', second=50) scheduler.start() # apps.py class MembersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'my_app_name' def ready(self): from .ap_scheduler import start start() バージョン情報 APScheduler==3.9.1 Django==4.0.5 -
Django-storages file only uploaded to S3 in admin
I have configured django-sorages with S3 and I have a model Archive with a FileField called archive. Files are uploaded to S3 without any issues through admin, but using my own form the archive field stays empty. Model: class Archive(models.Model): comments = models.TextField(blank=True, default="") archive = models.FileField(null=True, blank=True, upload_to=change_filename) Form: class ArchiveForm(forms.ModelForm): class Meta: model = Archive fields = ("comments", "archive",) widgets = { "comments": forms.TextInput } View: def upload_archive(request, campaign_id): campaign = Campaign.objects.get(pk=campaign_id) form = ArchiveForm(request.POST or None) if request.method == "POST": if form.is_valid(): archive = form.save(commit=False) archive.campaign = campaign archive.save() return redirect("campaign_detail", campaign_id=campaign_id) return render(request, "upload_archive.html", {"form": form}) -
Apply Function on List
I have a view method which returns a queryset of fee records in a paginated table def fee_all(request): fee_list = Fee.objects.all().order_by('code') # query for records # How to apply separate function e.g. get_column_result # to and append result on the fee_list? p = Paginator(fee_list,10) # paginate query page = request.GET.get('page') fees = p.get_page(page) # pagination object instance context = { 'fee_list': fee_list, 'fees': fees, } return render(request, 'fee-all.html', context) def get_column_result(fee): #do operations return column_result I want to apply a method/function for each queryset item to do a calculation and display the result as an additional column in the displayed table. Considering trying to use Data frames from Pandas with the apply() or Applying lambda function but conversion from resulting dataframe to queryset is difficult. Any ideas? -
FCM-Django ModuleNotFoundError: No module named 'requests.adapters'
I'm trying to use fcm-django in my Django app to use Firebase messages and notifications. But when I try to initialize the firebase app it gives me this error : Traceback (most recent call last): File "D:\Python\rolla_django\venv\lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\connection.py", line 84, in close_all for conn in self.all(initialized_only=True): File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\connection.py", line 76, in all return [ File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\connection.py", line 73, in __iter__ return iter(self.settings) File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\connection.py", line 45, in settings self._settings = self.configure_settings(self._settings) File "D:\Python\rolla_django\venv\lib\site-packages\django\db\utils.py", line 148, in configure_settings databases = super().configure_settings(databases) File "D:\Python\rolla_django\venv\lib\site-packages\django\utils\connection.py", line 50, in configure_settings settings = getattr(django_settings, self.settings_name) File "D:\Python\rolla_django\venv\lib\site-packages\django\conf\__init__.py", line 92, in __getattr__ self._setup(name) File "D:\Python\rolla_django\venv\lib\site-packages\django\conf\__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "D:\Python\rolla_django\venv\lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\Python\rolla_django\rolla_django\settings.py", line 14, in <module> import firebase_admin File "D:\Python\rolla_django\venv\lib\site-packages\firebase_admin\__init__.py", line 21, in <module> from … -
Django says current user is unauthenticated although logged in
I havent really changed anything and added a View to update some user data. Then i wanted to test my View and Django says that the current user is not authenticated. I logged out and logged in multiple Times and also looked at the requests in Burp. To me every looks fine, it always sends the session_id and also login goes through without problems. I also get my User Object returned to the frontend on login. When i then try the "edit" function for the User then i'm unauthenticated... This is my login: @action(methods=['post'], detail=False, url_path='sign-in', url_name='sign-in') def login_user(self, request): email = str(request.data.get('email')) password = str(request.data.get('password')) if email is None or password is None: return _ERROR_INCOMPLETE_CREDENTIALS # User authentication... user = authenticate_user(email=email, password=password) if user is None: return _ERROR_BAD_CREDENTIALS user_profile = UserProfile.objects.get(id=user.id) serialized_user = UserProfileSerializer([user_profile], many=True).data print(serialized_user) res = login(request, user) print(res) return Response(serialized_user, status=status.HTTP_200_OK) This is the custom authenticate_user Method: def authenticate_user(email, password): try: user = User.objects.get(email=email) except User.DoesNotExist: return None else: if user.check_password(password): return user return None This is a view which fails due to unauthentication: @action(methods=['get'], detail=False, url_name='current', url_path='current') def get_current_user(self, request): if not request.user.is_authenticated: return Response({"detail": "You need to be logged in for this!"}, status=status.HTTP_401_UNAUTHORIZED) user … -
Linking images from other websites in <img> tags, with URL's returned from my Django API. Is this a sustainable approach for production?
Will I run into a CORS error if I am using my API to return an image url, from on another site, which I set to an tag with the src attribute? I have an API written in Django which has a model with links to movie posters, which are hosted on the site: m.media-amazon.com, for example: https://m.media-amazon.com/images/M/MV5BNjM0NTc0NzItM2FlYS00YzEwLWE0YmUtNTA2ZWIzODc2OTgxXkEyXkFqcGdeQXVyNTgwNzIyNzg@._V1_SX300.jpg With my current development server, I have a JavaScript file that makes a request to an endpoint which returns that url, which I then set in an img tag with the src attribute. It displays in my browser, but will I run into issues in production? is this a sustainable approach? this is my js code: async function getMovieUrl() { try { const response = await fetch('/posterurl/', { method: 'GET' }); const urldata = await response.json() var url = document.getElementById("posterurl") url.src = urldata['url'] } catch(error) { console.error(error) } } this is my API code: @api_view(['GET']) def poster_url(request): context = {'url': url from above} return Response(context) and currently I am able to see the image in my browser upon clicking: <button onclick="getMovieUrl()">Movie URL</button> -
Perform query with foreignkey django
I'm new to django and i've got this two django models. Now i'm trying to query the stripe in the second model(GenerateKeys) which has the Stripe as the foreignkey and the way i'm doing it is like this " stripe.stripe_customer.all() " so i can get the individual data from each user in the Stripe model and use it in the Generateakeys model. But i keep getting this error below AttributeError: 'QuerySet' object has no attribute 'stripe_customer' class Stripe(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) CustomerId = models.CharField(max_length=255) class GenerateKeys(models.Model): stripe = models.ForeignKey(Stripe,on_delete=models.CASCADE,related_name='stripe_customer') key_sha = models.CharField(max_length=255) Thanks. -
How can I change display of visible value in django form?
I have Django model from external python library: class Item(models.Model): name = models.CharField(...) serial = models.CharField(...) def __str__(self): return str(self.name) ... I can't change this model, but I want to display on my form widget with value as "Item Name (Item Serial)" My form is very simple: # forms.py class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = ('title', 'item',) # models.py class Inventory(models.Model): title = models.CharField(...) item = models.ForeignKey(to='Item'...) ... Can I change display of visible value? -
Best way to send photo inside mail Django
What is the best way to attach my website logo inside activation mail? I tried to do something like this: @lru_cache() def logo_data(): with open('templates/authentication/logo.png', 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data) logo.add_header('Content-ID', '<logo>') return logo and then: email=EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.attach(logo_data()) email.content_subtype='html' email.send() In my html file it looks like this: <img src="cid:logo" style="width: 242px; height: 88px;"/> but it doesn't work. The photo is actually added to the mail in attachments, but the <img> tag is empty and looks just like this: What is wrong? I read also that attaching photos to email is not recommended because mail gets cause of that extra spam points. What is the best way to do this? Can I send my png logo without attaching it into attachments? -
removing __all__ from django form.errors
i want to render errors in each field and remove the all from errors {% csrf_token %} {% if form.errors %} <p><strong>{{form.errors}}</strong></p> {% endif %} <label>{{form.username.label}}</label> {% render_field form.username class+='form-control border' %} <br> <label>{{form.password.label}}</label> {% render_field form.password class+='form-control border' %} <br> <input class="btn btn-primary" type="submit" value="Login"> <p>don't have an account <a href="">Register</a> </p> </form> -
Why is Django product editing not working. Reverse for 'edit' not found?
I'm trying to edit a product (without using forms.py) but I get an error Reverse for 'edit' not found. 'edit' is not a valid view function or pattern name. vievs.py def edit(request, id): if (request.method == 'POST'): obj, update = Posts.objects.update_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() return render(request, 'edit.html') html <form action="{% url "blog:edit" %}" method="post"> {% for el in posts %} {% csrf_token %} <input type="text" placeholder="Название" name="title" value="{{ el.title }}"><br> <textarea placeholder="Текст статьи" rows="8" cols="80" name="text"></textarea><br> <input type="file" name="image"><br> <button type="submit">Добавить статью</button> {% endfor %} </form> -
How to store image in Django - use link or no?
I have field: image = models.ImageField( max_length=500, upload_to='images' ) and some settings to upload image to AWS S3 Bucket, where is PublicMediaStorage is my custom storage: PUBLIC_MEDIA_LOCATION = 'media' AWS_S3_MEDIA_ENDPOINT_URL = env('AWS_S3_MEDIA_ENDPOINT_URL', None) DEFAULT_FILE_STORAGE = 'new_project.storages.PublicMediaStorage' I need to store and get my images from database(postgres)? For now my image stores at the database like here. And if i write image.url i will get the url of my image(that's why I don't need to store urls of images in my database). But is it right way? Maybe it will be better to store immediately links at the database? Any solutions? -
Can I use django with angular together in single web application
Can I use django with angular together in single web application because I was learning NodeJs(express) and It started to be very confusing because of asynchronous javascript so that is why i wanted to learn python and django -
SerializerMethodField's function get_fieldname is not being called
I have this Serializer class RemovePermissionsSerializer(serializers.ModelSerializer): user_permissions = serializers.SerializerMethodField() def get_user_permissions(self, instance): print(1) **logic** return data class Meta: model = User fields = [ "user_permissions" ] and a generic viewset with this action @action( methods=["patch", "put"], detail=True, url_name="add-permissions", url_path="add-permissions" ) def add_permissions_request(self, request, pk): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.get_object() user_permissions = serializer.validated_data.get("user_permissions") response = User.add_permissions(user, user_permissions) return Response(response, status=status.HTTP_200_OK) the function get_user_permissions is not being called whatever I put in it, even print() is not showing anything, any help please?