Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrations files for large project in git (Best Practice)
I work with a team in Django project, in the local git with same database. we found that there was a lot of problems with django migrations specially when the team is large. So we decided to make databases for each developer, sometimes the developer delete them migrations files to solve some problems with migrations. we get a lot of the conflict in Django migrations files, we decided to add migrations files to gitignore. Then all the work become more smoothly. but we get some problems we lost the git history for migrations files, this gives problems at updating the project versions from the specific git tag. Also, it will delete the migrations files at every time we make "checkout" in git. I suggested the following but I did find its answers make migrations files tracked by local repository and ignored in the remote repository. Any one have forced this issue? -
Django - In a ModelForm, display data coming from a model linked with M2M relationship
I built a form for a model, including a field coming from another model linked with a M2M relationship. The form works properly, but I would like to add detailed data from this other model and I did not success. The main model is Event and it's linked to Groups thanks to this relationship; in the form, all groups are listed and displayed with checkboxes, but I'm only able to display the groups' name, no other information. It looks like I miss some data / information: the group name is displayed only because I use {{grp}}} (see below) but it has no attribute / filed available, even if it is initialized with a query from the group model. Any idea of what I did wrong, or any advice to manage this? Thanks in advance. Here are related code parts. Models: class UserGroup(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) users = models.ManyToManyField(UserComp, verbose_name="utilisateurs", blank=True) group_name = models.CharField("nom", max_length=100) weight = models.IntegerField("poids", default=0) hidden = models.BooleanField(default=False) def __str__(self): return self.group_name class Event(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) groups = models.ManyToManyField(UserGroup, verbose_name="groupes", blank=True) rules = [("MAJ", "Majorité"), ("PROP", "Proportionnelle")] event_name = models.CharField("nom", max_length=200) event_date = models.DateField("date de l'événement") slug = … -
Can you render form fields based on index number in Django?
Let's say I want to render the last three fields of the following form: {{ form.field1 }} {{ form.field2 }} {{ form.field3 }} {{ form.field4 }} In Python, I would access numbered items from a list by using something like: form[1::1] Of course, the field in an object with attributes, so a method like getattr is the most similar. My question is - is there any way to access selected form fields in a Django template? Something that would allow me write a for loop for one range of form fields, and another for another? In python what I want would look like this in a list: for field in form[0:10:2]: return field for field in form[11:21:2]: return field etc -
Django 502 Bad Gateway on GET a single profile
Problem Http: 502 Bad Gateway And error: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } Context Django App with HomePage and UserDetail. Login with two different users, both with same API Key and their own JWT: Ok User: Can access home page and account detail. Error User: Can access home page but can't access account detail. Question Why only this particular user can't access his own account detail? -
Can a consumer pull messages from RabbitMQ like it would retrieve the first item in a normal queue data structure?
From the documentation of RabbitMQ, I am currently left with the impression that as soon as a message arrives in the queue, it gets sent to a consumer for processing. What I would like to have is the ability for the consumer to decide on his own when he is ready to get and process the next message in the queue. Is this possible? My program generates a big amount of messages (around 3000) at once and is supposed to store them in a queue. (around 2-3 times a day) From this queue, a function is supposed to get the first message, calculate if a condition is met and if that is true, start a process on another server and only then retrieve the next message. If not, it should wait a small amount of time and try again with the same message as before. I am not interested in concurrency, quite the opposite, the application must be sequential. Can I achieve this with RabbitMQ? -
xml sitemap in django isn't showing the website urls
i am building sitemap in django, this my siteemaps.py from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse class StaticViewSitemap(Sitemap): def item(self): return ['home','blogurl','progurl','post_detail_url',] def location(self,item): return reverse(item) when i run the sitemap.xml, the urls are not appearing. enter image description here -
Pandas DataFrame table's styling in Django view
In a Django application I create a DataFrame, later on I transform it to html and pass to the view table = df.to_html(index=False) return render(request, 'results.html',{'table': table}) In results.html I add that table {{ table|safe }} And I get this table. Table in Django's view. Is there a way to add styling to it in the template? I would like to add some spacing between text and borders, as well as making titles for the columns centered. -
how to get javascript variables into django url
<a href="{% url 'main:projectdata' proname=pro.projectname n=state %}"></a> <script> var state = 'Done'; </script> how to pass javascript variable state into the django url in the line above when it change -
Is celery recommended for email sending only?
I have an api with django rest framework. The api is for user signup. After signup api will send verification email to the user but sending email takes a little time so for this purpose i want to send email in background. For this requirement what should be the approach ? -
How to upload Files in django to your desired Folder
model.py class Thread(models.Model): user = models.Foreignkey(User, on_delete=models.CASCADE) Title = models.CharField(max_length=30) Media = models.ManyToManyField("Files", on_delete=models.CASCADE) class Files(models.Model): File = models.FileField(upload_to="thisFolderDoesNotMatter/") in forms.py class ThreadForm(ModelForm): Files_Form_Label = forms.FileField(widget=forms.CleatableFileInput(attrs={'multiple':True})) class Meta: model = Thread fields = ("Title",) in views.py from django.views import View class NewThread(View): template_name = 'Thread/New.html' def get(self, request, id): return render(request, self.template_name, context={ 'form':ThreadForm(), 'data':Thread.objects.get(pk=id) }) def post(self, request): form_data = ThreadForm(request.POST, request.FILES) all_files = request.FILES.getlist('File_Form_Label') if form_data.is_valid(): new_thread = form_data.save(commit=False) new_thread.user = request.user new_thread.save() for f in all_files: file = Files(File=f) here is the problem that i want to upload this file in MEDIAROOT/request.user.username/new_thread.id/ ANY method to do this ? file.save() new_thread.Media.add(file) new_thread.save() return HTTPResponse('SUCCESSFULL') i Dont know how to use instance method in ManyToManyField.. -
Using **kwargs, a dictionary from views was not successfully pass to a function in models properly
I am trying to pass a dictionary in views to a function in models and using **kwargs to further manipulate what i want to do inside the function. I try to call the dict before passing it in to the function. The data is there. The moment the dict was pass to the function (isAvailable) the kwargs is empty. Here are the code snippets from views.py. def bookingAvailable(request): available = isAvailable(data=request.data) Here are the code snippets from models.py def isAvailable(**kwargs): bookedDate = kwargs.get('bookedDate') customerID = kwargs.get('customerID') cpID = kwargs.get('cpID') request.data is populated with data in a dictionary form. But the moment it got in to **kwargs everything is gone. Not so sure what happen in between. Any help is appreciated! -
Search database based on name with multiple returns. django
Hello guys am building a search tool for postgres in django and am getting a lot of errors my output is in this way. <QuerySet [<Bindll: HIV-1 protease>, <Bindll: HIV-1 protease>, <Bindll: HIV-1 protease> my code is #Search resuts page. {% extends 'Search/base.html' %} {%block content %} <center> <br/><br/><br/><br/> <h1>{% if ChemSearched %} {{ChemSearched}} <br> <br> {% for Bindll in tarname %} {{tarname}}<br> {% endfor %} </h1></strong> {% else %} <strong>No Entry</strong> {% endif %} Copyright (c) </center> {% endblock %} My database name in Bindll. #Views.py page from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Bindll def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = Bindll.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched) return render(request, 'Search/search_result.html', {'ChemSearched':ChemSearched,'tarname':tarname}) else: return render(request, 'Search/search_result.html',{}) using Postgresql and gitbash if related. Thanks in advace. -
hello im getting can only concatenate str (not "NoneType") to str error
hello everyone i'm having this error (can only concatenate str (not "NoneType") to str). my code is: from django.db import models from django.db import models from django.db.models.fields import CharField from datetime import datetime from django.contrib.auth.models import User # Create your models here. # Create your models here class features(models.Model): name = models.CharField(max_length=100) details = models.CharField(max_length=500) class post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title + ' | ' + self.author I did the migrations and everything and in the admin page everything is working bit the post page here is what the error syas entirely: TypeError at /admin/myapp/post/ can only concatenate str (not "NoneType") to str Request Method: GET Request URL: http://127.0.0.1:8000/admin/myapp/post/ Django Version: 3.2.9 Exception Type: TypeError Exception Value: can only concatenate str (not "NoneType") to str Exception Location: E:\Web-dev\python\newapp\myapp\models.py, line 21, in __str__ Python Executable: E:\web-dev\venva3.9\Scripts\python.exe Python Version: 3.9.9 Python Path: ['E:\\Web-dev\\python\\newapp', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\python39.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Pedro\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'E:\\web-dev\\venva3.9', 'E:\\web-dev\\venva3.9\\lib\\site-packages', 'E:\\web-dev\\venva3.9\\lib\\site-packages\\win32', 'E:\\web-dev\\venva3.9\\lib\\site-packages\\win32\\lib', 'E:\\web-dev\\venva3.9\\lib\\site-packages\\Pythonwin'] Server time: Thu, 25 Nov 2021 17:32:43 +0000 Error during template rendering In template E:\web-dev\venva3.9\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 53 can only concatenate str (not "NoneType") to str -
Quisiera saber como llamar al usuario User , despues de haberlo registrado con el formulario Usercreationforms para hacer un crud con este Usuario
Esto es lo que tengo en mi archivo forms.py forms.py <--------------- from django import forms from django.forms import ModelForm from django.forms import widgets from .models import Departamento, Location from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField() class Meta: model = User fields = ('first_name','last_name', 'username', 'email', 'password1' ,'password2' ) pass Asi se ve el template donde se renderiza el registro de usuario (resitro.html) {% extends 'app/index.html' %} {% block contenido %} <div class="col"> </div> <!--================ Latest Blog Area =================--> <section class="latest_blog_area section_gap"> <div class="container"> <div class="section_title text-center"> <h2 class="title_color">Registro</h2> <p>Registra una sesion.</p> </div> <div class="row mb_30 justify-content-center"> <div class="col-lg-4 col-md-6"> <form action="" method="post"> {% csrf_token %} {% load crispy_forms_tags %} {{form|crispy}} <input type="submit" value="enviar" class="btn theme_btn"> </form> </div> </div> </div> </section> {% endblock contenido %} y Esto es lo que estoy intentando hacer para llamarlo y tratar de modificarlo si alguien me puede orientar como hacerlo se lo agradeceria mucho from django.contrib.auth import get_user_model from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from app.forms import * from app.models import Location,Departamento from django.contrib.auth.models import User def modificarUser(request, id): user = get_object_or_404(User, id=id) data={ 'form':CustomUserCreationForm(instance=User), … -
User photo does not load in edit
I'm working on a user registration form. In this form there is an ImageField field for the user to upload his photo there. The point is that this ImageField only exists in forms.py, in models. py the photo is saved in a BinaryField called photo. In my views.py when saving the form I transform this image into base64, save the image in the photo field and save the form. So far so good, I can save the form. The problem is to edit this user form, how do I upload this photo for the user to view it in the template? models.py: class User(models.Model): photo = models.BinaryField(null=True, blank=True) forms.py: class UserForm(forms.ModelForm): image = forms.ImageField(required=False, label='Photo') views.py: if form.is_valid(): if form.cleaned_data['image']: user = form.save(commit=False) user.photo = base64.encodestring(form.cleaned_data['image'].file.read()) user.save() -
Django Form is not updating the database
I am making a form website. but my inputs are not being added to the database. It worked before but not anymore. the last change I made that stopped it from working was the URL from my form so it could go to another page when I submit the form. my html template was like this <div class="form-container"> <form enctype="multipart/form-data" action="/succes/" method="POST"> ..... after I added this it stopped working after adding the {%url 'Form:thank'%} everything went down hill. <div class="form-container"> <form enctype="multipart/form-data" action="{%url 'Form:thank'%}" method="POST"> ...... I am honestly lost right now. and don't know how to fix this. I am a beginner Django developer (so maybe I missed something) urls.py app_name = 'Form' urlpatterns = [ path('', FormPage, name = "Home"), ] of course I removed the thanks page to revert to what i had before. And the thanks page was working. if you are wondering models.py class Form(models.Model): company_name = models.CharField(max_length=200, null=False, blank=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) AIB_number = models.CharField(max_length=100) position_title = models.CharField(max_length=200) telephone = models.CharField(max_length=20) email = models.EmailField() job_duties = models.TextField() access_justification = models.TextField() wap_roa = models.CharField(max_length=255) required_access = models.CharField(choices=RequestAccessChoices, max_length=200) start_time = models.DateField(blank=True, null=True) end_time = models.DateField(blank=True, null=True) main_communications_room = models.ManyToManyField(MainCommunicationRoom, blank=True) new_terminal_building … -
Django celery + Redis transport - infinite loop, default debug_task works
Can't spot the bug. Django 2.2, celery 5.2.1, name of project = sharp. Also tried shared_task decorator instead of app.task, same situation. Default debug_task (see below) works fine. My celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sharp.settings') app = Celery('sharp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') __init__.py same as on official celery page. Settings: CELERY_BROKER_URL = 'redis://default:xxx@172.31.34.124:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Paris' My task: from sharp.celery import app @app.task(name='sendit') def _send_email_messages(recipient_email, messages, from_email, attachments): print('x') # not important stuff, just to have something here Infinite loop follows my output is: [2021-11-25 10:55:08,130: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2021-11-25 10:55:08,132: DEBUG/MainProcess] | Worker: Building graph... [2021-11-25 10:55:08,133: DEBUG/MainProcess] | Worker: New boot order: {StateDB, Timer, Hub, Pool, Autoscaler, Beat, Consumer} [2021-11-25 10:55:08,144: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2021-11-25 10:55:08,145: DEBUG/MainProcess] | Consumer: Building graph... [2021-11-25 10:55:08,181: DEBUG/MainProcess] | Consumer: New boot order: {Connec tion, Events, Heart, Agent, Mingle, Gossip, Tasks, Control, event loop} -------------- celery@ip-172-31-16-245 v5.2.1 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-4.19.0-18-cloud-amd64-x86_64-with-glibc2.2.5 2021-11-25 10 :55:08 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: sharp:0x7f250ffbdd00 - ** ---------- .> transport: redis://default:**@172.31.34.124:6379// - ** ---------- … -
Make Django admin `filter_horizontal` widget disabled
I have a question regarding admin customization For example I have a following model with m2m on itself via through model class Company(models.Model): some fields here… more fields … known_carriers = models.ManyToManyField( "self", through=’OtherModel’, through_fields=('field1', 'field2'), related_name='known_customers', symmetrical=False, ) and admin on this model @admin.register(models.Company) class CompanyAdmin(admin.ModelAdmin): … … filter_horizontal = ( ... 'known_carriers', ... ) … ... known_carriers in this admin is rendered as a nice widget specifying on a left side list of available model instances to add to m2m and on a right side ones have already added. Question is – is it possible to render same widget in admin but disabled, that is without possibility to move elements from left to right side and in opposite direction by mouse click or by clicking on arrows. Only nice representation is needed. Thank you. -
Jinja2 using {% include 'XXXXX' %} variables
I`m not sure how to explain this. At work we didnt get any training on this and the supplier is a bit crap. we were told we are using Jinja2. we can create what we call a "block" in Jinja code using already existing variables. once we created these blocks from jinja2 code we can reference them with an "include" statement. In my case this variable I created is a date. I want to create a new block using and formatting this variable. How could I use the below in another statement? {% include 'eme_sa_post_booking_personalisation_startdate_formatted' %} This will return 15/01/2022 for example based on existing criteria I can use I want to format this date from the include statement by specific languages. so lets say : {%- if -included variable- and contact.language in ('EN','FR','IE','SP','IT','FI') -%} {{ -include variable-|format_date('dd/MM/yyyy') }}{#-EN,FR,IE,SP,IT,FI have their date as 01.12.1900-#} {%- elif -included variable- and contact.language == 'HG' -%} {{ -included variable-|format_date('yyyy.MM.dd.') }}{#-HG have their date as 1900.12.01. -#} {%- elif -included variable- and contact.language == 'SW' -%} {{ -included variable-|format_date('dd.MM.yyyy') }}{#-SW have their date as 01.01.1900-#} {%- elif -included variable- and contact.language == 'GR' -%} {{ -included variable-|format_date('dd.MM.yyyy') }}{#-GR have their date as 01.01.1900-#} {%- … -
Django (hard question): How to allow users to write text and insert specific tags/variables that my app will then fill with values on the BE
This is an hard one (I think). I have a django app and I am trying to build a specific editor tool to help users write email templates. Basically, a user should be able to write simple text for an email but also insert tags/variables in specific spots that will then be filled with values. Almost like if they were create a django template. So imagine that a user would write something like: " Hi, <employee name> I am very happy to inform you that you have been confirmed for the position of <position name> for the upcoming <project_type> <project_name>...." And on the backend I would transform that into: " Hi, Mike I am very happy to inform you that you have been confirmed for the position of Product Designer for the upcoming feature film Titanic...." Currently I have a solution where the main structure of the email is the one I built and users can't really change it. (So it's just one template) but I would like to allow users to create their own templates. How can I do it? -
probleme to upload multiple file in Django
I'm getting an error when I try to upload multiple files in a form. this is my model: class Delivery(models.Model): user = models.ForeignKey( Client, on_delete=models.CASCADE, verbose_name=_("Client"), related_name=_("delivery_user") ) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("destination_address")) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) operation_time = models.TimeField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", blank=True, null=True, ) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def get_absolute_url(self): return reverse("delivery:unconf-delivery-details", args=[self.id]) I used an exemple from Django website to handle the multiple upload of files and this is the form and the view for this model: View.py class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" def get_success_url(self): return reverse("delivery:operation-form", kwargs={"pk": self.object.pk}) def test_func(self): return self.request.user.is_active def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist("decument") if form.is_valid(): for file in files: self.Delivery.objects.create(document=file) return self.form_valid(form) else: return self.form_invalid(form) Form.py class UserDeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = [ "user", "pickup_address", "destination_address", "operation_date", "operation_time", "document", ] widgets = { "operation_date": forms.DateInput( format=("%d %B %Y"), attrs={"class": "form-control mb-2 delivery-form", "placeholder": "JJ-MM-AAAA"}, ), "operation_time": forms.TimeInput( attrs={"type": "time", … -
how to create new upload_to for FileField folder from views.py
in models.py, class Files(models.Model): File = models.FileField(upload_to="documents/") in my views.py, all works perfectly when i remove the 3rd line file = Files(File=f) file.File.upload_to('Media/') file.save() Question is. I want to create new upload_to Folder from views.py only. is it even POSSIBLE ? I know the instance function method of creating Folder used in models.py, i dont want to use it -
Wagtail Custom Translatable Menu
I am new to wagtail and i am working with a custom menu. I set up a custom menu class and use a tag to display the menu-items in the templates. This works fine, however i would need to create different menus depending on what language my site is used in. (i know wagtailmenus exists, however i could not find a satisfying way to create translated menus there either) I wanted to create a similar translation experience like wagtail-localize does with pages. Is this possible or do i have to take a different approach? I already tried to use wagtails TranslatableMixin to simply create duplicates of my menu with different translations, however this does not seem to work. -
how to use if in django class based view
i want to use if and i need to have a variable and that variable needs kwords class ResetPassword(FormView): template_name = 'reset_password.html' form_class = ResetPasswordForm def get_context_data(self, **kwargs): context = super(ResetPassword, self).get_context_data(**kwargs) context['uuid'] = kwargs.get('uuid') context['base64'] = kwargs.get('base64') return context if (get_context_data['context']['uuid'] and get_context_data['context']['base64']) == (url_uuid and url_base64): def form_valid(self, form): user = User.objects.get(id= self.request.user.id) user.set_password(form.cleaned_data['password']) user.save() return redirect('/login') -
Django multiple serializers with relation
I have two tables of users and I am creating a form to store the user information. Models.py class MyUser(User): address = models.CharField(max_length=200) city = models.CharField(max_length=200) expire_date = models.DateField() This creates a table with user_ptr_id to the auth_user table of django. I created two serializers: one for the User: class UserSerializer(serializers.ModelSerializer): first_name = serializers.CharField(min_length=2, required=True) last_name = serializers.CharField(min_length=2, required=True) email = serializers.EmailField(min_length=5, required=True) password = serializers.CharField(min_length=8, write_only=True, required=True) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password') def create(self, validated_data): return UserSerializer(**validated_data) And MyUser class: class MyUserSerializer(serializers.ModelSerializer): address = serializers.CharField(max_length=200) city = serializers.CharField(max_length=200) class Meta: model = MyUser fields = ('city', 'address') def create(self, validated_data): return MyUser(**validated_data) As I am using Django Rest-Framework-Auth, I craeted a serializer to catch the data, but I don't know how to let the things work together. In the "MyUserSerializer" class, I also perform many validate checks, that I omitted here to keep the code clean. Code below doesn't work class UserSignup(serializers.Serializer): user = UserSerializer() my_user = MyUserSerializer() confirm_psw = serializers.CharField(min_length=8, write_only=True, required=True) def validate(self, data): if not data["user"].get('password') or not data.get('confirm_psw'): raise serializers.ValidationError("Please enter a password and confirm it.") if data["user"].get('password') != data.get('confirm_psw'): raise serializers.ValidationError("Those passwords don't match.") return data def save(self, …