Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django app to Python Anywhere through GitHub
I am currently trying to set up a deployment pipeline for my django app to pyhton anywhere. But the github Webhook recieves a 301 and I don't understand why... "Last delivery was not successful. Invalid HTTP Response: 301" I followed the instructions from this tutorial: https://digitalshyna.com/blog/how-to-deploy-django-apps-to-python-anywhere-through-github/ I added the update url: path('update_server/', views.update, name='update'), this is my update view: @csrf_exempt def update(request): if request.method == "POST": try: # Log the incoming request logger = logging.getLogger('webhook_logger') logger.info("Webhook POST request received") # Perform the code update repo = git.Repo('mayapp.pythonanywhere.com') origin = repo.remotes.origin origin.pull() # Log a success message message = "Updated code on PythonAnywhere" logger.info(message) return HttpResponse(message) except GitCommandError as e: # Log a Git error and return an error response error_message = f"Git Error: {str(e)}" logger.error(error_message) return HttpResponseServerError(error_message, status=500) else: return HttpResponse("Couldn't update the code on PythonAnywhere") GitPython is installed in my Pythonanywhere virtualenv. I created the deploy key and added it to my repository on github. I created a second ssh-key and added it to my github account, I added both keys to the ssh-agend on pythonanywhere. https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent When I access the route directly with Postman I see "Couldn't update the code on PythonAnywhere" Status Code 200 OK My log … -
Running Raw sql query in django signal giving is throwing error
I am trying to run a CTE in my django application I have a model class WorkflowStepDependency(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) step = models.ForeignKey('WorkflowStep', on_delete=models.CASCADE, related_name='step') step_dependency = models.ForeignKey('WorkflowStep', on_delete=models.CASCADE, related_name='step_dependency') step_dependency_status = models.ForeignKey('WorkflowStepStatus', on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.step}'s dependency on {self.step_dependency}'s {self.step_dependency_status}" class Meta: ordering = ['created_on'] I am trying to run a cte in one of my signals @receiver(post_save, sender=WorkflowStepInstance) def workflowStepInstanceUpdated(sender, instance, created, **kwargs): table_names = connection.introspection.table_names() print(table_names) if not created: with connection.cursor() as cursor: cursor.execute(""" WITH hierarchy AS ( SELECT step ,step_dependency ,1 AS lvl FROM Projects_workflowstepdependency WHERE step = %s ) ,lvls AS ( SELECT lvl ,step FROM hierarchy GROUP BY lvl ,step ) """, [instance.workflow_step] ) This is giving me error saying -
How to query models with a related model in a onetoone relationship in Django?
Models from the one-to-one Django docs: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return f"{self.name} the place" class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) How would I query "Place objects with name 'foo' or Place objects that have a Restaurant"? It needs to be one queryset, so I can return it to django-ninja for an API. -
Not able to add new instance of model, not even using Django Admin panel
For several months I am programing a web app using Django for learning purposes. I created class me function based view to create new entries of many model but for this one something is off. First I was unable to add using CBV, then I switch to function base view. I tried using forms.py or directly with template but every time I get clean console, good redirect but no new entry. Then I tried to create it just using Admin panel but i would get something like "The performance review “PerformanceReview object (1e549e2c-4b3d-4030-9007-b889265ed908)” was added successfully.", but the list of objects was still empty. As this message is basically a link when i try to follow it i get this message: "Performance review with ID “1e549e2c-4b3d-4030-9007-b889265ed908” doesn’t exist. Perhaps it was deleted?" -I did 'makemigrations' and 'migrate' -While this was happening rest of the app still worked as expected -Admin.py has model registred -All fields are correctly presented within Admin form -Validators work correctly from django.contrib import admin from . models import PerformanceReview # Register your models here. admin.site.register(PerformanceReview) I don't think that the rest of code is relevant as the Admin panel not working is the thing that puzzles … -
Django - Necessary to create own account adapter?
I am using django-allauth. I want to make use of the send_mail function that is found inside allauth.account.adapter import DefaultAccountAdapter. Is it necessary for me to create my own adapter that simply inherits the allauth DefaultAccountAdapter and what is the purpose if I am not modifying anything inside it? adapters.py from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): pass myAdapter = MyAccountAdapter() settings.py ACCOUNT_ADAPTER = 'api.adapters.MyAccountAdapter' views.py from .adapters import * myAdapter.send_mail(...) -
How to Create and Save Database Objects for Django Tests in the Same Test Case?
I'm working on Django tests, and I have a base class for my tests where I define some common variables and methods. I want to use fixtures or a similar approach to create database objects and use their attributes in the test data. However, I encountered an issue where the objects created in the base class are not available in the test class. Here's my simplified test structure: test_base.py: class BaseTestCases: class BaseEndpointTest(APITestCase): @classmethod def setUpClass(cls): super().setUpClass() # Create users and set up API clients @classmethod def tearDownClass(cls): # Delete users super().tearDownClass() # Other methods... def create(self, data, main_user=True): # Create API request # ... # Other code in test_base.py test_cities.py: class TestCities(BaseTestCases.BaseEndpointTest): endpoint = "cities" # Create a city object using create_city() p_key = create_city().pk print(Country.objects.all()) # Test data data = {"name": random_string(), "country": p_key} The problem is that when I print Country.objects.all() in test_cities.py, it contains the result of create_city(), but when I print the same in test_base.py using the create method, it doesn't contain the newly created record. I believe this is because the objects created in the base class are not being saved to the test database. How can I create and save objects in the … -
Use other table & column names for authenticate function in django
I have pre existing table with table name='XYZUsers' which columns names as user_id, XYZ_password. I want use authenticate function in django by passing user_id, XYZ_password instead of using normal username , password. How I can acheive this? Models.py class XYZUsers(models.Model): user_id = models.CharField(primary_key=True, max_length=30) XYZ_password = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'xyz_users' views.py def Login_user(request,Username,Password): print(Username) print(Password) try: PYX_Users=XYZUsers.objects.get(user_id=Username) except Exception as e: print('user not avaialble') PYX_Users=authenticate(request,PYX_Users.user_id=Username,PYX_Users.XYZ_password=Password) print(PYX_Users) if Gains_Users is not None: auth_login(request,PYX_Users) return JsonResponse(str('1'),safe=False) else: return JsonResponse(str('0'),safe=False) -
Python's time.sleep() function freezes Postgres DB time in Django tests
I need to make a pause in my Django project's test (I use pytest-django) and time.sleep() kind of works but with a strange side effect. It pauses the execution of the code as expected but it also stops Postgresql's "in-DB clock" that is not desired. Here is an example: from pytest import mark, fixture, raises from django.db import connection from django.utils import timezone import sys, datetime as dt @mark.django_db def test_db_time (): print('Code time before:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() before:', t_before := cursor.fetchone()[0], file = sys.stderr) sleep(1.56) print('Code time after:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() after:', t_after := cursor.fetchone()[0], file = sys.stderr) assert t_before != t_after, 'I need a nap!' When run this test with pytest, I get the next output: ========================================= test session starts ========================================= platform linux -- Python 3.10.1, pytest-7.4.0, pluggy-1.0.0 django: settings: pms.settings (from ini) rootdir: /home/nikita/files/projects/pms/dev configfile: pyproject.toml plugins: django-4.5.2 collected 1 item sis/tests/db/triggers/test_answer.py F [100%] ============================================== FAILURES =============================================== ____________________________________________ test_db_time _____________________________________________ def test_db_time (): print('Code time before:', timezone.now(), file = sys.stderr) with connection.cursor() as cursor: cursor.execute("SELECT NOW()") print('DB NOW() before:', t_before := cursor.fetchone()[0], file = sys.stderr) sleep(1.56) print('Code time after:', … -
How can i distinguished request actions in a serializer DRF Django
class EmailSerializerU(serializers.ModelSerializer): customlink = serializers.SerializerMethodField() class Meta: model = Email fields = ['id','owner','address','type','primary','customlink'] def get_customlink(self, instance): #Here Logic IF Action=List then A) IF Action=GET THEN b) full_url = ''.join(['http://', get_current_site(req).domain])+'/emails' return full_url In the def_get_customlink function i am trying to set the full_url depending on the action of the URL/API. How can i access this value? Is the context/the request somehow available? List Actions have a link to singel object url: emails/3 Get/View Actions have a link to the list of objects url: emails/ tried self.action, didnt work. self.action leads to 'EmailSerializer' object has no attribute 'action' tried self.context, but it shows an url not an action like in views, where self.action is set. req=self.context['request'] print(req) GET /emails/ HTTP/1.1" 200 21865 GET /emails/4/ HTTP/1.1" 404 15897 -
How to display child elements in a comment system
I'm implemeneting a comment system where a users can reply to each others comments. To do this I'm using MPTT and following along with this very good tutorial (https://www.youtube.com/watch?v=j7vj4k13xDY&list=WL&index=5). The problem I've come across is that I want to load the replies to comments dynamically, when someone presses a button, rather than load all the replies to every comment when the page first loads. The way the tutorial shows how to load comment replies is like so: {% if comments %} {% load mptt_tags %} {% recursetree comments %} #Use comment objects here, e.g {{ comment.description }} {% if not node.is_leaf_node %} #Displays the child elements <div class="pl-2">{{ children }}</div> {% endif %} {% endrecursetree %} This works fine when I was loading all the comments and replies at once, however as I'm now moving to loading the replies when a user clicks a button on the parent comment I'm having problems. I'm trying to use HTMX to load in the replies once this button is clicked but am having trouble accessing all the children. It's hard to figure out what to do as it just magically "works" with using the {{ children }} variable above. When I try and … -
Django Treebeard on how to use 'Position' and 'Relative to' in a customized form
I'm using treebeard and the materialized path trees to give tech support the ability to create troubleshooting guides. Each parent node will be the title of the guide and descendants of that parent node will be the steps to take. I've made a model to inherit from MP_Node with a few additional fields that I will be using to help create these guides such as name, description, step_type, etc. The form I've made for this is inheriting from the MoveNodeForm class which allows you to define the Position and Relative to fields that come with the class. It seems to me that the only way to access those fields is to call the entire form in the template like so {{ form|crispy }}. I would like to be able to use my form in a way where im calling each field one at a time so that I can make custimizations such as a RadioSelect for my step_type field, otherwise it will display as a dropdown in the form. Is there a way to access these fields Position and Relative to without calling the entire form? Can I not access those fields in my customized form class so that I … -
Arrows for carousel
I have the carousel with images from django <section id="container-id" class="container"> <div class="carousel"> <div class="slider"> {% for ph in photos %} <img id="{{ph.pk}}" src="{{ph.photo.url}}" class="slide"> {% endfor %} </div> <div class="slider-nav"> {% for ph in photos %} <a href="#{{ph.pk}}"></a> {% endfor %} </div> </div> </section> how can i add arrows for left and right slides? i tried bootstrap but it didnt work, so im here... :) -
django ckeditor 5 multiline toolbar
I'm trying to use django-ckeditor-5 and it works fine, but when I try to make a multiline toolbar and add "-" to the toolbar config nothing happens. here is my config: https://pastebin.com/G52EgEVt As you saw in my config, I did put a "-" before bulleted list, but nothing changes: Here is my models.py: class Post(models.Model): title = models.CharField(max_length=120, null=False, blank=False, verbose_name='عنوان') body = CKEditor5Field(config_name='extends', verbose_name='بدنه') I also tried putting "shouldNotGroupWhenFull": True in the "extends" config, but nothing happened -
Cannot access Django admin on production
My setup: Backend Django, Frontend React I have a website dockerized on production in following configuration: one container for serving static files, reverse proxy using nginx second for django backend. On development (without docker I am just running django admin using default configuration localhost:8000/admin), no issue here. The problem is on production. I think I have to add a location to /admin, otherwise it will be handled by frontend which I assume won't work with django admin. This is my full nginx conf: server { listen 80; server_name <website_url>; server_tokens off; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name <website_url>; server_tokens off; ssl_certificate /etc/letsencrypt/live/<website_url>/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/<website_url>/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; client_max_body_size 100M; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { try_files $uri @proxy_api; } location /auth { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend:8000; } location /admin/ { alias /app/backend/server/django_static/; } location /django_static/ { autoindex on; alias /app/backend/server/django_static/; } location /media/ { autoindex on; alias /app/media/; } } I tried to first add a … -
Parent Child Hierarchy in Django Model Serializer
I am trying to create a serializer of a django model where in this serializer I show the parent and all the generations below. In the model I have a field that's the "object_id" => (pk) and another field "parent_object_id" which indicates which pk is the parent: object_id | parent_object_id | object_name | 1000 | null | Product | 1001 | 1000 | Fruits | 1002 | 1000 | Veggies | 1003 | 1001 | Apples | 1004 | 1001 | Bananas | 1005 | 1003 | Variant a | 1006 | 1003 | Variant b | A.Product (highest node) Fruits 1.1 Apples 1.1.1 Variant a 1.1.2 Variant b 1.2 Bananas 1.2.1 Variant x Veggies 2.1 Spinach 2.1.1 Variant n 2.1.2 Variant y 2.2 Potatoes 2.2.1 Variant c 2.2.2 Variant g 2.2.2.1 Some other variable 2.2.3 Variant l Any suggestions on how I can achieve this? I just can't get my head around how to achieve this. -
MongoDB (Djongo) + Django | NoneType' object has no attribute 'attname'
I try to use MongoDB with Django. After several research, i found that to use both together, i had to: Downgrade Django to 3.1.12 Install djongo Dwongrade Pymongo to 3.12.3 Install pytz Here is my models: class Choice(models.Model): choice_text=models.CharField(max_length=200) votes = models.IntegerField(default=0) class Meta: abstract=True class Question(models.Model): question_text=models.CharField(max_length=200) pub_date = models.DateTimeField() choices=models.ArrayField( model_container=Choice ) I registered the model to the admin: from .models import Question # Register your models here. admin.site.register(Question) And run the server: everything goes alright. However, when i try to add an item via administration site, i got the following exception: ') -
Writing raw sql CTE in Django
I have a team hierarchy model class Hrc(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) emp = models.ForeignKey('Employee', on_delete=models.CASCADE, related_name='emp') mang = models.ForeignKey('Employee', on_delete=models.CASCADE, related_name='mang') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] Since I want to get the hierarchy under a particular given employee, I want to use CTE. I want to write a CTE in one of the Django Signals I have. Below is the signal I have @receiver(post_save, sender=Employee) def employeeUpdated(sender, instance, created, **kwargs): if not created: //I want to get the hierarchy under an employee (instance in this case). So the // CTE should be written here The CTE I want to write is with hierarchy as ( select emp, mang, 1 as lvl from hrc where emp = instance union all select child.emp, parent.emp, lvl+1 from hierarchy as parent join hrc as child on child.mang = parent.emp ), lvls as ( select lvl, emp from hierarchy group by lvl, emp ) select lvl, STRING_AGG(emp, '') within group (order by emp) from lvls group by lvl; How can I write this cte in the signal and get the desired result. -
Run a function when celery task correctly ends in Django
I'm using Django and Celery and I'm correctly executing Celery tasks with @shared_task(bind=True) def start_serial_acquisition(self, idObj, porta_COM): and start_serial_acquisition.delay(instance.pk, porta_COM) I would like to call or execute a specific function when a celery task ends with the SUCCESS flag. Are there any decorators like Django @receiver(pre/post,) as I can't find something similar I need to be executed after the tasks end so, a solution that launch the function as last line of the celery task is not suitable for me -
WSGI vs ASGI server with hybrid sync/async Django app
I have a Django app with multiple async views doing some http requests, but some part are still synchronous like most of the middlewares. So there will always be a small performance penalty with the sync/async switch when handling incoming requests. It is possible to run this app on both WSGI or ASGI gunicorn server (using uvicorn worker), but I don't really understand which one is better for an hybrid sync/async Django app. In both cases it seems that there is blocking code in a thread. -
Full size image doesn't show-up when using bs5-lightbox plugin in a Django project
I'm trying to use the bs5-lightbox plugin in a Django project and I'm encoutering some display issues. The plugin seems to be properly implemented and reactive, however when I click on one of the images, it doesn't display the image at the expected size. You can see a video of what's happening on the GH issue page: https://github.com/trvswgnr/bs5-lightbox/issues/ I didn't do it in the video, but if I right click on the small-sized popped up image and "open in new tab", the proper-sized image shows up. I uploaded the script locally but the issue was exactly the same when loading it from the CDN. The script is loaded at the end of my html file, after the bootstrap script. Here's an excerpt of my Django template code. If the image has principale == True, it displays as a single image: {% for image in object.illustrations.all %} {% if image.principale == True %} <figure class="figure"> <a href="{{ image.image.url }}" data-toggle="lightbox" data-gallery="focus-gallery" data-caption={{ image.legende }}> <img src="{{ image.image_thumbnail_medium.url }}" class="img-fluid"> </a> </figure> {% endif %} {% endfor %} And when principale == False, it loads a gallery with the other images: {% for image in object.illustrations.all %} {% if image.principale == False … -
Django SQL Server - near "EXEC": syntax error - Error returned when executing Stored Procedured on Dajndo using SQL Server
I am getting error return below trying to execute Stored Procedured in Django view using SQL Server database with mssql-django. Can you help me to find the solution, below I leave the code of the view and the connection to SQL Server. def arquive1(request): cursor = connection.cursor() try: cursor.execute("EXEC dbo.suspensos") result = cursor.fetchall() finally: cursor.close() context = { 'result': result } return render(request, 'test1.html', context) DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'XXXXXXXX', 'USER': 'xxxxx', 'PASSWORD': 'xxxxxx', 'HOST': 'xxxxxxxx', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } ERROR RETURNED: OperationalError at /app near "EXEC": syntax error Request Method: GET Request URL: http://xxxxxxxx/app Django Version: 4.0 Exception Type: OperationalError Exception Value: near "EXEC": syntax error Yes, that's exactly what I want you to help me with -
Django container on Azure with nginx, CSRF verification failed. Request aborted
I am struggling this now for days. And I can not find any solution. I have a django docker app running on Azure with nginx server: https://dockerdierenwelzijn.azurewebsites.net/admin/login/?next=/admin/ But after login I get this error: Reason given for failure: Origin checking failed - https://dockerdierenwelzijn.azurewebsites.net does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: And of course I googled this error. For example this url: https://stackoverflow.com/questions/70285834/forbidden-403-csrf-verification-failed-request-aborted-reason-given-for-fail But I already have done that. See my setttings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG',0))) ALLOWED_HOSTS = ['localhost', 'dockerdierenwelzijn.azurewebsites.net', 'www.dockerdierenwelzijn.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) #SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") CSRF_TRUSTED_ORIGINS = ["https://dockerdierenwelzijn.azurewebsites.net"] #CSRF_TRUSTED_ORIGINS = os.listdir('CSRF_TRUSTED_ORIGINS') CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "https://dockerdierenwelzijn.azurewebsites.net" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_METHODS = [ "GET" , "POST" ] But then I do: CSRF_TRUSTED_ORIGINS = ["localhost"] It works fine on my localhost. And my nginx config file looks like: upstream DierenWelzijn { server web:8000; } server { listen 80; server_name https://dockerdierenwelzijn.azurewebsites.net; location / { proxy_pass http://DierenWelzijn; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For … -
Django Models - function to get all objects in parent's BaseModel class
class BaseModel(models.Model): id = models.AutoField(primary_key=True) imported_id = models.CharField(max_length=200, blank=True, null=True) class Meta: abstract = True def get_all_imported_id(self): all_objects = xxxxx.objects.all() return [i.imported_from for i in all_objects] class Model_1(BaseModel): .... class Model_2(BaseModel): .... I want to create function "get_all_imported_id" in my BaseModel class that returns a list of values in all my present and future models. When called, e.g. Model1.get_all_imported_id() should return a list of all Models1 imported ids. -
how do you do you migrate to database in test in docker?
i have a simple django app that i am changing to use docker the docker-compose is this version: "3.8" services: ab: build: context: . ports: - "8000:8000" volumes: - ./src:/src environment: - SECRET_KEY=${SECRET_KEY} - EMAIL_ADDRESS=${EMAIL_ADDRESS} - EMAIL_PASSWORD=${EMAIL_PASSWORD} - DB_NAME=askb_db - DB_HOST=db - DB_USER=${DB_USERNAME} - DB_PASSWORD=${DB_PASSWORD} command: > sh -c "python3 manage.py runserver 0.0.0.0:8000" depends_on: - db - migrations db: image: postgres:10-alpine environment: - POSTGRES_DB=askb_db - POSTGRES_USER=${DB_USERNAME} - POSTGRES_PASSWORD=${DB_PASSWORD} i want to run my tests but in order to do that i have to migrate my data to database before that. how should i do that? i have been thinking of adding a new service named migrations.is it the right way of doing that?if yes then my service is going to be like below : migrations: build: context: . volumes: - ./src:/src command: > sh -c "python3 manage.py migrate" depends_on: - db but as you can see its sort of a copy of ab and it does not work.what is the right way of doing that? -
IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_userbankaccount.gender
while preparing registration form i cannot save/register a user. it is not saved in admin panel.it shows the above error.kindly help me. VIEWS from django.contrib import messages from django.contrib.auth import get_user_model,logout from django.contrib.auth.views import LoginView from django.shortcuts import HttpResponseRedirect from django.urls import reverse_lazy from django.views.generic import TemplateView, RedirectView from .forms import UserRegistrationForm User = get_user_model() class UserRegistrationView(TemplateView): model = User form_class = UserRegistrationForm template_name = 'accounts/user_registration.html' def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return HttpResponseRedirect( reverse_lazy('transactions:transaction_report') ) return super().dispatch(request,*args, **kwargs) def post(self, request, *args, **kwargs): registration_form = UserRegistrationForm(self.request.POST) if registration_form.is_valid(): user = registration_form.save() user.save() # login(self.request, user) messages.success( self.request, ( f'Thank You For Creating A Bank Account. ' f'Your Account Number is {user.account.account_no}. ' ) ) return HttpResponseRedirect( reverse_lazy('accounts:user_login') ) return self.render_to_response( self.get_context_data( registration_form=registration_form, ) ) def get_context_data(self, **kwargs): if 'registration_form' not in kwargs: kwargs['registration_form'] = UserRegistrationForm() return super().get_context_data(**kwargs) class UserLoginView(LoginView): template_name='accounts/user_login.html' redirect_authenticated_user = False class LogoutView(RedirectView): pattern_name = 'home' def get_redirect_url(self, *args, **kwargs): if self.request.user.is_authenticated: logout(self.request) return super().get_redirect_url(*args, **kwargs) MODELS from decimal import Decimal from django.contrib.auth.models import AbstractUser from django.core.validators import ( MinValueValidator, MaxValueValidator, ) from django.db import models from .managers import UserManager class User(AbstractUser): username = None email = models.EmailField(unique=True, null=False, blank=False) objects = UserManager() USERNAME_FIELD = 'email' …