Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django how to get query I want
Imagine I have such model class Data(models.Model): disease = models.CharField(max_length=1024) phrase = models.CharField(max_length=1024) I also have two lists: 'blacklist', 'allowed_list' I need to get Data objects in which disease is IN allowed_list & phrase NOT IN blacklist (both conditions). How can I get this query? -
retrieving data from one model to another using a foreign key
Trying to get values from related model. So i do something like this: class Model_one(models.Model): quantity = models.CharField() class Model_two(models.Model): quantity = models.CharField() class Calc(models.Model): product = models.ForeignKey(Product) model_one = models.ForeignKey(Model_one) model_two = models.ForeignKey(Model_two) result = ArrayField() def do_some(self): result = self.model_one.quantity + self.model_two.quantity return result def save(): ...... but getting error: RelatedObjectDoesNotExist: Calc has no model_one so how can i do it right? -
Django Post Model with Images in specific location
I'm working with a very simple blog-post-style model right now class TripReport(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) countries = models.ManyToManyField(Country, blank=False, related_name='trip_countries') title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateField(default=timezone.now) date_updated = models.DateField(auto_now=True) def __str__(self): return self.title I'm looking to add photos to the model. I know I can use the Django models.ImageField, but I want there to possibly be multiple photos and at specific locations throughout the content TextField. It seems like I would have to use a separate model to upload the photos, then use a ManyToMany relationship to tie them to the Trip Report model, but I'm not sure how I could make sure the TextField injects them at the right spot. -
Django form accessing other data
I have a standard modelform and specify the fields I wish to render. Is it possible to show data contained within that same model but not in the allowed fields in the template, and not as a form field? Just using a normal template tag? For example if I had a model like: class Blah(models.Model): blah = models.CharField() blah_again = models.CharField() And a form like: class BlahForm(ModelForm): class Meta: model = Blah fields = ['blah'] But in the template I want to render blah_again? I am using model formsets and whilst I believe the principal to be the same, as 2 forms are rendered I need to title each form by a field in each model instance for logic presentation. Thanks -
How can I fix "ValueError: "<Klant: None - aCustomer>" needs to have a value for field "klant" before this many-to-many relationship can be used."
Here are the imports: from django.db import models from datetime import datetime, timedelta from django.contrib.auth.models import User This is the first class I defined. It is the status of the action (Actie) and it has a status-id and a status-name with a max_length attribute of 5 (todo, doing, done) class Status(models.Model): id = models.IntegerField(primary_key=True) status_naam = models.CharField(max_length=5, default='todo') def __str__(self): return str(self.id) + " - " + self.status_naam This is the second class Klant wich means customer. It has an id, a customer-name and users from the customer wich is a ManyToManyField referring to users from the the User-table django gives me. class Klant(models.Model): id = models.IntegerField(primary_key=True) klant_naam = models.CharField(max_length=100, default='-') klant_gebruiker = models.ManyToManyField(User) def __str__(self): return str(self.id) + " - " + self.klant_naam This is the class Actie (Action or the action the user determines) wich has an id, an action-name, a action-status wich refers to the table Status here above, an action-publish-date, an ending-date (the deadline) and a customer-id wich refers to Klant. class Actie(models.Model): id = models.IntegerField(primary_key=True) actie_naam = models.CharField(max_length=150, default='-') actie_status = models.ForeignKey(Status, default=1) actie_aanmaakdatum = models.DateTimeField(default=datetime.now()) actie_einddatum = models.DateTimeField(default=datetime.now() + timedelta(days=1)) actie_klant = models.ForeignKey(Klant, default=1) def __str__(self): return str(self.id) + " - " + self.actie_naam … -
Map with hardcoded latitude and longitude in the template not showing up
<div id="map" style="width: 400 px;height:300px; background-color:lightblue; display: inline-block"></div> <script> console.log("outer"); function myMap() { console.log("inner"); var mapCanvas = document.getElementById("map"); var myCenter = new google.maps.LatLng(24.3771050,54.5168070); var mapOptions = {center: myCenter, zoom: 15}; var map = new google.maps.Map(mapCanvas,mapOptions); var marker = new google.maps.Marker({ position: myCenter, animation: google.maps.Animation.BOUNCE }); console.log("inner2"); marker.setMap(map); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=value&callback=myMap" type="text/javascript"></script> It prints the values: outer, inner and inner2 on the console. But doesn't show the map at all. I am not able to understand why this situation is arising. Same code works otherwise in web2p. Please help me correct this. -
How to get multiple values from a template and update multiple fields in a rows of thesame table in django
I am working on a result processing website and I've been trying to update multiple fields in each row of table. User should be able to input updated CA Score and EXAM Score values and it should update each student's CA Score and EXAM Score values which has been submitted. image of page Someone ask same question here trying to update a single field. I tried to work with the solution provided there but was unable to make it suit my need template <form action="" method="post"> {% csrf_token %} {% for student in students %} <tr> <td>{{ student.id_number }}</td> <td> <input type="number" value="{{ student.ca }}" name="student_{{ student.id }}"> </td> <td> <input type="number" value="{{ student.exam }}" name="student_{{ student.id }}"> </td> </tr> {% endfor %} <tr> <td><input type="submit" value="Save"></td> </tr> </tbody> </table> </form> view def add_score_for(request, id): if request.method == 'GET': students = TakenCourse.objects.filter(course__allocated_course__lecturer__pk=request.user.id).filter(course__id=id) context = { "students":students} return render(request, 'result/add_score_for.html', context) if request.method == 'POST': data = request.POST.dict() data.pop('csrfmiddlewaretoken', None) for i in data.items(): obj = TakenCourse.objects.get(id=i[0].split("_")[1]) if not str(obj.ca) == str(i[1]): # if i do i[2] trying to get for exams it raise 'tuple index out of range' obj.ca = i[1] obj.save() -
Django rest facebook auth
I would like to use django-rest-framework-social-oauth2 to auth from mobile app via API endpoint. So I followed example for facebook as it's described in README, but it doesn't work for me. I used this command where I replaced client_id and client_secret from my facebook console. curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token I'm getting errors: { "error": "invalid_request", "error_description": "Invalid client_id parameter value." } -
Select Object of a Model with Popup
I think this should be easy to solve but for Popups I always got some complicated solutions. I have three models that I need to make into one Con. Time (my own model class) and Doc (my own model class) I have the pk of those no problem. But there is a third one, Person that I need to combine with the others. So could should look like this. t = Time.objects.get(pk=pk) doc = Doctor.objects.get(pk=pk_doc) # create popup here and get the Person object p = Person.objects.get(pk=pk_p) con = Con(t, doc, p) con.save() Now I was thinking of doing a popup window of all the Person objects and select one from there pass it to my view and create that model. How can I do that or what other solution is there? Sorry for my explanation I am not familiar with the names in Django since I am quite new to it. Thanks in advance for your help! -
rename unique field in django model and migrate
I had a model which looks like this: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.TextField(max_length=100, unique=True) # other fields Then I realised after working further on what I am building, that it is quite important that the username field is slightly differently named, so made an alteration in that line: username_internal = models.TextField(max_length=100, unique=True) and ran python manage.py makemigrations myapp. It asked me for a default value, but when I look at the .py migration it created, don't like what it has done: # -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-11-14 10:49 from __future__ import unicode_literals import django.contrib.auth.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_user_internalid'), ] operations = [ migrations.AddField( model_name='user', name='username_internal', field=models.TextField(default=5, max_length=100, unique=True), preserve_default=False, ), migrations.AlterField( model_name='user', name='username', field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'), ), ] It is trying to create a new field, I just want it to rename the existing field. Am new to Django (using 1.11.4) Does anyone know how to fix this? -
Django resolve site and/or path as site, site framework?
A user of 'Some Organization' can make actions through: 1.2.3.4/someorganization/(action1/action2/etc..) By pointing someorganization.com to 1.2.3.4 What I want to achive is: I would like that django knows that someorganization.com/action1 "maps" the request to 1.2.3.4/someorganization/action1. I dont know if its possible to do something with a "URL Dispatcher" with middleware etc. I know a little about djangos site framework but I would like to avoid having a settings file for each site/organization. I'm not looking for a solution with subdomains eg. someorganization.ourdomain.com The thing is I'm not sure what to look/search for. So I need help getting pointed in the right direction. -
Django initiates a DetailView instead of a ListView contrary to what is defined in urls.py
I came across a very strange behavior of my django app, that I don't understand. Maybe someone sees an obvious mistake, that I don't see. I also must admin, I am not an expert in django... I have a Model - Exposure and my app app_name = 'BPMWebGUI' A User can have Exposures and I am using the default django User model. urls.py urlpatterns = [ path('', views.user_login, name='user_login'), path('<slug:slug>/', views.ExposureDetailView.as_view(), name='exposure_detail'), path('my_exposures/', views.ExposureListView.as_view(), name='user_exposure_list'), ] The link href="{% url 'BPMWebGUI:user_exposure_list' %} works and url: 127.0.0.1:8000/BPMWebGUI/file_upload/ appears in the browser views.py from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404 from .models import Exposure, User class ExposureDetailView(LoginRequiredMixin, DetailView): model = Exposure def __init__(self,*args, **kwargs): print("Exposure Detail View initiated") super(DetailView, self).__init__(*args, **kwargs) class ExposureListView(LoginRequiredMixin, ListView): model = Exposure template_name = 'BPMWebGUI/user_exposure_list.html' def __init__(self,*args, **kwargs): print("Exposure List View initiated") super(ExposureListView, self).__init__(*args, **kwargs) def get_queryset(self): try: print('get query set is called') self.exposure_user = User.objects.prefetch_related('exposures').get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: print("I was here") raise Http404 else: return self.exposure_user And when I run the code in debug mode I end always in the __init__() of ExposureDetailView and not in ExposureListView. If I want to see the details of some … -
django wsgi error no module found named site name
When I run the command uwsgi --http :8081 --gevent 100 --module websocket --gevent-monkey-patch --master -H env/ I get error No python application found and when I specify the path to the wsgi.py file, uwsgi --http :8081 --gevent 100 --module websocket --gevent-monkey-patch --master -H env/ --wsgi-file /Users/ishansrivastava/Desktop/ChatApp/Chatire/chatire/wsgi.py`, I get ModuleNotFoundError: No module named 'chatire' DAMN ! worker 1 (pid: 77847) died :( trying respawn ... Respawned uWSGI worker 1 (new pid: 77851) *** running gevent loop engine [addr:0x104312c00] *** Traceback (most recent call last): File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/gevent/monkey.py", line 611, in patch_all patch_thread(Event=Event, _warnings=_warnings) File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/gevent/monkey.py", line 348, in patch_thread _patch_existing_locks(threading_mod) File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/gevent/monkey.py", line 263, in _patch_existing_locks if isinstance(o, rlock_type): File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/django/utils/functional.py", line 215, in inner self._setup() File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/ishansrivastava/Desktop/ChatApp/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked When I cd into the directory chatire and run … -
Display difference user profile images
I was wondering how I could upload a picture to a user account and display it in their profile and do the same with multiple users I have not rewritten the code yet -
Django: migrate fails, but migrating in 2 steps succeeds
I currently have a nasty problem with Django migrations. I refactored models inside a new Django app, but specified the db_table attribute in their Meta classes to use the old tables, because they are already running in Production. However, now I added a new field to such a moved model, and migrating fails with state.models[app_label, self.model_name_lower].fields.append((self.name, field)) KeyError: ('crm', 'contact') The strange thing is that running ./manage.py migrate crm 0001_initial, and afterwards running the usual ./manage.py migrate gives no error at all! Why is this happening? Does anyone have a clue? Can include migration code if necessary. -
Stripe recurrent charges for 3D secured cards (not subscription or billing)
I want customer to pass 3D secure process only once. Then his future charges should be proceeded without doing 3d secure process. Is it possible in stripe? It is not clear from documentation. If it is possible then what is wrong my flow? Add card to customer and get card source id Create 3d source id using customer id and card source id source = stripe.Source.create( amount=1099, currency="eur", type='three_d_secure', three_d_secure={ 'card': card source id, 'customer': customer id }, redirect={ 'return_url': 'https://shop.example.com/crtA6B28E1' }, ) Then by passing to url I do 3d secure authentication, and 3d secure source authenticated becomes "true". I make charge using 3d secure source id and customer id and it succeeds. charge = stripe.Charge.create( amount=1099, currency='eur', customer=customer id, source='3d secure source id' ) Then I try to make charge using just customer and it fails. charge = stripe.Charge.create( amount=1099, currency='eur', customer=customer id ) -
Spliting all three attributes of this list
[8352] Marilyn Hudson - 16000 Views This is instance that i get from FacebookAdsAPi I have been trying separate list in to 3 attributes seperately. I have used client.split("]")[1] But it gives me Marilyn Hudson - 16000 Views. TIA -
How can I get a send a file created by javascript, to server and then handle it by django, for emailing?
My javascript code: function PrepareEmailPrescription() { doc = PreparePrescriptionPDF() var pdf = doc.output(); var fd = new FormData(); fd.append( 'file', pdf ); $.ajax({ url: `/clinic/${cliniclabel}/prescription/sendemail/patient/${patient_id}`, data: fd, processData: false, contentType: false, type: 'POST', success: function(data){ alert(data); } }); } Here, PreparePrescriptionPDF is a function which generated a pdf file with pdfjs. On the django server, I have: def SendPrescriptionbyMail(request, cliniclabel, patient_id): # print(request.body) print(request.FILES) print(request.FILES['file']) return HttpResponse('Successfully sent email') I am getting the following response from django: [14/Nov/2018 15:59:18] "GET /clinic/medicines HTTP/1.1" 200 8389 <MultiValueDict: {}> 2018-11-14 15:59:22,344 django.request ERROR Internal Server Error: /clinic/madhav/prescription/sendemail/patient/18 Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 77, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joel/myappointments/clinic/views.py", line 4911, in SendPrescriptionbyMail print(request.FILES['file']) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 79, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'file' However if my javascript code becomes: function PrepareEmailPrescription() { doc = PreparePrescriptionPDF() var pdf = new Blob(['abc123'], {type: 'text/plain'}); var fd = new FormData(); fd.append( 'file', pdf ); $.ajax({ … -
Django admin TabularInline with custom form
I want to use TabularInline for my model-admin with a custom form and extra=3. But the problem is that when I hit save in my admin page, the form gives validation error on empty extras that I didn't use and can't save the models I wanted to create. I read the docs in django and can't quite understand the solution to my problem. The reason I want to use a custom form is that I'm using custom widgets for some of the fields. So there may be a better solution for my needs than using a custom form which I'm not aware of. I'm using Django v2.0 and here's the code for my admin: class BingilForm(forms.ModelForm): class Meta: model = Bingil fields = '__all__' widgets = { 'position_top': RangeInput(), 'position_left': RangeInput(), 'background_color': ColorInput(), 'foreground_color': ColorInput(), } class InlineVideoBingil(admin.TabularInline): model = Bingil fk_name = 'video' form = BingilForm extra = 3 show_change_link = True -
NoReverseMatch at / Reverse for 'dashboard' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[^/]+)\\/$']
I get this error NoReverseMatch at / Reverse for 'dashboard' with no arguments not found. 1 pattern(s) tried: ['(?P[^/]+)\/$']. After a users clicks the login button its expected that the url should redirected to 'domain/username.html', after it has been authenticated and move to the dashboard.html page. login1.html {% load custom_filters %} <a href="" class="btn-back-sign-up" id="dismiss" id="sign-up"> <i class="fa fa-chevron-left"> &nbsp;SIGNUP</i> </a><br><br> <p class="text-join">Join our community that have more than 10,000<br> subscribers and learn new things everyday.</p> <div class='back' id='login_form'> <form id='login-form' method='post' {% url 'accounts:dashboard' %} ><br> {% csrf_token %} {% for field in form %} {% if field.errors %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% endif %} <div class="form-group"> {{ field.label_tag }} {{ field|add_class:'form-control'}} </div> {% endfor %} <div class="form-group"> <input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username" required id="id_username"><br> <input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password1" required id="id_password"><br> <button type="submit" value='Login' id="top-login-btn" class="btn btn-primary btn-block btn-signup-form-1">LOGIN</button> <p class="text-center">or</p> <button type="button" class="btn btn-primary btn-block btn-sign-linkedin-1">Login up with LinkedIn</button> <p class="text-already">Don't have an account? <a href="" data-toggle="modal" class="btn-back-sign-up" data-target="#modal-signup" id="dismiss" id="sign-up">Sign Up</a> </p> </div> </form> </div> <p class="text-already"><a href="{% url 'password_reset' %}">Forgot Password?</a></p><br> views @login_required def dashboard(request, username): """Dashboard page … -
Django: PasswordInput is empty
I have a simple Django model: class Remote(models.Model): password = models.CharField(max_length=256, blank=True) and admin.py: class RemoteForm(forms.ModelForm): class Meta: widgets = { 'password': forms.PasswordInput(), } class RemoteAdmin(ForStaffModelAdmin): form = RemoteForm admin.site.register(Remote, RemoteAdmin) If I open the change_view for an instance in the django admin, then the password field is empty. I checked the db: the instance has a password. Why is PasswordInput empty? -
Wagtail + Django problem - page is redirecting to wagtail although the url is not for the wagtail page
url(r'^$', views.HomePage.as_view(), name='homepage'), class HomePage(RedirectView): def get(self, request, *args, **kwargs): print('check') return render(request, url) And this is the html: <a href="{% url 'public_portal:homepage' %}"> although, I get a page with full design of wagtail Page model I have. Anyone knows why is it happening? -
Render enums as dropdown in django-rest-swagger
I am trying to get the right query parameters shown in the swagger documentation produced by django-rest-swagger from rest_framework.filters import BaseFilterBackend from rest_framework.compat import coreapi, coreschema from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from enum import Enum class MyChoices(Enum): ONE = 'ONE' TWO = 'TWO' class KeyFilter(BaseFilterBackend): key_param = 'key' default_key = 'psc' key_title = _('Key') key_description = _('Specify the aggregation key.') def filter_queryset(self, request, queryset, view): key = request.query_params.pop(self.key_param, [self.default_key])[0] return ConsumptionAggregate(queryset).aggregate(key) def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( name=self.key_param, required=False, location='query', schema=coreschema.Enum( MyChoices, title=force_text(self.key_title), description=force_text(self.key_description) ) ) ] But that is not being displayed as a dropdown. How can we have choices being rendered as dropdowns? -
How to manipulate the name and the value of a textfield if it is autogenerated in Django
In my scenario within a form in my template I have two div parts. In the first div there is a name="products__contains" so I can easily refer to selected item when i deal with a POST request. <div class="form-group col-md-12"> <select id="products__contains" name="products__contains" class="form-control product"> <option disabled selected>Select Product:</option> {% for p in products %} {% if p %} <option value="{{p}}" {% if p == request.GET.products__contains %}selected="selected"{% endif %}> {{p|capfirst}} </option> {% endif %} {% endfor %} </select> </div> In my second div, which implemented based on autocomplete there is no name to refer to. <div> {% csrf_token %} {{ form.product_name }} </div> <script type="text/javascript" src="<script type="text/javascript" src="static/admin/js/vendor/jquery"></script> {{ form.media }} My purpose is to create same urls when posting something. When using the first solution with date and product selected I can create a url looking like: www.example.com:port/shops/rest_new/?date=2018-11-13&products__contains=10+HERBS+COLON+CLEANSE+30tav When using the second solution with date and product selected from the autocomplete textfield(loads the list of the products) I can create a url looking like: www.example.com:port/shops/rest_new/?date=2018-11-13&categories__contains=1.ALFA&csrfmiddlewaretoken=QZmVRfHpFrmDEHsKysX60drdkVgbZWcOrhJTtj5G4u0h9eL1MOdBBt8Xw17iwsMg&product_name=22# which is not what I want since it has a csrf reference and the product_name refers to id and not to the name of the product as I would like to. In both examples … -
Django Rest framework Change password
//models.py class UserManager(BaseUserManager): def create_user(self, email, name, password=None): if email is None: raise TypeError('email is empty') user = self.model(email=email, name=name) user.set_password(password) user.save(using= self.db) return user class UserProfile(AbstractBaseUser, PermissionMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=500) password = models.CharField(max_length=300) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = UserManager() //views.py class UserAPIView(viewsets.ModelViewSet): permission_classes = (IsOwnerOrReadOnly,) serializer_class = RegistrationSerializer queryset = UserProfile.objects.all() def post(self, request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) //serializers.py class RegistrationSerializer(serializers.ModelSerializer): class Meta: extra_kwargs = { 'password' : { 'write_only' : True }} model = UserProfile fields = ('id','email','name','password','is_staff') def create(self, validated_data): return UserProfile.objects.create_user(**validated_data) This is a portion of my app. I need to set a patch() or update() function in this app so that it should be update the password field correctly, ie., password field must be hashed using set_password()