Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Whats the correct structure for Django templates?
I have a project in Django called: "my_site", and an app called "blog", I'm trying to render the "index.html" inside the path: my_site/blog/templates/blog/index.html. But keep getting this error: Template-loader postmortem Django tried loadi ng these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\blog\templates\index.html (Source does not exist) The view: def index(request): return render(request, 'index.html') the urls.py: urlpatterns = [ path('', views.index), path('posts', views.show_all_posts), path('posts/<slug:slug>', views.show_post) ] If i move the index.html outside the blog folder, like in this example: my_site/blog/templates/index.html the code runs and the index.html renders without problem, but i was taught that the correct structure is to create a folder inside templates with the same name of the app. So could anyone please explain me the way i should structure my files? -
Django REST Framework; ImproperlyConfigured; Could not resolve URL for hyperlinked relationship
Am trying to use DRF to make an election tracker; getting on what was supposed to be fairly simple ViewSet list and retrieve endpoints; django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "election-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Model Snippet... class Election(models.Model): _id = models.CharField( name="id", primary_key=True, validators=[election_ids.validate], max_length=32 ) date = ComputedDateField(compute_from="_date") # not relevant parent = models.ForeignKey( to="self", on_delete=models.CASCADE, default=None, null=True ) Serializers class ElectionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Election # Removing the 'url' from below stops the ImproperlyConfigured error on retrieve calls fields = ["url", "org", "date", "constituency", "parent"] read_only_fields = ["url"] depth=1 ViewSet class ElectionViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint that allows elections to be viewed or edited. """ lookup_field = 'id' lookup_value_regex = '[a-z0-9.\-_]+' # this might be the culprit, see below queryset = Election.objects.all().order_by("-date") serializer_class = ElectionSerializer permission_classes = [permissions.AllowAny] and relevant urls.py app_name = "counts" api_router = routers.DefaultRouter() api_router.register(r"users", UserViewSet, "users") api_router.register(r"groups", GroupViewSet, "groups") api_router.register(r"elections", ElectionViewSet, "elections") api_router.register(r"candidates", CandidateViewSet, "candidates") api_router.register(r"stages", StageViewSet, "stages") # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", … -
Is it possible to use f-strings with Concat(), Value() and F()
I have a varchar column whose values I would like to update. Here is what I have tried so far: for item in Item.objects.filter(): some_items = get_some_items(item) Item.objects.filter(field=item.field).difference(some_items).update( field=Concat( Value(settings.PREFIX), Value(f"{F('id'):>010d}") ) ) Which gives me TypeError: unsupported format string passed to F.__format__ I need help on how I can achieve this if possible. -
Filtering numbers from a django list
In my database I have a list of users, each one has an id, this id is CharField, it can contain either a string containing a number (e.g "058") or a string containing something like this "0Y5" I want to filter the list of users to have only the ones that have an id that contain a valid number, like "005", "011", "122", I tried this but it seems not working: users = User.objects.filter(id.isnumeric == True) -
Django Models objects cannot find declaration to go to
I have a simple django app. Inside the models.py folder i have: class TestModel(models.Model): name = models.CharField(max_length=300) def get_all(self): all = TestModel.objects.all() return all Even though I have instances of TestModel in my database (PostgreSQL), the function get_all returns None. PyCharm helped me in narrowing down the problem by marking objects and telling me that it Cannot find a declaration to go to. If I create the project with PyCharm Professional through the UI, this problem does not occur. As soon as I open the application through PyCharm Community, the problem appears and does NOT go away by switching back to Professional. Django version - 3.2.9 and 4.0.0 tested Questions: How to make the Django recognize objects by using PyCharm Community? What is the cause for this strange behaviour? -
Exporting a django template table to xlsx
I'm trying to use django template for the first time and I need to export some data. How can I export a table in my django template to a .xlsx file? Is there any method? here is my views.py: from django.shortcuts import render import requests from .utils import most_frequent, get_json_values, get_max_dict def launches(request): """main request. Retrieve the year that had most launches""" response_launches = requests.get('https://api.spacexdata.com/v3/launches? filter=launch_year') launches = response_launches.json() launch_years = get_json_values('launch_year',launches) result_launches = most_frequent(launch_years) """retrieve the launch site most used for launches """ response_sites = requests.get('https://api.spacexdata.com/v3/launches? filter=launch_site') sites = response_sites.json() launch_sites = get_json_values("launch_site", sites) result_sites = get_max_dict(launch_sites,'site_id') """retrieve the number of launches between 2019 and 2021""" response_2019_2021 = requests.get('https://api.spacexdata.com/v3/launches? start=2019&end=2021') launches_2019_2021 = response_2019_2021.json() result_2019_2021 = len(launches_2019_2021) data = { "year_most_launches": str(result_launches), "launch_sites":result_sites, "launches_2019_2021":str(result_2019_2021) } return render(request,"main/launches.html", {"data":data}) And that's my table inside my template: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> <tr> {% for element in data.values %} <td>{{ element }}</td> {% endfor %} </tr> </tbody> </table> I couldn't find a way to do it so any help is really appreciated! -
No module named 'application' deploying Django 4.0 to AWS Beanstalk
When I try to deploy my project to AWS beanstalk I keep on getting the same error in my logs "ModuleNotFoundError: No module named 'application'". Because of this I get 502 Bad Request errors. I am using Django 4.0. The application runs fine when I run "python manage.py runserver" on the virtual-env. I have followed all the steps described in the tutorial which Amazon provides, yet without success. Of course I have added my server to the ALLOWED_HOSTS, but I don't think that is the problem. Is there something that changed in Django 4.0.4 that could've changed things? In my .elasticbeanstalk/config.yml file I have the line "default_platform: Python 3.8 running on 64bit Amazon Linux 2", which should be compatible with Django 4.0.4. One other thing I have tried is following the same steps from the tutorial again on a new region, with a new application and environment, but this was also not successful. My .ebextensions/django.config file is the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: nameofmyproject.wsgi:application The WSGIPath refers to the wsgi, which is located in nameofmyproject/wsgi.py, which looks like the following: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nameofmyproject.settings') application = get_wsgi_application() -
Accessing a field from a model linked to another model with get_context_data()
I have the following models in my Django app: Model User class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=30, blank=True) email = models.EmailField('Adresse mail', unique=True) first_name = models.CharField('Prénom', max_length=30, blank=True) last_name = models.CharField('Nom', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) company = models.ForeignKey('Company', on_delete=DO_NOTHING, blank=True, null=True) Model Company class Company(models.Model): name = models.CharField(max_length=200, blank=False) transporters = models.ManyToManyField(Transporter, blank=True) Model Transporter class Transporter(models.Model): name = models.CharField(max_length=100) avatar = models.ImageField(blank=True, null=True) Model Supplement class Supplement(models.Model): transporter = models.ForeignKey(Transporter, on_delete=DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=DO_NOTHING, blank=True, null=True) header_row = models.IntegerField(blank=True) Starting from the user, I would like to access the field header_row in get_context_data(). In my app, the user belongs to a company and the 'supplement' is attached to a Company. Here's what I came with in views.py : class UserSupplementView(TemplateView): model = User template_name = 'tool/try.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.request.user context['supplements'] = user.company.supplement.header_row print(context['supplements']) return context But it's not working and I have the following error message: 'Company' object has no attribute 'supplement' But if I go with context['supplements'] = user.company.supplement_set.all() , I can actually retrieve part of the data. Could you please help me to retrieve the header_row field? -
Chart JS Angular how to display list of data in a line chart
Its my first time using any chart in programming so sorry if this is really simple and im just being an idiot. So I have created a really basic chart using ChartJS in angular. loadChart(): void { new Chart(this.chart,{ type:'line', data: { datasets: [ { data:data:[30, 60, 40, 50, 40, 55, 85, 65, 75, 50, 70], label:"Series 1", backgroundColor: '#007bff', tension: 0.3, } ], labels:['17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', ], }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true, } } } }) } I have a get method to my rest api that responds with a bunch of data such as these detections. [ { "DetectionId": 2, "CityId": 2, "TimeUpdated": "2018-11-20T21:58:44.767594Z", "FPercent": 22, }, { "DetectionId": 3, "CityId": 2, "TimeUpdated": "2016-11-20T21:58:44.767594Z", "Percent": 22, } ] How can I add this data to my chart so that it displays each detection as a dot on the line graph. Ideally I would like to plot percent on the Y axis and Timeupdated on the x axis. Any help or advice would be greatly appreciated I've tried a few tutorials but none have worked so far. Also is there any way I can … -
DJango testing multiple database application
I have django application which has two database defaultdb and externdb DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, 'TEST': { 'NAME': 'test_{0}'.format(config("DB_NAME")), 'MIRROR': "default", }, }, 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DB_EXTERN_NAME"), 'USER': config("DB_EXTERN_USER"), 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': config("DB_EXTERN_HOST"), 'PORT': config("DB_EXTERN_PORT"), 'TEST': { 'NAME': 'test_{0}'.format(config("DB_EXTERN_NAME")), 'MIRROR': "extern", }, } } The application works well but when testing ,this error occurs below when trying to access the extern database from extern_db.models import TBasicInfo class HelpViewTest(TestCase): def test_api(self): tb = TBasicInfo.objects.get(info_id=10352) This error occurs AssertionError: Database queries to 'extern' are not allowed in this test. Add 'extern' to defapp.tests.HelpViewTest.databases to ensure proper test isolation and silence this failure. which setting should I check?? -
What are Django's "__init__.py" empty files for? [duplicate]
When i started with a Django template, I saw two __init__.py files. When I looked into, they was empty. What are they for? Or it was a mistake from the template creator? -
How can I fix an error creating newPost in django?
I'm trying to make a new post, but I get "Followers matching query does not exist" as an error. I don't know how to fix it. Could someone help me to solve it?. Attached files. All this done in Django. models.py class Followers(models.Model): user = models.ForeignKey (User, on_delete = models.CASCADE, related_name = "followers") follower = models.ManyToManyField (User, related_name = "following") def __str__(self): return f"{self.user}" class Post(models.Model): content = models.CharField (max_length = 280) created_date = models.DateTimeField (default = timezone.now) creator = models.ForeignKey (User, on_delete = models.CASCADE, related_name = "posts") likes = models.ManyToManyField (User, related_name = "liked_posts") def __str__(self): return f"{self.id}: {self.creator}" views.py @login_required def newPost(request): if request.method == "POST": form = Post (content = request.POST['content']) form.creator = Followers.objects.get (user = request.user) form.save() else: return render (request, "network/index.html") return HttpResponseRedirect (reverse("index")) newPost.html {% for post in posts %} <div class="card-body" style="border: 1px solid rgba(0,0,0,.1);"> <strong><a style="font-size: 20px; color: black;" href="#">{{post.creator}}</a></strong> · <a style="font-size: 14px;">{{post.created_date}}</a> <a href="#" style="font-size: 14px; float: right;">Editar</a> <br>{{post.content}} <br> <a href="#" style="color: black;"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16"> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 … -
Django: how to use "or" in django filter method?
i want to filter a model by a tuple, i dont know if that is the right sentence to use but i have a model that looks like this USER_COURSE_RATING = ( ("1.0", "1.0 - Poor"), ("2.0", "2.0 - Fair"), ("3.0", "3.0 - Good"), ("4.0", "4.0 - Amazing"), ("5.0", "5.0 - Excellent"), ) class Course(models.Model): course_title = models.CharField(max_length=10000) class CourseRating(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) rating = models.CharField(max_length=1000, choices=USER_COURSE_RATING, null=True, blank=True) and what i want to do in the views if to filter the CourseRating by the tuple i defined above called USER_COURSE_RATING i have written the view but it seems not to be working, NOTE: i am not getting any error message but it not working def course_detail(request, course_slug): rating_count = CourseRating.objects.filter(course=course, rating="3.0" or "4.0" or "5.0").count() So i want to only display the count if the rating was either 3.0, 4.0 or 5.0 that is what i am expecting -
How to save multiindex dataframe into Django JSONField?
I have a dataframe structure like this I would like to insert into a dictionary new_dic and then save in a Django JSONField. How can I do that ? dic = df.to_dict(orient='index') dic {'ABC': {('free', 'quantity'): 256.6964787, ('free', 'value'): 256.6964787, ('total', 'quantity'): 256.6964787, ('total', 'value'): 256.6964787, ('used', 'quantity'): nan, ('used', 'value'): nan}, 'DEF': {('free', 'quantity'): 0.029599199999999992, ('free', 'value'): 88.45099336799997, ('total', 'quantity'): 0.06789919999999999, ('total', 'value'): 202.90250036799998, ('used', 'quantity'): 0.0, ('used', 'value'): 0.0}} I'm able to assign the dictionary to a key 2022-04-22 and save the new dictionary in my Django model. Here, data is a field JSONField. new_dic = dict() new_dic['2022-04-22T15:00:00Z'] = dic w = MyModel.objects.get(name=name) w.data = new_dic w.save() w.data {'2022-04-22T15:00:00Z': '{"ABC":{"(\'free\', \'quantity\')":256.6964787,"(\'free\', \'value\')":256.6964787,"(\'total\', \'quantity\')":256.6964787,"(\'total\', \'value\')":256.6964787,"(\'used\', \'quantity\')":null,"(\'used\', \'value\')":null},"DEF":{"(\'free\', \'quantity\')":0.0295992,"(\'free\', \'value\')":88.450993368,"(\'total\', \'quantity\')":0.0678992,"(\'total\', \'value\')":202.902500368,"(\'used\', \'quantity\')":0.0,"(\'used\', \'value\')":0.0}}'} Everything looks fine, but there is a problem when the data is loaded with json.loads(). How can I do that ? json.loads(w.data) TypeError: the JSON object must be str, bytes or bytearray, not dict -
django bootstrap modal upade with another modal
I have modal with with table and trying to make this table editable - only add new content needed. Here is the first modal: first modal Once I click plus sign (+) it will open new modal with fields: second modal What I need is once fileds in 2nd modal are fulfilled and click "Submit" it should add it to table in first modal. Do you guys have and idea how to do it? -
How to create APIs using Python Django to fetch unread emails and send emails using gmail account(create one using your phone number)
Create APIs using Python Django to fetch unread emails and send emails using gmail account(create one using your phone number) The API should use Googles API i.e. (https://developers.google.com/gmail/api/guides/sending) NOTE: after fetching the emails make it read so in the next iteration the api doesnt pick it up again Deliverables: An API endpoint to send an email with some paramaters An API endpoint to fetch all unread emails -
Android Studio - How to select a file (PDF) and send it via HTTP request? + how to download it from Django backend
In my Java Android Studio app I want to let the user choose a PDF file that will be sent via an HTTP POST request to my local backend made in Django which saves the PDf file received to an postgreSQL database as a bytea data type. My backend should be ready to handle these requests, so I only need help with the Java Android Studio frontend. Many solutions that I found online used no longer supported functions, so I want to specify that the app is for Android 10 and higher I would also like to know how can I download these uploaded files from the database on back to my mobile device with a GET HTTP request. If you want to see some sections of my code just let me know. -
Django: How to use 1 form of 2 forms in one view?
I have app like this: enter image description here When I want to login, the data from username and password go to first form "Search friend or event" and I get a bad template. How to mark form to the suitable view? First form: def search_friend(request): if request.method == 'GET': search = request.GET.get('search') results = User.objects.filter(username=search) return render(request, 'friends/search_friend.html', {'results': results}) <div class="middlenavbar"> <form action="{% url 'search-friend' %}" method="GET"> <input id="middlesearchinput" type="search" placeholder="Search friend or event"> <button id="magniferbutton" type="submit"><i class="icon-search"></i></button> </div> Second form: login is from LoginView <div> <form action="{% url 'login' %}" method="POST" > {% csrf_token %} {{ form|crispy }} <div> <button type="submit">Login</button> </div> </form> <small > Need An Account? <a href="{% url 'register' %}">Sign Up Now</a> </small> </div> -
get last instance of model which contains request.user in manytomanyfield
I am building a BlogApp and I am trying to get the last instance of model in which request.user in ManyToManyField I have tried using models.py class Blog(models.Model): title = models.CharField(max_length=3000) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_likes') views.py def get_data(request): get_last_blog = Blog.objects.filter(likes__in=[request.user]).last() print(get_last_blog) But it is showing first instance not last. I have tried without list like likes__in=request.user but it shows 'User' object is not iterable I have tried many times but it is still not working. I am new in django. Any help would be much Appreciated. Thank You in Advance -
Pytest a function which contains a async function call
@app.task def function_a(num): //do somethings pass def function_b(a): //do something function_a.delay(a) return a @pytest.mark.django_db def test_function_b() a = function_b() // assert condition depends on the operation on function_a The conditions we are going to check in the test function is dependent the operations we did in the function_a how can we test this using pytest? -
How in django add ssl (https)?
how change http to https? Deploying django with docker compose. (Test database, Static file, Media file) Django + psycopg2 + uWSGI http for example: https://github.com/mazyargholami/django-docker version: "3.9" services: app: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${SECRET_KEY} - ALLOWED_HOSTS=${ALLOWED_HOSTS} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: context: ./proxy restart: always depends_on: - app ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } https? how add ssl certificate? or certbot? -
Django is not sending e-mails
guys! I have an issue with my Django project. About project: Django version: 3.0.7 Django hosting provider: Digitalocean E-mail hosting provider: Beget.com OS: Ubuntu 18.04.6 Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.beget.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'my@email.com' EMAIL_HOST_PASSWORD = 'MyVerySecretPassword' DEFAULT_FROM_EMAIL='my@email.com' Here is my views.py from django.core.mail import send_mail def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Please, activate your account by clicking the link below.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL, [to_email]) What I have tried to solve my problem: Using gmail account (yes, with anabled 'Allow less secure apps') Sending via Django shell (nope, it returns code '1', the mailbox is as empty as my ideas:( ) I have opened 587 and 465 ports in ufw I tried to write and run simple python smtp script to send e-mail via Django shell (spoiler: it worked perfectly on my server via shell), but when I tried to implement this code into my Django code, it failed just like Django send_mail() function: here is the code: import … -
for loop to populate a django template table
I'm trying to make a table in Django template. I'm sending a dict as my data inside my views.py like this: data = { "year_most_launches": result_launches, "launch_sites":result_sites, "launches_2019_2021":result_2019_2021 } return render(request,"main/launches.html", {"data":data}) My table in HTML code: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> {% for element in data.values %} <tr> <td>{{ element }}</td> </tr> {% endfor %} </tbody> </table> My problem is that the values of data just appears in the first columm, creating 3 rows instead of just appearing in the first row. How can I solve that? It is a problem inside my html? -
How to replace port 8000
I'm working on a project now and I'm currently using Django+uWSGI+Nginx to deploy the backend on the server. There is also a frontend using Vue.js on the same server. So the frontend is www.mysite.com The backend uses port 8000 as www.mysite.com:8000 But I encountered a problem, that is, many users' work network blocked port 8000, so that users could only use the front end, but could not connect to the back end. Is there any way to avoid using www.mysite.com:8000 and replace it with another url? -
django rest framework RetrieveUpdate
I'm now making user profile update API using drf with RetreiveUpadteAPIView there is one question I cant' figure out what the solution is. With this logic, request datas are well updated on DB. Only password given is set without hashed but just normal character. even that changed normal character password is also not matched as with i set. How can i fix it.. your best regard Here is my code below. #views.py @permission_classes([IsAuthenticated]) class UpdatePartialUserView(RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = UserProfileSerializer def get_object(self): queryset = self.filter_queryset(self.get_queryset()) obj = queryset.get(pk=self.request.user.id) self.check_object_permissions(self.request, obj) return obj def retrieve(self, request, *args, **kwargs): serializer = UserSerializer(request.user) return Response(status=status.HTTP_200_OK, data = serializer.data) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) self.object = self.get_object() serializer = self.get_serializer(request.user, data = request.data, partial=partial) # serializer = self.get_serializer(self.object, data = request.data, partial=partial) if not serializer.is_valid(raise_exception=True): return Response(status=status.HTTP_409_CONFLICT, data = {'message':serializer.errors}) self.perform_update(serializer=serializer) self.object.set_password(request.data['password']) self.object.save() return Response(status=status.HTTP_202_ACCEPTED, data={"message": "success!"}) #serializers.py class UserProfileSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) profile_img = serializers.ImageField(use_url=True, required = False) def validate(self, attrs): if attrs.get('password') != attrs.get('password2'): raise serializers.ValidationError({ "password" : "비밀번호가 다릅니다."}) return attrs def validate_old_password(self, value): #check user request = self.context.get('request') if request and hasattr(request, "user"): user = request.user …