Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Query database from Channels consumers.py (WebSocket is closed before the connection is established)
I had live chat functionality working, but now I am trying to add a query to the database within the connect method. I am following the Channels documentation, and tried the solution in this other StackOverflow question but nothing is working. Below is my code. The error I'm seeing in the Javascript console is WebSocket connection to 'ws://localhost:8000/ws/chat/334/' failed: WebSocket is closed before the connection is established. I do have redis-server running on localhost and that was working before, so that's not a problem. async def connect(self): print('connect (got here!)') self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('self.room_name: ' + str(self.room_name)) valid_connection = await database_sync_to_async(self.verify_chat_room_key)() print('valid_connection: ' + str(self.valid_connection)) # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def verify_chat_room_key(self): trans = database_sync_to_async(Transaction.objects.get)(id=self.room_name) print('trans.status: ' + str(trans.status)) return True -
How to modify docker settings for multiple database for a django project?
My development file is as follows: version: '3' services: db: image: mdillon/postgis container_name: sl_database ports: - "5432:5432" volumes: - db_vesatogo_starling_v1:/var/lib/postgresql/data env_file: - ./config/dev.env networks: - db_network pgadmin: image: dpage/pgadmin4:4.28 container_name: sl_admin links: - db depends_on: - db environment: PGADMIN_DEFAULT_EMAIL: admin PGADMIN_DEFAULT_PASSWORD: password ports: - "80:80" networks: - db_network redis: image: redis:latest container_name: sl_redis ports: - "6379:6379" restart: always networks: - redis_network networks: db_network: driver: bridge redis_network: driver: bridge volumes: db_vesatogo_starling_v1: static: Now, I have introduced a replica databases in my settings. What changes should I make in my development file to implement multiple databases? I tried adding database on another server which in this case is 5433 as I am running my main db on 5432 but it is showing me following error: "could not connect to server: Connection refused Is the server running on host "db-replica" (172.25.0.3) and accepting TCP/IP connections on port 5433?" Please help me out! -
How to get the model instance calling the mixin?
I am putting the form_valid() method into a mixin like this.. ''' class PaymentAtomicMixin(object): @transaction.atomic def form_valid(self, form): try: with transaction.atomic(): self.instance = form.save(commit=False) .... .... form.instance.user = self.request.user return super().form_valid(form) ''' 3 models are sub-classing/utilizing this mixin, and I will have to perform different actions depending on what model is executing the form_save() method. How will I know which model and the model instance is utilizing the mixin? (Django 3.2.7, Python 3.9.5) -
Need to deploy django app in Apache windows server 2016, Without C++ Build Tools
I have a Django app, I need to deploy this in Apache windows server 2016. But we were not able to deploy because of licensing issue. To deploy in windows we need Microsoft c++ build tools, but we can't install them because it's bundled with Visual Studio MSDN licensing. We are getting Microsoft c++ dependency errors while trying to install "wsgi" package, could you please tell me any alternate solution to install wsgi and deploy it in apache without using Microsoft c++ build tools. Thank You!! -
when i trying to add a data to database with Django i got error calls NOT NULL constraint failed: pages_login.password
The strange thing is I cant send data and add it to data base when I make user_data.save() comment and open the page then delete the # but when I go our from the page and try to join it again I got the error " NOT NULL constraint failed: pages_login.password " models.py folder from django.db import models class Login(models.Model): username = models.CharField(max_length=40) password = models.CharField(max_length=20) views.py folder from django.shortcuts import render from .models import Login def index(request): index_context = { 'name': 'yahia', 'age': '20', } return render(request, 'pages/index.html', index_context) def about(request): usernamee = request.POST.get('username') password = request.POST.get('password') user_data = Login(username=usernamee, password=password) user_data.save() return render(request, 'pages/about.html') here the user_data.save() when i comment it like this #user_data.save() the code word and the page opens and i can send the data when i remove the # but when i restart the page i get the error admin.py page from django.contrib import admin from .models import Login # Register your models here. admin.site.register(Login) the full error IntegrityError at /about/ NOT NULL constraint failed: pages_login.password Request Method: GET Request URL: http://127.0.0.1:8000/about/ Django Version: 3.2.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_login.password Exception Location: C:\Users\a\OneDrive - Higher Technological Institute\Desktop\test\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in … -
How to precisely set breakpoint when debugging remotely using PDB
I want to set breakpoint in like() function in below source code, ## views.py @csrf_protect @login_required def like(request, comment_id, next=None): However, in PDB prompt, when I use command break views.like to set break, the breakpoint goes to Breakpoint 1 at /usr/local/lib/python3.7/site-packages/django/utils/decorators.py:119, then after so many subsequent continue and next commands expecting to step into like() function soon, i failed and got lost. is there a way to set breakpoint and skip all those decorators ? or any convenient ways for me to view source file (views.py) remotely under PDB command prompt to identify which line to set breakpoint ? -
Two many values to unpack (expected two)
I'm making a python project for returning recipes with certain genres or ingredients. I'm getting a two many values to unpack error thrown when I am trying to create the genre in my database. def createbgenre(request): BreakfastGenre.objects.create(genre=request.POST['genre'],user=User.objects.get(request.POST['user'])) return redirect ('/breakfast') this breakfastgenre object creation is throwing the error. -
Is there a way to import a file in forms.py or views.py?
In my Django project I created a subdirectly country/translations where country is the name of the app, translations is the folder. I created __init__.py inside it, so Python will recognize it as a module and inside it I created a file, countries_fr.py. Inside countries_fr.py I have this custom translation function: def t_countries(c): country_dict = { "Albania" : "Albanie", "Algeria" : "Algérie", "Antigua and Barbuda" : "Antigua-et-Barbuda", "Argentina" : "Argentine", "Armenia" : "Arménie", # etc. } if c in country_dict: return country_dict[c] return c I don't use gettext in this case because the country list come form a json file and gettext doesn't translate data coming from databases or files. I want to use it in Forms.py this way def get_country(): filepath = 'myproj/static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('----', _("--- Select a Country ---"))] for x in all_data: y = (x['name'], t_countries(x['name'])) all_countries.append(y) return all_countries The problem is I can't import the infamous function I tried all this from .translations/countries_fr import t_countries from .translations.countries_fr import t_countries from translations.countries_fr import t_countries from translations import t_countries from translations import countries_fr from .translations import countries_fr from translations import t_countries from countries.translations import countries_fr from countries.translations.countries_fr import t_countries import countries.translations and more I have … -
Django channel occasionally gets error "cannot call this from an async context - use a thread or sync_to_async"
My project recently added django channel for websocket and layer: Django=3.2.6 Channel=3.0.4 channels-redis="3.3.0" gevent=21.8.0 gunicorn=20.1.0 Gunicorn and daphne run WSGI and ASGI separately, Nginx proxy the traffic to WSGI or ASGI. In my production environment, it has less 0.1% chances to get cannot call this from an async context - use a thread or sync_to_async. These errors are not from ASGI(daphne) but from normal WSGI(Gunicorn) requests, they didn't occur in same piece of code but the root cause is a database query. For example, this is in a database query: Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/dist-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/opt/www/myproj/myproj/services/member_service.py", line 275, in _wrapped_view return view_func(api_view, request, *args, **kwargs) File "/opt/www/myproj/myproj/api/restful/form.py", line 108, in get published_form = PublishedForm.objects.get_latest_published_for_form(form_identifier, try_master_form=False) File "/opt/www/myproj/myproj/webform/models.py", line 44, in get_latest_published_for_form return self.filter(form_case__identifier=form_identifier, form_case__form_state=FORM_STATE_PUBLISHED).latest('version') File … -
How to insert a new row for each data in django?
I have a multiselct data (using select2) - by which user can select multiple datas and do a post ! This is how i receive the post request: <QueryDict: {'csrfmiddlewaretoken': ['XNcF2x.......'], 'document_type': ['equivalent', 'level', 'passport']}> So now, i need to insert new rows for each of "document_type", in other words if document_type has three datas then i need to make 3 new rows ! How to do that ? I have read few things bulk_create or is there any efficient way to achieve this ? -
How to protect Nginx autoindex within the scope of a Django project?
So I have a Django application that's not publicly accessible. I also utilize an autoindex through nginx which users can access. Problem is so can everyone else on the internet. How can I protect this autoindex location so that only logged in users can view it? -
Django Error - ValueError: Field 'id' expected a number but got 'company'
I'm currently writing an application in django called account, now everything was working fine (as it usually happens), but I had to add more information in my models.py file, and all of the sudden, I got problems running the migrations, certainly as django enthusiast the usual approach is to delete all the migrations in the migration folder, delete the Database and finally run the usual set of commands. Unfurtunetely this time, that trick is not solving my problem, and I'm getting the following error: ValueError: Field 'id' expected a number but got 'company'. That error appears when I type python manage.py migrate, the run migration runs without problems, and a migration 0001 file and a database is created, but I still get the error when running the migrate command. models.py from django.db import models from django.conf import settings from django_countries.fields import CountryField from phone_field import PhoneField from djmoney.models.fields import MoneyField class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.user class Company(models.Model): company = models.CharField(blank=True, max_length=30) def __str__(self): return self.company class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = … -
Django: How can I changes values via views.py
I am trying to make a "upload" page so that I can upload a file and process to postgres DB using pd.to_sql(). All the data has been succefuly recorded into DB, but cannot change the values of "is_recorded" and "has_issue". Here is the files I am working on so far. In upload/models.py from django.db import models class Upload(models.Model): file_name = models.FileField(upload_to='uploads', max_length=255) uploaded = models.DateTimeField(auto_now_add=True) # When uploaded successfully is_recorded = models.BooleanField(default=False) # When it has a problem to fix has_issue = models.BooleanField(default=False) def __str__(self): return f'{self.file_name}: {self.id}' In views.py import os from django.shortcuts import render from core.db_implements import upload_csv_to_DB from upload.forms import UploadForm from upload.models import Upload def upload_view(request): error_message = None success_message = None form = UploadForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = UploadForm() try: obj = Upload.objects.get(is_recorded=False) recorded, issue, success_message, error_message = ***upload_csv_to_DB***(obj) obj.is_recorded = recorded obj.has_issue = issue obj.save() success_message = success_message error_message = error_message except: error_message = 'Something went wrong.' context={ 'form': form, 'success_message': success_message, 'error_message': error_message, } return render(request, 'upload/upload.html', context) In forms.py from django import forms from django.db.models import fields from django.forms.fields import FileField from django.forms.models import ModelFormMetaclass from .models import Upload class UploadForm(forms.ModelForm): # file_name = forms.FileField(max_length=255, label=False) … -
Remove record from database when session is expired
My cart is working based on sessions and Cart model. When an item is added to the cart the session is created and product added to the Cart model. Delete product from cart is handled by this function: def remove_cart(request, slug): cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) try: product = Product.objects.get(slug=slug) cart.products.remove(product) cart.total -= product.price cart.save() except Product.DoesNotExist: pass except: pass if cart.products.count() < 1: cart.delete() return HttpResponseRedirect(reverse("cart")) When the user deletes every item from the cart, the record is deleted from the database so it doesn't store empty records. The problem is when the user leaves items in the cart and the session expires (for example: user logged out). The record stays in the database and will never be used again, so it just takes up space. What would I have to do, to delete the Cart model, when the session is expired? The Cart id corresponds to the session name. -
How to create new python classes with different names dynamically in a cycle? [duplicate]
I'm making a kind of online shop. I have a base abstract class and child classes for all products. ***models.py*** class Item(models.Model): class Meta: abstract = True class FirstItem(Item): pass class SecondItem(Item): pass I register all classes in admin.py ***admin.py*** class FirstItemAdmin(admin.ModelAdmin): inlines = [] def foo(): pass class SecondItemAdmin(admin.ModelAdmin): inlines = [] def foo(): pass admin.site.register(FirstItemAdmin) ... How can I dynamically create new classes with different names like class ThirdItemAdmin(), class FourthItemAdmin(), class FifthItemAdmin()... in a cycle so that these classes could be registered in further code ? admin.site.register(ThirdItemAdmin) admin.site.register(FourthItemAdmin) ... I tried like that def classMaker(*args, **kwargs): for class in args: new_class_name = cls.__name__ + 'Admin' type(new_class_name, (admin.ModelAdmin,), {}) classMaker(FirstItem, SecondItem, ThirdItem, FourthItem, FifthItem) and all classes are created, but they are invisible in further code. Is there a way to make it dinamycally or I'll have to make classes for all items manually ? -
how to get object numbers in django models
I am a new user in Django and I am trying to print the total number of objects in a model but this code below prints the query set with its title. Here's my function def showthis(request): count= Item.objects.count() print (count) I need to get the total number of objects in Model Item -
Django Sockets: ConnectionRefusedError at /robot/1, [Errno 111] Connection refused
I am trying to connect to another device on my same network, a robot running on a raspberry pi but when I try to connect I get the error. I am not sure what is causing it because they are on the same IP 127.0.0.1. If anybody has any ideas on what is causing it the help would be great. My View: HEADER = 64 PORT = 6060 SERVER = '127.0.0.1' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' def form_valid(self, form): self.object = form.save() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) client.send(send_length) client.send(message) send("HELLO") print(self.object) send(DISCONNECT_MESSAGE) return render(self.request, "theblog/bloghome.html") My Raspi Code: HEADER = 64 PORT = 6060 SERVER = '127.0.0.1' ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" print(SERVER) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[NEW CONNECTION] {addr} connected") connected = True while connected: msg_length = conn.recv(HEADER).decode(FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(FORMAT) if msg == DISCONNECT_MESSAGE: connected = False print(f"[{ADDR}] {msg}") conn.send("MSG Received".encode(FORMAT)) return msg conn.close() def start(): server.listen() print(f"[LISTENING] Server … -
Models and serializers Django
I'm working on the back end part of the project and I'm facing an issue that I cant through Postman send an API request for POST, GET or PUT data in model_seconds field. At this point, no required any front end part, only back end. thanks Models: class ModelBase(models.Model): email = models.EmailField(blank=True) phone = models.CharField(max_length=32, blank=True) first_name = models.CharField( max_length=64, blank=True, verbose_name=_(u'First name') ) last_name = models.CharField( max_length=64, blank=True, verbose_name=_(u'Last name') ) name = models.CharField(max_length=128, blank=True, editable=False) ] birth_date = models.DateField(null=True, blank=True) personal_code = models.CharField( max_length=32, blank=True, verbose_name=_(u'Personal code') ) hobbies = models.CharField( max_length=128, blank=True, verbose_name=_(u'Hobby') ) legal_name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Legal name') ) registration_nr = models.CharField( max_length=32, blank=True, verbose_name=_(u'Registration Nr') ) legal_address = models.CharField( max_length=128, blank=True, verbose_name=_(u'Address') ) country = models.ForeignKey( Country, blank=True, null=True, related_name='+', verbose_name=_('Country'), on_delete=models.CASCADE ) state = models.CharField( max_length=128, blank=True, verbose_name=_(u'State/province') ) city = models.CharField( max_length=128, blank=True, verbose_name=_(u'City') ) zip_code = models.CharField( max_length=32, blank=True, verbose_name=_(u'ZIP code') ) class Meta: abstract = True def __str__(self): if self.hobbies: return self.hobbies elif self.legal_name: return self.legal_name elif self.name: return self.name elif self.email: return self.email else: return self.phone class Models(ModelBase, UUIDIdMixin): friend = models.ForeignKey(Merchant, related_name='models', on_delete=models.CASCADE) account = models.ForeignKey(Account, related_name='models', on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='models', on_delete=models.CASCADE) modified = models.DateTimeField(auto_now=True) class … -
How to increase read and write time after using DJango storages package?
I have a web app running on DJango which currently uses the DJango Admin interface as front end. Till date I had been using the default file system of the server for storing my media files, recently I ran out of space and chose to go for a third party storage service like AWS S3. But for all the images uploaded to my server I need to create a Dropbox link so I planned to use the DJango Storages package and set Dropbox as the default storage backend. It work fine, but the problem is that the reading and writing is very slow. It takes a lot of time to upload the images and to view the same. The loading time is very very slow. But the moment I change my storage backend it fastens up again. Is it due to using the DJango storages package? Is there a work around for the same? Yes I’m aware that I can use DJango queued storage for uploading but that’ll fix uploading speed and not the reading time. -
How do I create a function to update many entries at once in Django SQLite database?
I have a functioning application, but would like to streamline aspects. I have create, update and view pages for a table of about 20 instances of Post2. I would like to assign a function to a button that would update all player1, player2 and player3 to "Empty". Even better would be to set it to a weekly timer. Any help would be very much appreciated, nothing I've tried has worked. The following is my models.py- class Post2(models.Model): time=models.CharField(max_length=50) player1=models.CharField(max_length=50, default="Player 1") player2=models.CharField(max_length=50, default="Player 2") player3=models.CharField(max_length=50, default="Player 3") def __str__(self): return self.time This is my views.py- def teetimes(request): posts=Post2.objects.all() return render(request, 'memtees2/teetimes.html', {'posts':posts}) def add(request): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post2.objects.create(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'New Time has been added') return render(request,'memtees2/add.html') def update(request,id): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] Post2.objects.filter(id=id).update(time=time,player1=player1,player2=player2,player3=player3) messages.success(request,'Information has been updated, return to Tee-Times to view ') post=Post2.objects.get(id=id) return render(request,'memtees2/update.html',{'post':post}) -
How to link 3rd party model and view with own model in Django
I successfully implemented django-contrib-comments to my project and starting to adjust it step by step to make it 100% suitable to my project. Now I have the following issue which I cannot solve: I have a model Poller which offers two possible votes for any user stored in the model Vote. Now if a user comments on a poller I would like to return his individual vote for this specific poller to the rendered comment in the template. Since I don't wanna touch the 3rd partie's architecture by any means, I would prefer to get the required queryset in my view. Comment model of django-contrib-comments package class CommentAbstractModel(BaseCommentAbstractModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), [..] My Poller, Vote and Account/User models class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) [..] class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='vote') user = models.ForeignKey(Account, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) [..] class Account(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) [..] -
django social does not return user after login
I am trying to setup social login with GitHub using the Django social package. I am able to complete the begin by visiting http://127.0.0.1:8000/api/v1/auth/login/github/ and the I get redirected to the complete page as expected. The login is appears to be successful as it sends me to the SOCIAL_AUTH_LOGIN_REDIRECT_URL I have specified in my settings. Now the view has a IsAuthenticated permission requirement and throws an error that credentials are not provided. I expected that after the login completes that the logged in user is added to the request but that does not seem to be the case as request.user is an Anonymous user. How can I get the logged in user after I am redirected from the oauth provider page successfully. My end goal is to return the access token to my spa from end and query the convert-token endpoint to get a jwt which I can then use for all my routes. Any example on how I can achieve this would be greatly appreciated. view # @permission_classes([IsAuthenticated]) class MyProfileView(APIView): def get(self, request): # profile = UserProfile.objects.get(user=request.user.id) # serializer = UserProfileSerializer(profile) # return Response(serializer.data) social = request.user.social_auth.get(provider='provider name') return social.extra_data['access_token'] -
Finding total score from specific user's maximum score in django orm
I have a function that gets two parameters(contest_id,user_id), how could i get maximum score of each problem in given contest for the given user and then sum up all those max scores? each problem can have zero or many submitted scores. for example : (problem_id,submitted_score) --> (1, 80), (1, 100), (2, 150), (2, 200), (3, 220), (3, 300) expected result for this example should be 600, 100 + 200 + 300. Models: class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants') class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey(User, on_delete=models.DO_NOTHING) score = models.PositiveIntegerField(default=100) class Submission(models.Model): submitted_time = models.DateTimeField() participant = models.ForeignKey(User, related_name="submissions", on_delete=models.DO_NOTHING) problem = models.ForeignKey(Problem, related_name="submissions", on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) -
how to pass query parameters from DRF serializer
when we pass query params through a request to DRF, are query params passed through serializer ? or is there any way to pass them from serializer ? -
My Django custom signup form does not save new users in the Database even after i have tried everything i can
**So am trying to build a signup page for users on my app but, after i built it, when a user sings up, they are not registered in the database. I used the Django form and also used html and CSS for styling but my custom form does not register user on the database this is the views.py section passing the form after it has been created in the forms.py** def customerRegister(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.save() group = Group.objects.get(name = 'Customer') user.groups.add(group) messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request,'kumba/register.html', context) *forms.py this is my custom form with specific information needed from the user* class CreateUserForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'required' : "", 'name': "username", 'id' : 'username', 'type': 'text', 'placeholder' : 'Enter Username.....', 'class' : 'form-input' }) self.fields['email'].widget.attrs.update({ 'required' : "", 'name': "email", 'id' : 'email', 'type': 'email', 'placeholder' : 'Enter Email.....', 'class' : 'form-input' }) self.fields['password1'].widget.attrs.update({ 'required' : "", 'name': "password1", 'id' : 'password1', 'type': 'text', 'placeholder' : 'Enter password.....', 'class' : 'form-input' }) self.fields['password2'].widget.attrs.update({ 'required' : "", 'name': "password2", 'id' : 'password2', 'type': …