Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the user context in all views django?
Im using a template syntax to set the permissions for the topbar of the application like so Top bar permision {% if user.is_authenticated %} # Top bar html code {% endif %} but the problem is that when a user i authenticated they can accress the profile picture and name of another user if they have the correct url:uuid link. I managed to get this fixed by putting this syntax in the template {% if object == request.user %} {% if object.pk %} {% endif %} {% endif %} This fixed the issue on the pages where the request.user can be accressed from the profile view. How can i accress the request.user in all the views at once? -
nginx+gunicorn+django error Not Found: /static/.. file
I built a python web framework by using django, and I want to deploy it with nginx and gunicorn. However, I keep getting prompted for error about "Not Found: /static/answer/result.png". If I didn't use nginx adnd gunicorn I wouldn't get this error. I don't know what went wrong, please help me, thank you. (1) settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tuh%ati6x38&q8t4sr$h46m_lc$r!dpx@#aobx#%dj(vflho2z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["127.0.0.1", "192.168.43.90", "192.168.2.229"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "gunicorn", 'UserProfile', 'ImageRecognition', "KuaiChao", "HuaXiao" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'LPAI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'LPAI.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
ARA Exception even though the env variable and the API are set properly
What is the issue? I am facing this issue: ~ # ansible-playbook test_playbook.yml -vv ansible-playbook 2.10.6 config file = None configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /root/.local/lib/python3.8/site-packages/ansible executable location = /root/.local/bin/ansible-playbook python version = 3.8.7 (default, Mar 2 2021, 10:13:07) [GCC 10.2.1 20201203] No config file found; using defaults [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Operations to perform: Apply all migrations: admin, API, auth, contenttypes, db, sessions Running migrations: No migrations to apply. Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: test_playbook.yml ***************************************************************************************************************************************************************************************************************** 2021-03-09 17:47:40,379 ERROR ara.clients.http: Failed to post on /api/v1/playbooks: {'ansible_version': '2.10.6', 'arguments': {'version': None, 'verbosity': 2, 'ask_pass': False, 'private_key_file': None, 'remote_user': None, 'connection': 'smart', 'timeout': 10, 'ssh_common_args': '', 'sftp_extra_args': '', 'scp_extra_args': '', 'ssh_extra_args': '', 'force_handlers': False, 'flush_cache': False, 'become': False, 'become_method': 'sudo', 'become_user': None, 'become_ask_pass': False, 'tags': ('all',), 'skip_tags': (), 'check': False, 'syntax': False, 'diff': False, 'inventory': ('/etc/ansible/hosts',), 'listhosts': False, 'subset': None, 'extra_vars': "Not saved … -
How can I show specific users data into the serializer through django?
I am trying to create a portfolio of users for the stock market. I have custom users model like this: class CustomUsers(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, db_index=True,null=True) phone_no = models.CharField(max_length=50,null=True,unique=True) first_name = models.CharField(max_length=120, blank=True) last_name = models.CharField(max_length=120, blank=True) is_admin = models.BooleanField('admin', default=False) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now ) objects = CustomUserManager() def get_full_name(self): return (self.first_name +" " +self.last_name) I have another app called portfolio and I have two models in it. They are like this: class MyShares(models.Model): TYPE = ( ('IPO',_('IPO')), ('FPO', _('FPO')), ('Secondary',_('Secondary')), ('Bonus', _('Bonus')), ('Rights', _('Rights')), ('Auction', _('Auction')) ) SHARE_STATUS = ( ('Owned',_('Owned')), ('Sold',_('Sold')) ) user = models.ForeignKey("users.CustomUser", verbose_name=_("User"), on_delete=models.CASCADE, related_name='my_shares') stock_symbol = models.ForeignKey("finance.Organization", verbose_name=_("Stock Symbol"), on_delete=models.CASCADE) buy_date = models.DateField(_("Buy Date"), auto_now=False, auto_now_add=False) sell_date = models.DateField(_("Sell Date"), auto_now=False, auto_now_add=False, null=True, blank=True) buy_price = models.FloatField(_("Buy Price")) sell_price = models.FloatField(_("Sell Price"),null=True,blank=True) quantity = models.PositiveIntegerField(_("Quantity")) share_type = models.CharField(_("Type"), choices=TYPE, default='IPO', max_length=50) share_status = models.CharField(_("Status"),choices=SHARE_STATUS,default='Owned', max_length=50) def __str__(self): # if self.user.first_name: # return self.user.get_full_name() return self.stock_symbol.symbol class Portfolio(models.Model): … -
how to install djangorestframework-gis-distance
hi i am on ubuntu and i tried to install djangorestframework-gis-distance i followed the instructions and installed the dependencies which installed fine. But when i install djangorestframework-gis-distance it gives an error of ERROR: Command errored out with exit status 1: command: /home/aarush/git_fudo/food1_back/food1_back/env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py", line 9, in <module> from pip.req import parse_requirements ModuleNotFoundError: No module named 'pip.req' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. which basically says i think that there is no file called pip.req. is there another way i can install djangorestframework-gis-distance? -
How to run a long process/function on button click django
Im trying to do a django website in which: I take a user input from the template (done) Save the input in the view (done) On a button click, user starts a function that send a api request every x seconds and if the function find a different api response then show it in template as status. And i have no idea how to achieve the 3rd point. This is how the api request function looks like: def function(zapytaniex,fraza,kategoria): starttime = time.time() data1 = zapytaniex while True: data2 = apirequest(fraza = fraza, categoryid = kategoria) if data1 != data2: context["status"] = "got new offer" elif data1 == data2: context["status"] = "still nothing" time.sleep(120.0 - ((time.time() - starttime) % 120.0)) As you can see this function send the api request every 2 minutes and I want to run this function when user clicks a button and then update a status context in a template WITHOUT refreshing the whole page. I tried to run it with threading but the page keep loading when the thread in working. Thanks for any help and ideas! -
The view admission.views.UpdateEducation didn't return an HttpResponse object. It returned None instead
What is the problem in this.... View.Py def UpdateEducation(request, id=None): context = {} user_obj = request.user if not user_obj.is_authenticated: return redirect('login') user_id = Applicant.objects.filter(app_id = user_obj.app_id).first() applicant = ProfileInfo.objects.filter(user=user_id).first() if request.POST: form = EducationForm(request.POST, instance=applicant) if form.is_valid(): obj = form.save(commit=False) obj.applicant_info = applicant obj.save() return redirect('profile') else: context['education_form'] = form else: try: user_info = ApplicantEducation.objects.filter(applicant_info = applicant).get() form = EducationForm( initial={ 'institute_name': user_info.institute_name, 'marks_percentage' : user_info.marks_percentage, 'affilation_with' : user_info .affilation_with, 'date_completion':user_info.date_completion, 'degree_details' : user_info.degree_details, } ) context['education_form']= form except: form = EducationForm() context['education_form']= form return render(request, 'admission/signup.html', context) i have a model called ApplicantEducation for which i am using EducationForm. This view function listed above is intended to store education details, but it comes up with error. What missing here, please take a look.... -
Sum and store values in another table
I am new to Django. My query is I store some quantity of components in a table. I want to sum the quantity sorting it by components and then use the summed quantity in some other table to do further calculations. How can I achieve this.. #views.py class PurchaseCreateView(CreateView): model = Purchase fields = '__all__' success_url = reverse_lazy("purchase_form") def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['purchases'] = Purchase.objects.all() return context #models.py class Purchase(models.Model): purchase_date = models.DateField() invoice_no = models.CharField(max_length=200,unique=True) supplier =models.ForeignKey(Supplier,on_delete=models.CASCADE) components = models.ForeignKey(Components,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() remarks = models.TextField(max_length=500,blank=True,null=True) def __str__(self): return str(self.pk) # Below is the Model where I want to use the summed quantity for further calc class IntermediateStage(models.Model): producttype = models.ForeignKey(ProductType,on_delete=models.CASCADE) components = models.ForeignKey(Components,on_delete=models.CASCADE) processingstage = models.ForeignKey(ProcessingStage,on_delete=models.CASCADE) unitsrequired = models.PositiveIntegerField() quantity = models.PositiveIntegerField(blank = True) total_quantity = models.IntegerField(blank= True) class Meta: unique_together = [['producttype','components','processingstage']] def __str__(self): return str(self.id) -
applying selected model data to form - Django
I am working on a printing ordering service website in Django 3.1 . I am stuck on order page. On order page I want to provide option to user that he can create either a custom order from given option otherwise he can select from packages one of the package and that package data will be applied to the form and that form will be submitted as order. But I don't know how to achieve that functionality. models.py class Packages(models.Model): package_ID = models.AutoField("Package ID", primary_key=True) package_Name = models.CharField("Package Name", max_length=30, null=False) attribute_values = models.JSONField("Item Details JSON", max_length=500, null=False) package_Price = models.IntegerField("Package Price", null=False, default=0.00) quantity = models.IntegerField("Quantity", null=False, default=00) prod_ID = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Product ID (FK)") class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.IntegerField('Product Quantity', null=False, default=0) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) This is my views I am storing custom order in order table , here I am packing size and color value in dictionary and storing it as JSON in model. views.py def order(request, id): products = Product.objects.all() sizesList = [] ColorsList = [] Packages_list = [] quantity = 0 try: … -
How to download PgAdmin 4 database backup in Django
import os def Download_db(request): os.system("pg_dump -- kite=postgresql://postgres:root@127.0.0.1:5432/test>C:\Users\hp\Desktop\dumpfile3.dump" ) return HttpResponse("done") -
ModuleNotFoundError: No module named 'model_mixins'
Python 3.8 models.py from gettext import gettext import omnibus.model_mixins.general as general from django.db import models import model_mixins class Client(general.NameMixin, general.FlagMixin, model_mixins.DirMixin, general.ArchivedMixin, general.CommentMixin, models.Model): class Meta: verbose_name = gettext("Client") verbose_name_plural = gettext("Clients") model_mixins.py from django.db import models from django.db.models import Index from django.utils.translation import gettext class DirMixin: dir = models.CharField(max_length=30, unique=True, verbose_name=gettext("Target directory")) class Meta: abstract = True Index(fields=['dir', ]) **tree** ├── ads6 │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ └── urls.cpython-38.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── clients │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── model_mixins.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── models.cpython-38.pyc │ ├── tests.py │ └── views.py ├── db.sqlite3 **migrations** (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py makemigrations 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 "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", … -
Access variable in the forms class?
How to get the value of ModelChoiceField in Django forms class. I have one ModelChoiceField in my forms.ModelForm class: class mStockForm(forms.ModelForm): mStock_product = forms.ModelChoiceField( queryset=mProduct.objects.filter(), label='Select Milk Product', help_text="Choose from the list of milk products", required=True, ) #---------------------------Want to access mStock_Product'''''''''''''''''''''''# value = mStock_product.value #<------------Here -
Code for Python image upload handler with tinymce
Please help me with code for locally upload image of tinymce. I use tinymce for WYSIWYG Editors on admin page of django. It work. But I cannot upload image from the local computer. I search on google and have some result for php code (https://www.tiny.cloud/docs/advanced/php-upload-handler/). I cannot find example code for python. If I want to upload a local image, I must config images_upload_url in settings.py as below: TINYMCE_DEFAULT_CONFIG = { ... 'images_upload_url': os.path.join(BASE_DIR, "script/upload.py"), ... } But I don't know where I place upload.py file and how I can config path. And How to code upload.py correctly. -
Make a field in fieldset of ModelAdmin required in Django
I need to make some fields in the fieldset variable of a ModelAdmin class as required so that the user cannot create or update a user instance if those fields are not selected in the form. How can I do that? class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update({ 'duplicate_username': 'This username has already been taken.' }) class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) @admin.register(User) class UserAdmin(AuthUserAdmin): fieldsets = AuthUserAdmin.fieldsets + ( (None, {'fields': ('user_type', 'country')}), ) add_form = MyUserCreationForm Here I want to make country and user_type as required in the admin panel. How can I do that? -
Image is not getting saved in the database django
I am trying to upload an image to the database. While posting the data I am not getting any error. Image tag in html <div class="text-center"> <h6>Upload a different photo...</h6> <input type="file" class="form-control" name="user_img"> </div> UserProfile model # User profile class UserProfile (models.Model): # user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) user_img = models.ImageField(null=True, blank=True, upload_to='static/images') name = models.CharField(max_length=100) emailID = models.CharField(max_length=100) phone = models.CharField(max_length=15) college_name = models.CharField(max_length=200) branch = models.CharField(max_length=100) urls.py from django.contrib import admin from django.urls import path, include # For user profile from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('colos.urls')), path('accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py # For user images MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') views.py # edit user profile def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) if request.POST.get('action') == 'post' and request.FILES: name = UserProfile.objects.all() response_data = {} # user profile image start user_img = request.FILES['user_img'] # user profile image end name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = … -
Nested management commands in Django
Is there anyway to create nested management commands in Django, similar to what the docker and kubectl have? For example, let's say I need to have the following structure: |-->manage.py |-->restaurant |-->list |-->get |-->employee |-->list |-->get |-->delete The following commands should all be possible: ./manage.py -h ./manage.py restaurant -h ./manage.py restaurant list ./manage.py employee list ./manage.py restaurant get "" ./manage.py employee delete tiffany The argparse subparser looks promising but I feel like there should be an easier way using python modules in the app/management/commands or something like that. -
what is the best solution for GNU gettext installation in windows?
in windows for a django project on pycharm, my Django and dependencies are installed on venv. I wanted to modify one .po file and test it if it's working or not, it seems that this change needs to commit by this command: *django-admin makemessages -l -ja* I tried it and I faced with this error: "CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed." I tried to install gettext for my project but it didn't work. pip install python-gettext didn't work as well. and some of the answers for similar issue were not clear I want to know the best solution for this situation ... -
can I use django authentication in already created mysql database with user data?
I am creating a web app and I need to authenticate the login. The username and password is already stored in mysql database. Can I use django for authentication of existing data? It will be great help if anyone knows the answer. -
The safe is not working after creating hashtag system for my Django project
I made a hashtag system for my Django project but after making it the safe isn't working and if a user wants to use special characters it shows weird in output. Example I want to write: " Hello, I'm Ramin " it will show " Hello, I & #x27;m Ramin " Can anyone help me? -
Django query how to write: 'WHERE field LIKE' in Cassandra
What is the equivalent of this CQLSH statement in Django? SELECT * FROM table_name WHERE string LIKE pattern; How do I implement this in django? I tried result = table.objects.filter(string__contains='pattern') but it is giving the following error [Invalid query] message="Cannot use CONTAINS on non-collection column string" I have already made a custom index for the search field and raw LIKE query is working in cqlsh. But I need something for Django to filter on basis of keyword. Thanks in advance -
How to install Figures Plugin for openedx koa release
Hi I am using openedx koa.2 release and want to install appsembler figures reporting plugin.Since figures doesn’t support koa.2 is there anyway to install figures for koa2 release.enter link description here -
Python Django models id increment by 2
is it possible to increase the auto increment in django models id: class Role(models.Model): id = models.AutoField(primary_key=True) # I need to get Integer field, increment=2 uuid = models.CharField(max_length=36, unique=True) Should I overwrite the .save() method? -
problem with deploying django project on heroku
i can't deploy my website because of favicon problem (i don't have favicon on my static) 2021-03-10T05:27:41.838422+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=sausagepolls.herokuapp.com request_id=81a5685f-9561-4523-bdd0-b276d66f99c3 fwd="156.214.1.142" dyno= connect= service= status=503 bytes= protocol=https 2021-03-10T05:27:42.124704+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=sausagepolls.herokuapp.com request_id=018aa90c-998f-48d4-9cba-1c1473edde29 fwd="156.214.1.142" dyno= connect= service= status=503 bytes= protocol=https -
Convert two lists into a dictionary of X and Y Format
I have two lists containing around 300 decimal numbers. That I need to convert into a dictionary format like below in order to plot a scatter graph using the values within the two lists as X and Y coordinates with Chart.JS. This is the format that Chart.JS requires the data to be in. data: [{ x: -10, y: 0 }, { x: 0, y: 10 }, { x: 10, y: 5 }] I've been trying to do this in a number of different ways but each time I get it wrong. Does anyone know a good way to accomplish this? -
Django Extending User Model - Inherit Profile Form from Model
I am following a tutorial to do this in Django 3.1.7. The problem I'm having here is I'm being forced to repeat my Profile Model in my Profile Form definition. I want to use forms.ModelForm in my forms.py to inherit my Profile Model and auto-generate the forms. It seems redundant to have to spell everything out again in forms.py when it is already defined in my Models. But I'm not sure how to do that with this architecture. I've tried this approach: https://stackoverflow.com/a/2213802/4144483 But the problem with this is that UserForm is incomplete - 'password1' and 'password2' don't exist for model User. This is not a good solution for user registration. I seem to be bound to using UserCreationForm somehow. #models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() #forms.py rom django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') class Meta: model = User fields = ('username', 'birth_date', 'password1', 'password2', ) #views.py from …