Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Json values into databse with Django
how I can insert json values that Im getting from request.get("some url") into database in django? -
Dashbord url unique url generate to permit non connected user to see a specific dashboard
I, m using dash to generate a dashboard for different services / company. I would like to generate a url that permit a user (not connected) to access to his dashboard he dashboard is the same for every user except that data queries differ. I'm using dash in a django app. I really don t know how to code this. -
why does my form validation not work in django
I am trying to make it so that if the user already exists then log in the user else return error message. I read the documentation and implemented it into my own project. I get error: "The view sign_in.views.sign_in didn't return an HttpResponse object. It returned None instead." from django.shortcuts import render, redirect from .forms import SignInForm from django.contrib.auth import authenticate, login from django.contrib import messages def sign_in(request): if request.method == "POST": form = SignInForm(request.POST) else: form = SignInForm() username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("boom-home") messages.success(request, f"Signed in as {user}") else: return messages.error(request, f"Failed to sign in as {user}.") context = { "form": form } return render(request, "sign_in/sign_in.html", context) NOTE: usually this error is because people do not put "return" before the "render" method but I do put return. -
Value from views.py, not getting reflected in HTML page : Django
i got a problem while passing element from views.py to html page , first i will explain about UI , i have a single html page with name . side-menu-light-tabulator.html and UIlooks something like this and when i click on show server list , it will toogle the div and show me another div with another table replacing the old one , as u can see "Document Editor" remains same in header only table changes. consider the first UI as table 1 and second UI as table2 , so i am getting the data for table 2 by performing some queries on table 1 data , table 1 works fine and when performing queries with data obtained from table 1 is also getting printed on terminal , but when i send the data through return render , it is not getting printed in table 2. So here is my code : def secondtableonDashboard(request): Server_list = "" NewList = "" afterConcat = "" conn = pyodbc.connect('Driver={SQL Server};' 'Server=ABC\SQLEXPRESS;' 'Database=WebstartUI;' 'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute("select * from CustomerServer") result = cursor.fetchall() if request.method=='POST': # ------> getting value from first table user_list = request.POST.getlist('checked_list') Server_list = listToString(user_list) +"," else: print("No Values") for listValue … -
Creating a Simple form using django. Stuck between two error, Attribute Error and Key error
This is my form code and I am getting error an Keyerror on line 8 and 9 i.e name and also email.I am also getting attribute error on line with ValidationError. from django import forms from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class StudentRegistration(forms.Form): name= forms.CharField() email= forms.EmailField() def clean(self): cleaned_data = super().clean() valname= self.cleaned_data ['name'] valemail=self.cleaned_data [ 'email'] if len(valname) < 8: raise forms.ValidatonError('Name should be more than or equal to 4') if len(valemail) < 10: raise forms.ValidatonError('Abe dhang se daal') My Error: AttributeError at /regi/registration/ module 'django.forms' has no attribute 'ValidatonError' Request Method: POST Request URL: http://127.0.0.1:8000/regi/registration/ Django Version: 3.0.2 Exception Type: AttributeError Exception Value: module 'django.forms' has no attribute 'ValidatonError' Exception Location: C:\Users\pkish\OneDrive\Desktop\GS\gs41\enroll\forms.py in clean, line 11 Python Executable: C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.1 Python Path: ['C:\Users\pkish\OneDrive\Desktop\GS\gs41', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib\site-packages', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\confusable_homoglyphs-3.2.0-py3.8.egg'] Server time: Sun, 28 Mar 2021 15:42:39 +0000 -
How use rabbitmq in django
https://github.com/wangyuhuiever/django-rabbitmq Guys need help use it code, i don't understand how use is. Pls need example code -
I am trying to implement an image upload feature on my Django project but no file is being created. What is wrong with my code?
I have a profile page with a default profile picture and a 'Change' button beside it which will trigger a modal upon being clicked. In this modal, the image upload button (for choosing the image) will appear along with a submit button. I have created a separate view for handling the image upload. I do not know why a file is not being created after upload. No error message is being given by Django. I suspect it has something to do with settings.py configuration or the action part of my modal field. views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm from .models import Key, Weekly_Item, Daily_Item, Profile def profile_view(request): profiles = Profile.objects.all() mainprofile = profiles.last() if profiles: form = ProfileForm() context = { 'page_title':"Profile", 'mainprofile':mainprofile, 'form': form } else: context = {'page_title':"Profile"} return render(request, "bujo/profile.html", context) def update_image(request, pk): mainprofile = Profile.objects.get(id=pk) form = ProfileForm(instance=mainprofile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=mainprofile) if form.is_valid(): form.save() return redirect('profile') return redirect('profile') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('profile/', app_views.profile_view, name='profile'), app_views.update_image, name='update_image'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT … -
Difference between queryset attribute and get_queryset() method in django?
I am learning class based views in Django. I was reading the Django documentation and read about queryset attribute and the get_queryset() method. When googled them I came across this answer. I tried to replicate the result using my code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:2] class IndexView2(generic.ListView): template_name = 'polls/index2.html' context_object_name = 'latest_question_list2' queryset = Question.objects.all() In answer it is mentioned that when you set queryset, the queryset is created only once, when you start your server. On the other hand, the get_queryset method is called for every request. But I was able to insert questions in database and they were available in the page index2.html without restarting, I was able to change the database and changes were reflected on the page index2.html after refreshing the page. I further googled and found this link. In the DRF website, it is mentioned that queryset will get evaluated once, and those results will be cached for all subsequent requests. Can you point where I am going wrong ? What link I am missing ? -
How to compare two dates (not time) in django-python project?
Here It is my function to print the previous(oldTickets) and upcoming(newTickets) bookings. journeyDate is database attribute(column name) which is of type date and ticketDetail is model name. Here It is showing error in comparing date attributes. def booking(request): if request.user.is_authenticated: user_name = request.user.username today = date.today() oldTickets = ticketDetail.objects.all() oldTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate<today) newTickets = ticketDetail.objects.all() newTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate>today) context = {'oldticket':oldTickets, 'newticket':newticket} return render(request, 'bookticket/myBookings.html', context) else: return redirect('/login') Can anyone guide me, how to solve this error? Thank You :) -
django.db.utils.IntegrityError: NOT NULL contraint failed: appname_modelName.id
I am creating a client management system in django. I have two models called 'Client' and 'Installment'. my 'models.py' file is given below: models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, blank=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') I am using ForeignKey in the installment model to link the Client model to it, because one client can have multiple installments. When I RUN the following two commands python manage.py makemigrations python manage.py migrate I didn't get any error. Then I RUN the server using: python manage.py runserver and it runs successfully. Then I add a new client in My app that uses client model. But when I want to add installment to the client, is takes input from the user in the fields (installment_month and installment_month), and when I click 'add installment', … -
Why isint opening a text file giving me desired output?
I have a text file that I opened in python, but the output is completely different. I think this is hex. Here's my code: python: class myClass: ... with open("token.txt", "r") as f: self.token = f.read() print(self.token) ... token.txt (inside of working directory) Here's my output("there's no error"): ÿþ1\x006\x00b\x004\x001\x005\x004\x00e\x009\x00f\x00c\x006\x00a\x00a\x00c\x00e\x006\x009\x001\x007\x00d\x00d\x004\x004\x009\x00c\x00f\x00b\x006\x002\x005\x000\x00b\x005\x002\x008\x003\x008\x005\x00a\x00 PS: I doubt this will help but I'm using django and the token is for github. -
How does the value attribute of HTML <input> tag work?
I new to programming and I am reading this django book and it says that in the template that codes for login page, the value attribute of input can redirect the user to the main page after the user log in successfully. When I want to find out more I see the HTML documentation but it says the value attribute accepts data to be submited to the server however it does not say how it causes a redirect in the URL. May I please know how does the value attribute cause a redirect to the URL? I added the Django tag but I am not sure if it’s a django question. -
DRF Custom Pagination not working properly
Recently I was working with drf pagination class,PageNumberPagination.I may or may not have encountered a weird bug . The official docs mention,to overide the page size of PageNumberPagination we have to create a Custom paginator which overides the page size configuration like shown below class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 class BillingRecordsView(generics.ListAPIView): queryset = Billing.objects.all() serializer_class = BillingRecordsSerializer pagination_class = LargeResultsSetPagination But when I tried to do the same the custom paginator was using the default setting as 100 Here's my snippet I used class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class TrendingClassesView(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = BaseClassTileSerializer queryset = BaseClass.objects.all() One moment the code the working fine but after playing around with the page size for some time the paginator just stopped working, I have to do something like below to make the page size working class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 def get_page_size(self, request): return 10 This is my rest framework settings REST_FRAMEWORK = { 'UPLOADED_FILES_USE_URL': True, 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', 'rest_framework.parsers.FormParser', ], "TIME_FORMAT": "%I:%M %p", "TIME_INPUT_FORMATS": ["%I:%M %p", "%H:%M"], } I guess I may be doing something wrong but I am … -
Can't load static files in Django with right setting
Can't load static files from app called 'gameMuster' even if I'm sure everything is okey with settings.py. Project structure Statics confs Installed apps -
why am i getting this error "expected string or bytes-like object"
I am creating a youtube video downloader with Django and bootstrap but when I try to get the youtube video link and redirect to the download page, I get the error "expected string or bytes-like object" below are my HTML and views.py code views.py from django.shortcuts import render from pytube import YouTube def youtubedownloader(request): return render(request, 'youtube_downloader.html') def download(request): url = request.GET.get('url') yt = YouTube(url) video = yt.streams print(video) return render(request, 'download.html') youtube_downloader.html {% extends 'base.html' %} {% block content %} <div class="mt-5"> <center><h1>Download Youtube Video</h1></center> </div> <div class="container mt-5"> <form method="GET" action="download/"> <div class="form-group align-items-center"> <div class="col-auto"> <label class="sr-only" for="inlineFormInput"></label> <input name="url" type="text" class="form-control mb-2" id="inlineFormInput" placeholder="Paste Youtube link here"> </div> </div> <center> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-2">Go</button> </div> </center> </form> </div> {% endblock content %} -
Error creating a multi-step form using Django session
I'm currently working on building a multi-step registration form in Django. I followed the official documentation which can be seen here. Although the forms do not show any error, the user does not get created. Is there a problem I might be overlooking? def signup_step_one(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('accounts:personal-signup')) else: if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): # collect form data in step 1 email = form.cleaned_data['email'] password = form.cleaned_data['password1'] # create a session and assign form data variables request.session['email'] = email request.session['password'] = password return render(request, 'personal-signup-step-2.html', context={ 'form': form, "title": _('Create your personal account | Step 1 of 2'), }) else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-1.html', { "title": _('Create your personal account | Step 1 of 2'), 'form': form, }) def signup_step_two(request): # create variables to hold session keys email = request.session['email'] password = request.session['password'] if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = email user.set_password(password) user.first_name(form.cleaned_data['first_name']) user.last_name(form.cleaned_data['last_name']) user.save() print('user created') return HttpResponse('New user created') else: form = CustomUserCreationForm() return render(request, 'personal-signup-step-2.html', { "title": _('Create your account | Step 2 of 2'), 'form': form, }) -
Module for pagination in the django framework
I'm writing a web application that uses the google book API to display books that the user searches for. I'm now trying to add pagination to the application, but I'm struggling to find great resources to implement this. I have looked into the Pagination Class, but it seems as it designed to paginate results from a database and not responses from API calls. Do you have any tips or good resources to look into, modules or something that could make it a little bit easier to implement this? Any tips are highly appreciated, Thanks! -
I'm trying to send an email from Django using Gmail SMTP
I've set insecure source ON in my account's setting. Also, this is my settings.py file. Can anybody help me? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com ' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER =' my email' EMAIL_HOST_PASSWORD = 'my password' and I'm getting this error in terminal when I write this code PS D:\start here\silicium7\config-project> python manage.py sendtestemail atabarzega79@gmail.com Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\start here\silicium7\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "D:\start here\silicium7\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "D:\start here\silicium7\lib\site-packages\django\core\management\commands\sendtestemail.py", line 33, in handle recipient_list=kwargs['email'], File "D:\start here\silicium7\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "D:\start here\silicium7\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "D:\start here\silicium7\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Ata Barzegar\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket self.source_address) for res in getaddrinfo(host, port, 0, … -
permission to add new user in Django
in localhost/admin there is a button for adding new user(figure 1) and this permission is not for all the users figure 1 how can I add this promotion to other user and make it in another template not have to enter to localhost/adminto add a new user and how can I create this new user without email or password (temporary user) (figure2 figure 2 -
Problem with django server (page not loading)
I am currently using Stripe API to develop my own checkout through python/html in Visual Studio Code. I have successfully run a localhost server and I have a django server up and running. When I press checkout, the screen does not go onto the checkout screen, it just stays on the same screen[enter image description here][1]. I am wondering why this is happening? My code for my checkout page (views.py) is: import json import stripe from django.core.mail import send_mail from django.conf import settings from django.views.generic import TemplateView from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from django.views import View from .models import Product stripe.api_key = settings.STRIPE_SECRET_KEY class SuccessView(TemplateView): template_name = "success.html" class CancelView(TemplateView): template_name = "cancel.html" class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLIC_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': product.price, 'product_data': { 'name': product.name, # 'images': ['https://i.imgur.com/EHyR2nP.png'], }, }, 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({ 'id': checkout_session.id }) @csrf_exempt … -
Django : Displays "No Value " When trying to fetch checked checkbox without submit using AJAX
i wrote a program using django to retrieve all checked checkbox without submit button by using AJAX , it is not throwing any error , but it displays "NO Value " . Can anyone check and tell me what is the mistake i did . AJAX : <script> $('.form-check-input').change(function(){ // checkbox1 change event var checked_lists = []; $(".form-check-input:checked").each(function() { checked_list.push(this.value); }); var formdata = new FormData(); $.ajax({ formdata.append('checked_list',checked_list) formdata.append('csrfmiddlewaretoken',$('input[type=hidden]').val()); $.ajax({ url:"secondtableonDashboard", //replace with you url method:'POST', data:formdata, enctype: 'application/x-www-form-urlencoded', processData:false, contentType:false, success:function(data){ alert("Display return data"+data) }, error:function(error){ alert(error.error) } }); }); }); </script> Views.py if request.method=='POST': user_list = request.getlist('checked_list') print(user_list) else: print("No Values") html : <td> <div class="form-check form-switch"> <input class="form-check-input" name="Servers[]" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </div> </td> -
How can we get the user to add .csv files using django and mongodb?
I'm very new to both Django & MongoDB and I'm trying to make a project which is about NLP. So, at first, we are going to have a web site. It starts with a user login. User can upload .csv files to the web site and we are going to processes and return to the user as a result. We are going to keep the NLP processing codes in docker. For the database, we are using MongoDB and for the backend side, we are using Django. My question is, How am I going to read and store these .csv file data in MongoDB? I know how to upload .csv files into Django. But, I have no idea what I am going to do if the files coming from the user. -
how can I get an id from request.POST of the form that I'm submitting now
I'm building a clinic Management System and in the section that you add a new doctor, I want the admin to be able to add the days that the doctor is available at, so that means the days' field is a list but Django doesn't have a list field in its models so I created CharField-> days days = models.CharField(max_length=200,null=True) and then I've created a multi-select input field inside the form <select name="days" class="form-select" multiple aria-label="multiple select example"> <option value="mon">Mon</option> <option value="sun">sun</option> <option value="wed">wed</option> <option value="etc">etc</option> </select> so I took the Selected data by using this code for i in request.POST.getlist("days"): d= str(i)+" "+d print(d) # result gonna be the days in string value splited by spaces eg : mon sun wed so I can use it later by using split() but the thing is I'm not able to add this data into the form while submitting it so I thought that I can save the form data and then alter the field days like that def add_doctor(request): form = Add_doctorForm() if request.method == "POST": form = Add_doctorForm(request.POST) if form.is_valid(): form.save() d = "" for i in request.POST.getlist("days"): d= str(i)+' '+d print(d) formdata = Doctors.objects.get(id = request.POST.get("id") formdata.days = d … -
how to link two models in one form in CreateView?
There are two models. Attachment must bind to Post. models.py class Post(models.Model): title = models.CharField(verbose_name='Название', max_length=300) slug = models.SlugField(verbose_name='Ссылка', max_length=300, blank=True, db_index=True) category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.CASCADE) content = models.TextField(verbose_name='Описание') created_by = models.ForeignKey(User, verbose_name='Материал добавил', on_delete=models.SET_DEFAULT, default=1, related_name='post_created_by') updated_by = models.ForeignKey(User, verbose_name='Материал обновил', on_delete=models.SET_DEFAULT, default=1, null=True, related_name='post_updated_by') is_published = models.BooleanField(verbose_name='Опубликовать', default=True) views = models.PositiveIntegerField(verbose_name='Просмотры', default=0, blank=True) time_create = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True) time_update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) # META author = models.CharField(max_length=255, verbose_name='Автор', blank=True) source = models.URLField(max_length=255, verbose_name='Ссылка на источник', blank=True) def get_absolute_url(self): return reverse('post', kwargs={'cat_slug': self.category.slug, 'slug': self.slug, 'pk': self.pk}) class Attachment(models.Model): post = models.ForeignKey('Post', verbose_name='Прикрепить файл', on_delete=models.SET_NULL, null=True, related_name='post_attachment') link = models.URLField(verbose_name='Основная ссылка', blank=True) meta_link = models.CharField(verbose_name='Информация', max_length=255, blank=True) load = models.PositiveIntegerField(verbose_name='Загрузки', default=0, blank=True) type = models.ManyToManyField('Type', related_name='type_post') version = models.CharField(verbose_name='Версия материала', max_length=255, blank=True) forms.py class PostForm(ModelForm): class Meta: model = Post fields = '__all__' class AttachmentForm(ModelForm): class Meta: model = Attachment fields = '__all__' exclude = ('post',) How to connect them in CreatView in views.py? I just tried different ways, errors came out. I don't understand a little how to make a formsets. -
I am trying make a custom user signup form and getting following error while making this
I am trying to extend the user model from django.db import models # Create your models here. class RegisterUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) phone_number = models.CharField(max_length=20) sector = models.CharField(max_length=50) and tried to create a form for the signup from django.contrib.auth.forms import UserCreationForm from .models import RegisterUser class CreateUserForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = RegisterUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'phone_number', 'sector') ** These are the only changes I made I am getting the following error:** raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for RegisterUser