Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I register with 2 categories of users and save the status in the database?
This is what my current code looks like, but the status is not saved in the database. Even if in models I default = 'Admin' in the database it appears at status: '-'. Why? I want to add the status to the database to know which category users belong to models.py STATUS_CHOICES = Choices( ('Client', 'Client'), ('Master', 'Master') ) class User(AbstractUser): email = models.EmailField(error_messages={ 'unique': 'A user is already registered with this email!'}, verbose_name='email address', max_length=255, unique=True, ) confirmed_password = models.CharField( max_length=128, verbose_name='confirmed_password') status = models.CharField( max_length=100, choices=STATUS_CHOICES, verbose_name='status', default="Admin") username = models.CharField(max_length=254) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] forms.py class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password', 'confirmed_password', 'username') views.py def RegisterUser(request): master = EditUserForm(request.POST) if request.POST: if master.is_valid() and request.POST["status"] == "Master": master.save() messages.success(request, "It was successfully registered master") return render(request, "registration/index.html") elif master.is_valid() and request.POST["status"] == "Client": master.save() messages.success(request, "It was successfully registered CLIENT") return render(request, "registration/index.html") else: return render(request, "registration/register.html", {}) else: master = EditUserForm() return render(request, "registration/register.html", {'master': master}) register.html <h1>Registration Page</h1> <form action="" method="post"> {% csrf_token %} {{ master.as_p }} <input type="submit" name="status" value="Master" /> <input type="submit" name="status" value="Client" /> </form> -
Django drf-spectacular How to split api descriptions for public and private use?
I want to make 2 different documentations. One is for public with few api methods and no authz. Another one is for private usage with all api methods and only for authorized users. -
Django: multiple dates form
so in my .html file i inserted two inputs for two different dates (end and start) From: <input type='date' name='fromdate'/> To: <input type='date' name='todate'/> <input type='submit' value='Submit'/> and in my models.py i have this model class MyDatesInput(models.Model): dates = ArrayField(models.DateTimeField() ) i need to use the dates for an api call like this: http://history.openweathermap.org/data/2.5/history/city?lat={lat}&lon={lon}&type=hour&start={start}&end={end}&appid={API key} how do i link all of this together? -
how to query filter self foreign key
query = Services.objects.filter(parent_id__isnull=True,sub_service__type=0) When im filtering sub_service__type=1 It returns correct output. i.e. type 1 for sub_service, But when i change it to sub_service__type=0 filters doesnot work. Instead it returns me every output. i.e. type 0,1 Instead of type 0 Heres Code: # MODELS class Services(models.Model): type_ = ((1, 'INCLUSIVE'), (0, 'EXCLUSIVE')) service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='sub_service') type = models.SmallIntegerField(blank=True, null=True, choices=type_) # VIEWS @action(detail=False, methods=['get'], permission_classes=(AllowAny,)) def service_list(self, request): query = Services.objects.filter(parent_id__isnull=True,sub_service__type=0) serializer = SubServiceSerializer(query , many=True).data return Response(serializer.data) # SERIALIZER class SubServiceSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class ServiceSerializer(serializers.ModelSerializer): sub_service = SubServiceSerializer(many=True) class Meta: model = Services fields = "__all__" -
Django - how to use many variables in a template tag value
I want to add two variables as the value on an input tag but the syntax I am currently using only renders the first variable. How can I make both variables show up? Current code loan={ amount": 200000, "due_date": "12/12/2021", } <input class="block" id="address" name="address" type="number" value="{{ loan.amount }} {{ loan.currency }}"> This currently outputs nothing -
AuthenticationForm.is_valid() always return False
I'm new to Django. form.is_valid() always return False. from django.contrib.auth.forms import AuthenticationForm class SignInForm(AuthenticationForm): pass Test method is below. form = SignInForm({'username': 'user2', 'password': 'example2'}) self.assertTrue(form.is_valid()) form.is_valid() always return False. Why??? -
Find user name and last name Query Django
In my Django app I have module 'users' which I use to create profiles. I need help on how to query and find user name and last name depending on Profile in 'users'. users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) I'm not sure, but how can I find 'user.first_name' and 'user.last_name' using only Profile. Something like: queryset = User.objects.values('first_name').filter(Profile=Profile_var) -
Limiting the queryset displayed after the foreign key in the template - Django
I know how to return all objects by a foreign key in a Django template. But how to limit their number to the last 3? Is it possible? Example Models.html class Person(models.Model): ... class Tag(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) name = models.CharField(max_length=10) Template.html {% for tag in person.tag_set.all %} ... {% endfor %} What is expected (only the last 3 objects)? {% for tag in person.tag_set.all[:3] %} ... {% endfor %} -
when i make a post it shows this errorField ‘id’ expected a number but got ‘d’. NOTE: the post get created but i get this error
I have tried a lot of things to resolve this issue but they are not working that why i wanna ask somebody that better than me here. Ive tried using a slug field it doesnt show that, but i wanna use id that when it starts showing the error. NOTE: the post get created perfectly well and that it then shows this error but the posts was made. I treid making the post using a forms from my frontend let me show some code views.py def blogpost(request): if request.method == "POST": form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.instance.creator = request.user form.save() # ← no commit=False messages.success(request, f'Hi, Your Post have been sent for review and would be live soon!') return redirect('blog:home') else: form = BlogPostForm() context = { 'form': form } return render(request, 'blog/AddPost.html', context) # this is the blog list view def blog_list(request): posts = Blog.objects.filter(status='published').order_by('-created') categoriess = Category.objects.all() context = { 'posts': posts, 'categories': categoriess, } return render(request, 'blog/bloghome.html', context) #this is the blog detail view def blog_detail(request, post_id): post = get_object_or_404(Blog, id=post_id) # post = Blog.objects.filter(slug=blog_slug) categories = Category.objects.all() comments = post.comments.filter(active=True) new_comment = None if request.method == "POST": comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) … -
How to stack filters if parameters exist or not?
If I have something such as this: tasks = Task.objects.filter( Q(datetime__contains=date) & Q(user=uid) if uid!=0 else & Q(member=mid) if mid!=0 else & Q(job=jid) if jid!=0 else ) It will stack/mix the filters dependent on what function parameters are passed, but obviously that doesn't work, what is the best way to continue? -
Fill form when select an element of a datalist
I am trying to fill a form with the data of a local mongodb database. When the user selects a value of the datalist, I want to fill the form with the values of that selected option. I have managed to show the different possible values in the datalist, so the database is well connected already. modificar_centro_educativo.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Rellenar Centros Educativos</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </head> <body> <div class="container"> <form action="/polls/centro_educativo/" method="GET"> <div class="row"> <div class="col"> <label for="centros" class="form-label">Nombre centro</label> <input list="centros" name="browser"> <datalist id="centros" onchange="/polls/centro_educativo/"> {% for result in Centro_educativo_contacto%} <option>{{result.nombre_centro}}</option> {% endfor %} </datalist> <label for="FormControlNombre_contacto" class="form-label">Nombre contacto</label> <input type="text" class="form-control" id="FormControlNombre_contacto" name="nombre_contacto"> <label for="FormControlUbicacion" class="form-label">Ubicación</label> <input type="text" class="form-control" id="FormControlUbicacion" name="ubicacion"> <label for="FormControlTelefono" class="form-label">Telefono</label> <input type="text" class="form-control" id="FormControlTelefono" name="telefono"> <label for="FormControlEmail" class="form-label">Email address</label> <input type="email" class="form-control" id="FormControlEmail" name="email"> </div> <div class="col"> <label for="FormControlGrados" class="form-label">Grados</label> <input type="text" class="form-control" id="FormControlGrados" name="grados"> <label for="FormControlConocimientos_generales" class="form-label">Conocimientos Generales</label> <input type="text" class="form-control" id="FormControlConocimientos_generales" name="conocimientos_generales"> <label for="FormControlToken_moodle" class="form-label">Token moodle</label> <input type="text" class="form-control" id="FormControlToken_moodle" name="token_moodle"> <label for="FormControlUrl_moodle" class="form-label">Url moodle</label> <input type="url" class="form-control" id="FormControlUrl_moodle" name="url_moodle"> <label for="FormControlUsuario_moodle" class="form-label">Usuario moodle</label> <input type="text" class="form-control" id="FormControlUsuario_moodle" name="usuario_moodle"> <label for="FormControlContrasena_moodle" class="form-label">Contrasena moodle</label> <input type="password" class="form-control" id="FormControlContrasena_moodle" name="contrasena_moodle"> </div> </div> <input … -
Django: "AssertionError: 401 != 200" error when user updates profile [closed]
I'm a beginner. I've been strictly following this tutorial to implement user profiles in Django: https://vhutshilo.medium.com/?p=dc7732c96607 Everything has been going well, up until when implementing the ability to update your own profile. All of this is in the test folder. This is the code that gives me an error: '''User updating their own profile''' def test_profile_update(self): #Register register_url = reverse('accounts:register') register_data = { 'username': 'bean', 'password': 'boom12345' } self.client.post(register_url, register_data, format='json') user = User.objects.get(username='bean') self.client.force_login(user) url = reverse(('accounts:profile'), kwargs={'username':'bean'}) data = { 'name': 'Bean', 'bio': "I don't know what to write" } response = self.client.put(url, data, format='json') And the error code: FAIL: test_profile_update (accounts.tests.test_api.AccountAPITestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\varga\Downloads\Rattarium\backend\accounts\tests\test_api.py", line 157, in test_profile_update self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 401 != 200 What's wrong? It's the exact code from the tutorial, and everything up until this point has been working. Thanks in advance. -
ValidationError - Django Q Query - is not a valid UUID
I am trying to get value from User Model, my requirement is that or condition should be in same query. User.objects.get( Q(premium_referral=form.cleaned_data.get('referral_code')) | Q(id=form.cleaned_data.get('referral_code')) ) But it give error ValidationError at /register ['“XUSB5” is not a valid UUID.'] The above query works perfect for id but not for premium_referral field Bellow is the model class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) premium_referral = models.CharField(('Premium Referral Code'), max_length=30, null=True,blank=True, unique=True) -
Populate Python object with Django Form
I am trying to use a Django form to populate a Python object (not a Django model). I have the feeling I can only either: build a simple form and populate manually use a Django model as proxy The extra difficulty is the form send a GET request The class class Search: def __init__(self): self.min_area = 0 self.max_area = 999 The form from django import forms class MainSearchForm(forms.Form): min_area = forms.IntegerField(label="Minimum", required=False) max_area = forms.IntegerField(label="Maximum", required=False) The view from django.http import HttpResponse from django.template import loader from front.forms.search.main import MainSearchForm from front.gears.search import Search def main(request): search = Search() form = MainSearchForm(request.GET) # manual populating i want to avoid if form.is_bound: search.min_area = form.cleaned_data['min_area'] search.max_area = form.cleaned_data['max_area'] tpl = loader.get_template('front/search/main.html') ctx = { 'form': form } return HttpResponse(tpl.render(ctx, request)) For now, I am populating manually in the view but I am quite sure there is a better way to do it. Am I missing a part of the documentation ? -
Django - method save() put button value to database
I have a problem. I used this [link][1] to complete my exercise, but I dont know, how to do it practically. [1]: https://stackoverflow.com/questions/69964943/how-to-put-button-value-to-database-django/69965390#69965390 I have a few buttons like this: {% for up in ups%} <div id="{{up.name|cut:' '}}" class="m-l-0"> {% for under in unders%} {% if up.pk == under.up.all.0.pk %} <button id="under{{ under.pk }}" class="under overflow-hidden btn btn-lg btn-primary ml-3" style="display:none" value="{{under.nazev}}({{under.up.all.0.nazev}})" type="button">{{under.nazev}}</button> {% endif %} {% endfor %} </div> {% endfor %} and views.py def form_create(request): if request.method == "POST": catch = request.GET.get('name') if request.POST.get(catch, False): novy = Trying(up=request.POST.get(catch)) novy.save() return render(request, 'index.html') and this is models.py class Trying(models.Model): up = models.CharField(max_length=100, null=True, blank=False, verbose_name="Up") I have also models Up and Under. And in under is ForeignKey to Up. I am desperate. I was trying previous question, but its not working. I will be glad for every point. Thank you!!! -
How to reference self.something as ForeignKey in Django models.py?
I'm working on a Django project that uses models. I want to somehow access the highest bid on that listing at all times (as listing.highest_bid) or some other way if there's a better solution. What I tried in the code snippet below for the highest_bid doesn't seem to work, it gives me an AttributeError (AttributeError: 'str' object has no attribute 'bids'). How can I access a model's own parameter's values and filter them to my liking? class Listing(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings") title = models.CharField(max_length=100) description = models.CharField(max_length=1000) starting_bid = models.PositiveIntegerField() picture = models.TextField(max_length=200, default='static/auctions/notfound.png') category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="listings") is_active = models.BooleanField() highest_bid = models.ForeignKey("self".bids.aggregate(Max('price')).first()) #["price__max"] # highest bid # listing created on xxxx-xx-xx def __str__(self): return f"{self.title}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") price = models.PositiveIntegerField() # time TODO def __str__(self) -> str: return f"Bid #{self.id}" -
Accessing S3 img from plain javascript while using django storages
I have a pretty basic issue am unable to solve. I am serving static files from S3 using Django storages. In my template, I setup img source like this: "{% static 'fun_share/img/logo/logo.svg' %}" while having STATIC_URL = "/static/" Django storages handle the actual img src "translation", ie becomes https://my-bucket.amazonaws.com/static/fun_share/img/logo/logo.svg?..... So far so good. Now, I want to change the image src from plain javascript to I different image (logo-2.svg). What is the best way to handle calling the s3 bucket with proper URL (also considering secrets and keys)? I would expect const logo = document.querySelector(".navbar-brand img"); logo.src = "/static/fun_share/img/logo/logo-2.svg"; to work, but that does not seem to be the case, as the js call is made to the server itself, not redirected to the s3 bucket. Any help much appriciated. -
Django i want create a function which can be run from any page from the website and do its process and return on the same page
Django i want create a function which can be run from any page from the website and do its process and return on the same page What i want to is to create a button to add to cart i have writted function but the time come from returning from the function i use redirect to cart page but i want that there are lots of types of product pages and i want they must redirect to the same page from where they come and use the same function to do that any idea @login_required(login_url='login_signup') def add_cart(request,id): prod = Product.objects.get(id = id) try: cart = Cart.objects.get(cart_id = _cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product = prod,cart = cart) cart_item.quantity = cart_item.quantity + 1 cart_item.save() # print("I was tries") customer = request.user cust = Customer.objects.get(user = customer) # print(f"The customer is {cust}") except CartItem.DoesNotExist: customer = request.user cust = Customer.objects.get(user = customer) # print("Cart except is also being hit") cart_item = CartItem.objects.create( product = prod, quantity = 1, cart = cart, user = cust, ) cart_item.save() return redirect('/cart/cart_page') Here is the function i use to add to cart i want it to redirect … -
Get ressource URI for foreign object in django in a serializer?
Supposing we have the following models: class Person(models.Model): name = models.CharField(max_length=10, blank=True, null=True) class Food(models.Model): person = models.ForeignKey(Person, default=None, on_delete=models.CASCADE) name = models.CharField(max_length=10, blank=True, null=True) I have these models in ModelViewSets and registered them as URLs with Django Rest Framework. And they are accessible as ressource URI successfully, but I want to add field for Food that can return the Person ressource URI. I can hardcode it as follows but I need something better: class Food(models.Model): person = models.ForeignKey(Person, default=None, on_delete=models.CASCADE) name = models.CharField(max_length=10, blank=True, null=True) def get_person_uri(self): return f"http://127.0.0.1:8000/persons/{self.person.id}/" Serializer is as follows: class FoodSerializer(serializers.Model): class Meta: model = Food fields = ["person", "name", "get_person_uri"] Where get_person_uri should take me directly to the parent person URI What solutions can you suggest? -
django query nested list in array
I have a jsonfield in my model (callRecord called participants containing the following data: [ { "acsUser":"None", "spoolUser":"None", "phone":"None", "guest":"None", "encrypted":"None", "onPremises":"None", "acsApplicationInstance":"None", "spoolApplicationInstance":"None", "applicationInstance":"None", "application":"None", "device":"None", "user":{ "id":"1", "displayName":"User One", "tenantId":"some tenant" } }, { "acsUser":"None", "spoolUser":"None", "phone":"None", "guest":"None", "encrypted":"None", "onPremises":"None", "acsApplicationInstance":"None", "spoolApplicationInstance":"None", "applicationInstance":"None", "application":"None", "device":"None", "user":{ "id":"2", "displayName":"User Two", "tenantId":"some tenant" } } ] I want to search the entire json to check if it conjtains a displayName of "User Two" I just can't get it to work. What I tried: recent_user_calls = CallRecord.objects.filter(participants__user__contains = {'displayName':'User Two'}) recent_user_calls = CallRecord.objects.filter(participants__contains = {'displayName':'User Two'}) recent_user_calls = CallRecord.objects.filter(participants__user__contains = [{'displayName':'User Two'}]) recent_user_calls = CallRecord.objects.filter(participants__contains = 'User Two') ecent_user_calls = CallRecord.objects.filter(participants__user__contains = 'User Two') and a million other combinations. None of them work. They all return empty results. searching on a key outside of the user list works fine. IS there a way to search the user list contained in each object of the array? -
How to handle cron-tabs for a Docker-based Django app running on a Linux-based Webapp in Azure, scaled over multiple cloud-instances
I have a Docker-based Django application running on a Linux based Webapp in Azure, which can scale from 1-5 instances. I want to run cron-tabs which run management commands inside the Django application, and found the following approaches: I've found this post, suggesting a bash-script to start the cron-tabs. How to run cronjobs on an azure linux hosted webapp? I've also found this example github on how to set-up cron-tabs inside a docker-container: https://github.com/Adiii717/docker-python-cronjob But the problem is that I can't run it inside the Docker environment, as the cron-jobs then will be run multiple times if the Webbapp is scaled over multiple instances in Azure. I neither can use Azure's Webjobs, as it's not yet available for Linux-based Webapps. The only option I see right now is creating a parallell mirrored Webapp that's restricted to only using one instance from Azure, thus not creating the issue with having cronjobs being run multiple times - but this seems sub-optimal as I need to deploy two web-apps every time I make code change, to have both the "original" application as well as the "cronjobs-application" being run on the same updated version of the codebase. How can I implement a better solution … -
Google line chart not printing in Django
I'm doing a project on covid visualization i.e., when a user selects a particular state, date range, and output type corresponding to the input we get output as a graph for which I'm using Google API to display line charts. The problem occurring now is graph is not displayed on the website but data is passing from backend python views to HTML. HTML <div id="chart_div"> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('string', 'X'); data.addColumn('number', {{user_required_type_json|safe}}); data.addRows({{chart_list_json|safe}}); var options = { hAxis: { title: 'Dates', textStyle: { color: '#1a237e', fontSize: 14, fontName: 'Calibri', bold: true }, titleTextStyle: { color:'#1a237e', fontSize: 22, fontName: 'Calibri', bold: true, }, }, vAxis: { title: {{user_required_type_json|safe}}, textStyle: { color: '#1a237e', fontName: 'Calibri', fontSize: 18, bold: true }, titleTextStyle: { color: '#1a237e', fontName: 'Calibri', fontSize: 22, bold: true }, }, title: {{user_input_state_json|safe}}+' '+{{user_required_type_json|safe}}+' Data' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </div> views.py import json from django.shortcuts import render from django.http import HttpResponse import requests import datetime as dt def indexview(request): url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json') json_data=url.json() user_input_state='' user_input_date_from='2021-10-01' user_input_date_to='2021-10-10' user_data_type='' user_required_type='' if request.method == 'POST': user_input_state=request.POST.get('state') user_input_date_from=request.POST['date_from'] user_input_date_to=request.POST['date_to'] user_data_type=request.POST.get('data_period') #cumulative or daily user_required_type=request.POST.get('required_type') #confirmed, recovered..... #To store dates … -
Why does Django run all scripts when `makemigrations` is run?
Whenever I run python manage.py makemigrations it seems that Django executes a script within one of my apps that establishes a connection to an external API which takes some time. Why's that & is there any way to avoid this? This slows down development since the script takes 30 seconds or some. -
Files not uploading to the chosen directory after form validation with Dropzone.js and Django
I am trying to implement a drag & drop function for files in my webpage (now limited to images for testing purposes). I am using Django and Dropzone.js I think I implemented everything properly but for some reason, even the form is validated, the content is not uploaded to the desired folder. forms.py from django.forms import ModelForm from crown_agents.models import FileHistory class UploadFileForm(ModelForm): class Meta: model = FileHistory fields = ('file_image',) models.py from django.db import models from django.contrib.auth.models import User class FileHistory(models.Model): file_image = models.ImageField(null=True, blank=True, upload_to="project_files/") user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) timestamp = models.DateTimeField( auto_now_add=True) views.py from django.contrib.auth.decorators import login_required from django.conf import settings from django.shortcuts import HttpResponse, render from .forms import UploadFileForm @login_required def project_page(request): context = {} context['nbar'] = projects if request.method == 'POST': print(request.FILES) form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() return render(request, 'project_page.html', context) print (form.errors) else: form = UploadFileForm() context['form'] = form return render(request, 'project_page.html', context) urls.py from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.utils.translation import gettext_lazy as _ from . import views urlpatterns = [ … -
Working DRF and JWT returns "detail": "No active account found with the given credentials"
I went through StackOverFlow and none of the solutions seem to fix my problem. I created a superuser and only that superuser is able to obtain an access token and refresh token. While newly created users don't seem to be recognized by the system. I use a custom user class. Here you can view the error serializers.py from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password class RegisterUserSerializers(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'password') extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def validate_password(self, value: str) -> str: """ Hash value passed by user. :param value: password of a user :return: a hashed version of the password """ return make_password(value) views.py from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny from .serializers import RegisterUserSerializers from rest_framework_simplejwt.tokens import RefreshToken class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request): reg_serial = RegisterUserSerializers(data=request.data) if reg_serial.is_valid(): newUser = reg_serial.save() if newUser: context = { "message": f"User created {newUser}" } return Response(context, status=status.HTTP_201_CREATED) return Response(reg_serial.errors, status=status.HTTP_400_BAD_REQUEST) class BlacklistTokenView(APIView): permission_classes = [AllowAny] def post(self, request): try: refresh_token = …