Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe API, How can I get"customer_email" when Checkout Session executed
I want Django App to send a confirmation email to a customer when webhook is executed, In order to send an email, I need to get the customer's email address when they make payment. But the JSON posted by stripe Webhook always sends customer_email with null value. Here's the result from the part of Webhook object. { "api_version": "2020-08-27", "created": 1623048315, "data": { "object": { "allow_promotion_codes": null, "amount_subtotal": 1, "amount_total": 1, "billing_address_collection": null, "cancel_url": "http://3.129.28.xxx/subscriptions/cancel/", "client_reference_id": "1", "currency": "jpy", "customer": "cus_Jcrw9AXrxWB91I", "customer_details": { "email": null, "tax_exempt": "none", "tax_ids": [] }, "customer_email": null, "id": "cs_test_a1gup9kG1ArIxORROMUbKqg6eBnIknoYdgQARcr3AS14DGo2gLFfVnxxxx", You can see "customer_email": null, And "customer_details"'s "email" is also null, Therefore I thought I need to get "customer_email" when "create_checkout_session" is executed. So I added "customer_email=userEmail" in create_checkout_session view.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': # domain_url = 'http://localhost:8000/' domain_url = 'http://3.129.28.206/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( customer_email=userEmail, client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'subscriptions/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'subscriptions/cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_PRICE_ID, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) But it does not work. So I tried a different attempt. customer_email = request.org.billing_email It also does not work. and there is … -
Django Rest Framework PyJWT Token Invalid header padding
I am using Django Rest Frame Work and I'm trying to get authenticated user info, using token in session views.py: # Get Authenticated User Data class UserAPIView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): return Response(UserSerializer(request.user).data) JWTAuthentication class JWTAuthentication(BaseAuthentication): def authenticate(self, request): token = request.COOKIES.get('jwt') print('token = ', token) if not token: return None try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) print('payload = ', payload) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('unauthenticated') user = User.objects.get(pk=payload['user_id']) if not user: raise exceptions.AuthenticationFailed('User not found!') return (user, None) @staticmethod def generate_jwt(id): payload = { 'user_id': id, 'exp': datetime.datetime.now() + datetime.timedelta(days=1), 'iat': datetime.datetime.utcnow() } return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') But I got this error Invalid header padding this is the Traceback [08/Jun/2021 10:44:09] "GET /api/account/user/ HTTP/1.1" 500 134862 token = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2MjMyMzU0NDcsImlhdCI6MTYyMzE0MTg0N30.qnNZw3M5YiLMalc78wknjtuTOztHbjyr2swHyK1xuGY' Internal Server Error: /api/account/user/ Traceback (most recent call last): File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 186, in _load header_data = base64url_decode(header_segment) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\utils.py", line 42, in base64url_decode return base64.urlsafe_b64decode(input) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 133, in urlsafe_b64decode return b64decode(s) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Invalid base64-encoded string: number of data characters (37) cannot be 1 more than a multiple of 4 this is the rest of Traceback During handling of the above exception, another exception occurred: File … -
Django admin - User and group extend
Iam trying to update my user model in Django's admin Panel. I want to add a field/column in Admin panel named "Group" for Users. This field will have the option to select any value from the existing Groups (single option only/Dropdown). I tried to search for the document but I couldnt found out the relevant information to manipulate the User Admin panel. Although I do found a few blogs and video where they have created a new app and extend the User model. Is it possible to update Admin panel for User? Please suggest any document or blog or any approach to achieve the goal. -
Can login in production but not in development [closed]
I have backed up my postgres database from production and am using it in my dev environment. Everything works as it does in production aside from authentication. When I try to login with the correct details it fails. I thought this could be because of something in settings.py however I don't really have anything added (maybe I need something?) -
How to perform a validation according to types, instead of field by field, in Django?
In Django, before calling the "save" method of an instance, it is possible to implement your own validation by defining the "clean" or "full_clean" method in the corresponding model. The problem is that in that case it would be necessary to check each of the fields and add a particular behavior; however, what I want is a more general behavior, so that if you enter a type that does not match the one defined in the model, such field will be saved as None. Example: Let's suppose an application, with the following model: class Company(models.Model): name = models.CharField(max_length=255, null=True, blank=True) date_of_formation = models.DateTimeField(null=True, blank=True) assets = models.FloatField(null=True, blank=True) And assume we have these 3 json data inputs: input_1 = { "pk": 1, "name": "Alexander", # right type "date_of_formation": "2021-01-01", # right type "assets": 500023.658 # right type } input_2 = { "pk": 2, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": "2021-01-01", # right type "assets": 523658 # right type } input_3 = { "pk": 3, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": 65, # WRONG type "assets": "523658" # WRONG type } The behavior I would expect is something like: Company.objects.create(**input_1) Company.objects.create(**input_2) Company.objects.create(**input_3) >> Company.objects.get(pk=1).__dict__ { "id": 1, "name": "Alexander", … -
Why we cannot use select_related for ManyToMany fields
let's say i have the following fields class ABC(models.Model) whatever=models.ManyToManyField('DEF') class DEF(models.Model) something=models.CharField() I want to retrieve ABC along side each DEF it's connected to, why i cannot do this ? ABC.objects.filter(pk=123).select_related('DEF').get() I believe we can do this in one SQL query like so select * from ABC inner join ABC_DEF on ABC.id = ABC_DEF.ABC_ID inner join DEF on DEF.id = ABC_DEF.DEF_ID -
How to filter Django serializer data?
I'm trying to filter data based on userName in JWT. This is how I've been trying to do it: views.py: class TestView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token} try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] request.user = user person = Person.objects.filter(userName=request.user) except ValidationError as v: print("validation error", v) return Response(person[0]) This works as I can get the Person data with print("Person: ", person[0]). The return Response(person[0]) however returns an error: TypeError: Object of type Person is not JSON serializable. I guess I could use a serializer class to return a valid JSON, am I right? I have this in my serializers.py: class TestSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' I just don't know how to use this with my view. If I use serializer instead of person = Person.objects.filter(userName=request.user), how is the filtering supposed to be done? Please correct me if I'm not on right track at all. -
Semgrep: Looking for wrong import
How would I go on about making Semgrep check if my codebase is important the wrong module from the wrong place? E.g. in my django project: from gettext import gettext but we should really do from django.utils.translation import gettext Any ideas on how to achieve this with semgrep? -
What is actual meaning of r'^ icon in every urls? can any one explain what is his meaning and how important this are in details [duplicate]
This is the code in question: url(r'^dreamreals/', ListView.as_view(model = Dreamreal, template_name = "dreamreal_list.html")), ) -
Threading: Restarting a thread
I have a django project that I am currently working on. I have several threads that I use to fill a database through API requests when the user asks for a database update using a button. This works great. My problem is that I would like users to be able to refresh the database more than once while the server is active (in the future). Since threads can't be restarted once they finish, I'm not really sure how to proceed to achieve what I want. Here are my threads: agencies_thread = threading.Thread(target=fill_agencies, name="Database Updater1") companies_thread = threading.Thread(target=fill_companies, name="Database Updater2") contracts_thread = threading.Thread(target=fill_contracts, name="Database Updater3") orders_thread = threading.Thread(target=fill_orders, name="Database Updater4") projects_thread = threading.Thread(target=fill_projects, name="Database Updater5") resources_thread = threading.Thread(target=fill_resources, name="Database Updater6") I'm thinking that the threads have to be recreated everytime someones presses the button, but adding those lines ^^ in my views.py function that manages the database loading can't really work considering my function: elif urlRequest[:12] == 'loading.html': # PAGE DE CHARGEMENT global updateValue if updateValue == 0: agencies_thread.start() companies_thread.start() contracts_thread.start() orders_thread.start() projects_thread.start() resources_thread.start() updateValue = 1 updateState = 0 if agencies_thread.is_alive(): agenciesState = 'en cours de chargement' else: agenciesState = 'Chargement terminé' updateState += 1 if companies_thread.is_alive(): companiesState = 'en … -
How to pass value/variable from one function to another in django - views
Not able to pass a variable from one function to another. @api_view(['GET']) def UserList(request): loc = User.objects.all() latest_id = User.objects.latest('userid').userid #want to pass this variable into DetailList function serializer = UserSerializer(loc, many=True) return Response(serializer.data) @api_view(['GET']) def DetailList(request): loc = Detail.objects.all() serializer = DetailSerializer(loc, many=True) return Response(serializer.data) and finaly want to use that userid variable to add the data into Detail table. class UserAPIView(APIView): def post(self, request ): userid = request.data.get('userid') name = request.data.get('name') age = request.data.get('age') gender = request.data.get('gender') address = request.data.get('address') phone = request.data.get('phone') user_serializer = UserSerializer(data={"name": name, "age": age, "gender": gender}) detail_serializer = DetailSerializer(data={"userid": userid,"address": address, "phone": phone}) if user_serializer.is_valid(raise_exception=True): user_serializer.save() if detail_serializer.is_valid(raise_exception=True): detail_serializer.save() return Response({'status': 'Success'}) not able to pass variable data through declaring global , as getting error Nulltype is not callable. -
SQL to Queryset Django
i want to use this query in django, i have tried and read the django document but i still can't understand it Sql to QuerySet Django SELECT * FROM movie as m INNER JOIN similarity as s ON m.`movie_id` = s.first_movie WHERE `movie_id` = 1 ORDER BY `s`.`similarity_score` DESC -
Nginx error_page will not display
I can't configure nginx custom error pages /etc/nginx/sites-enabled/mysite looks like this error_page 404 /custom_404.html; location = /custom_404.html { root /usr/share/nginx/html; internal; I tried other paths as well looked all over the internet and still nothing that helped. I wasl also following this tutorial but no luck If anyone knows the solution for this and have a time to respond it would be awsome. Thank you all. -
Django-Beard MP_Node save to database with post request
I am new to django and I am trying to understand Django-beard. What I want is to save the data to the db, but for the models I have inherited from MP_Node. Here is the models: class Update(MP_Node): name = models.CharField(max_length=30) update = models.TextField() date = models.DateField(auto_now_add=True) node_order_by = ['created'] I am using viewsets for the views part and it takes care of the CRUD: class UpdateViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = UpdateSerializer queryset = Update.objects.all() Can someone help me understand how do I save the data using POST or PUT? Currently I am getting the error that the path and depth fields are required but it is supposed to be generated automatically. I am using all the fields while serializing but I tried to set a particular few fields but then I am getting the error from the database level that Depth cannot be a not null constraint. class UpdateSerializer(serializers.ModelSerializer): class Meta: model = Update fields = '__all__' Is there a way to save the data using the MP_Node? -
How can check Bookings related to specific saloon in django
How can a saloon check the booking like how many people reserve the time slot for different service. When i click on check booking button is show the error 'WSGIRequest' object has no attribute 'saloon' Model.py class Booking(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.CharField(max_length=40) time = models.TimeField() date = models.DateField() View.py class SaloonCheckBooking(TemplateView): template_name = 'saloonCheck.html' def get(self, request, *args, **kwargs): checkBooking = Booking.objects.get(saloon_id=self.request.saloon.id) return render(request, self.template_name, {'checkBooking': checkBooking}) -
trying to setup mysql on ubuntu for django but getting error 'django.db.utils.OperationalError: (1046, 'No database selected')'
my Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'DATABASE' : 'DjangoProject', 'USER' : 'myprojectuser', 'PASSWORD' : 'Akbar@123456', 'HOST': 'localhost', 'PORT': '', # 'default-character-se' : 'utf8', # 'NAME': BASE_DIR / 'db.sqlite3', } } SHOW DATABASES command on terminal mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | DjangoProject | | information_schema | | mysql | | performance_schema | | sample | | sys | +--------------------+ 6 rows in set (0.00 sec) mysql> error File "/usr/local/lib/python3.8/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1046, 'No database selected') I have granted the user rights on the database but it still showing error, please help i want to run mySql just like sqlite3 where you can see your databases in the admin panel, and works same once settings are made, please tell if there is gui interface for mySQL and also how to see your database on the browser, -
Data not saving in database in Django
I am trying to save data into the database from the website. My web page is taking the data(image from my system) but in the database , its not showing up. If i add manually then its creating a new user entry and storing it. Here are my files: models.py class Details(models.Model): name = models.CharField(max_length=122) username = models.CharField(max_length=122) email = models.EmailField(max_length=122) password = models.CharField(max_length=20) def __str__(self): return self.name class Image_Data(models.Model): img_User = models.ForeignKey( Details, blank=True, null=True, on_delete=models.CASCADE) img_password = models.ImageField(null=True, blank=True) def __str__(self): return str(self.img_password) forms.py class ImageForm(ModelForm): class Meta: model = Image_Data fields = ('img_password',) labels = { 'img_password': 'Add your image ', } widgets = { 'img_password': forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Upload from device'}) } views.py def register_new_b(request): saved = False if request.method == "POST": # take whatever is posted to the Details Form form = ImageForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your message has been sent!') return HttpResponseRedirect('/register_new_b?saved=True') else: form = ImageForm() if 'saved' in request.GET: # sends saved var in GET request saved = True return render(request, 'register2.html', {'form': form, 'saved': saved}) here is what i get in database upon saving the image -
Docker run, after docker-compose build could not translate host name “db” to address: Name or service not known
I have currently a system built with docker-compose, it creates a Django application. I've use a database inside a container (postgresql) in my testing build. I want upload my docker image to docker-hub. When i run $ sudo docker-compose up Server goes up sucecesfully Recreating rest_api_db_1 ... done Recreating rest_api_web_1 ... done Attaching to rest_api_db_1, rest_api_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2021-06-08 07:22:10.698 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-06-08 07:22:10.708 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-06-08 07:22:10.719 UTC [26] LOG: database system was shut down at 2021-06-08 07:15:22 UTC db_1 | 2021-06-08 07:22:10.726 UTC [1] LOG: database system is ready to accept connections web_1 | Operations to perform: web_1 | Apply all migrations: admin, api_bus_routes, auth, contenttypes, sessions web_1 | Running migrations: web_1 | No migrations to apply. web_1 | Watching for file changes with StatReloader web_1 | Performing system … -
Django images not displaying properly,static images not displaying
image I am a beginner and I have no idea what the problem is I did give URL and DIR in settings.py STATIC_URL = '/static/' STATICFILES_DIR = [(os.path.join(BASE_DIR, 'static'))] my index.html {% extends 'base.html' %} {% load static %} {% block title %} <title>Home page</title> {% endblock title %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> </div> </div> {% endblock content %} my base.html <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% block title %} {% endblock title %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'index' %}"><img src="{% static 'images/logo.png' %}"</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link" href={% url 'index' %}>Home</a> <a class="nav-link" href={% url 'todolist' %}>Todo List</a> <a class="nav-link" href={% url 'contactus' %}>Contact Us</a> <a class="nav-link" href={% url 'aboutus' %}>About Us</a> </div> </div> </div> </nav> </head> <body class="bg-secondary"> {% block content %} {% … -
How to include Token in Header using Django Rest Framework
I am working with Token Authentication using Django REST Framework. I am generating a new token during User Registration. I need to pass this token to the frontend including in header. These are my code: settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', ... ] urls.py: (project level) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] urls.py: (app level) urlpatterns = [ path('signup/', views.Register.as_view({"post":"register"}), name='users'), path('login/', views.Login.as_view({"post":"create"}), name='login'), path('profile/', views.Profile.as_view({"get":"list"}), name='profile'), ] views.py: # Register View class Register(viewsets.GenericViewSet, mixins.CreateModelMixin,): serializer_class = UserRegisterSerializer def register(self, request): data_dict = self.request.data firstname = data_dict['firstname'] lastname = data_dict['lastname'] username = data_dict['username'] email = data_dict['email'] password = data_dict['password'] mobile = data_dict['mobile'] data = userRegistrationModel.objects.create(firstname=firstname, lastname=lastname, username=username, email=email, password=password, mobile=mobile) if data: user = data.set_password(password) data.save() token = Token.objects.create(user=data) return Response({"message": "Registered Successfully", "code": "HTTP_201_CREATED", "Token": token.key}) else: return Response({"message": "Sorry Try Next Time!!!", "code": "HTTP_403_FORBIDDEN"}) # Login View class Login(viewsets.GenericViewSet, mixins.CreateModelMixin,): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def create(self, request, *args, **kwargs): data_dict = self.request.data email = data_dict['email'] password = data_dict['password'] data = authenticate(email=email, password=password) if data: users = Token.objects.filter(user=data).first() userData = UserRegisterSerializer(data) return Response({"message": "Login Successfully", "code": "HTTP_200_OK", "token": users.key, "user": userData.data}) else: return Response({"message": "Invalid Login", "code": "HTTP_401_UNAUTHORIZED"}) # Profile View … -
call another viewset method from same viewset
I am writing a simple django app where all my apis are based on class based viewsets. I've the following viewset with 2 methods(2 different api calls) but in one of the apis i wanted to access another api's method. class TestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Model.objects.all() serializer_class = MSerializer @action(detail=True, methods=["PUT"], name="viewone") def viewone(self, request, pk): try: <logic> except Exception as e: raise("error") @action(detail=True, methods=["PUT"], name="viewtwo") def viewtwo(self, request, pk): try: viewone = self.as_view({'put': 'viewone'})(request, pk=pk) except Exception as e: print(e) raise("error") the view set two throws me the following AttributeError: This method is available only on the class, not on instances. what am i doing wrong here? -
Django not recognizing empty url config
Sorry, beginner here. I was following this tutorial https://www.youtube.com/watch?v=JD-age0BPVo on py/django and managed to get the webserver running. However, it simply displays the default page: when in my urls.py, I have the default page set. urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')) ] and in api.urls: from django.urls import path from .views import main urlpatterns = [ path('', main) ] and finally in api.views.py I have main(request) from django.shortcuts import render from django.http import HttpResponse # Create your views here. def main(request): return HttpResponse("hello") My project directory looks like this in case it helps: -
How to implement multiple subcategory selection in Django models
I want to implement multiple choice field in model for example i have table named as Category and Subcategory and what i want when i add subcategory i can select multiple Categories using checkbox and categories are stored in a list. NOTE : Categories will come dynamic -
How to achieve multiple sorting levels in Django ORM Queries
On the below Posts model , I need to sort the posts by both date and likes. the results should be last 24 hr posts ,sorted by likes , then the next day posts sorted by likes , it goes on.. class Posts(models.Model): comment_text= models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now()) likes = models.IntegerField(default=0) views.py latest=Posts.objects.filter().order_by(-date,-likes) the above query is not giving the desired results , let us say if there are two posts created at 07/06/2021 at 1 pm which has 3 likes and another one at 1:30 pm which as 1 like. Then the post created at 1:30 pm with 1 like comes on top instead of the post at 1 pm with 3 likes -
How to solve AttributeError: 'NoneType' object has no attribute 'encode' in Django
I tried to give validation to the give form in the HTML file using JAVASCRIPT and also check the email is available or not in the database table using AJAX.Also imported sha256 from hashlib.But I got an error like this. I did not understand why this error happens.Can anyone suggests a solution for this problem. Internal Server Error: /User/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 214, in userregister epassword = sha256(upassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' HTML file: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>User Registration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script type="text/javascript" language="javascript"> function getsid(str) { print(str) if(window.XMLHttpRequest) { xmlhttp= new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readystate==4 && xmlhttp.status==200) { document.getElementById("lemail").innerHTML= xmlhttp.responseText; } } xmlhttp.open("GET","{% url 'checkemail' %}?id="+str,true); xmlhttp.send(null); } </script> </head> <body> <section class="sreg" id="sreg"> <div class="container-fluid"> <div class="htop"> <h4>User <span>Register Form</span></h4> </div> <div class="row"> <div class="col-12"> <form method="POST" name="contact" action="{% url 'userregister' %}"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name"> <span id="lfname"></span> </div> <div …