Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Using array elements as relative URLs in a django template
I am totally new to django, and have been struggling with the following issue for a while. I am sending a sorted list of lists to a template from views.py to a template, in which each sublist (containing two elements) should be displayed. I would like the first element to be a link, in such a way that the String content should be the relative URL to be displayed. So I used the following syntax: <a href="{% url {{user.0}} %}">{{user.0}}</a> but it gives me the following error: TemplateSyntaxError at /app/best_travelled/ Could not parse the remainder: '{{user.0}}' from '{{user.0}}' Please find below the relevant code snippets: views.py: def best_travelled(request): trips = Trip.objects.all() user_trips={} for trip in trips: user_trips[trip.owner] = user_trips.get(trip.owner,0)+1 user_list = [] for key, value in sorted(user_trips.items(), key = itemgetter(1), reverse = True): user_list.append([key, value]) context_dict = {'user_list':user_list} return render(request,'best_travelled.html',context_dict) Template: <html lang="en"> <head> <meta charset="UTF-8"> <title>Most Recent Trips - Travelmate</title> </head> <body> <h1>Best-Travelled</h1> <div> {% if user_list %} <ol> {% for user in user_list %} <a href="{% url {{user.0}} %}">{{user.0}}</a> <li>{{user.0}}, Number of trips: {{user.1}}</li> {% endfor %} </ol> {% else %} There are no travellers yet! This is your chance to become the very first one! <br /> … - 
        
How can I put a ForeignKey field in alphabetical order?
this is my code. models.py class Preventivo(models.Model): prestazione1 = models.ForeignKey('Prestazione',on_delete=models.CASCADE, related_name="prestazione1") form.py class PreventivoForm(forms.ModelForm): class Meta: model = Preventivo fields = ['cliente','prestazione1'] - 
        
Django Model field validation vs DRF Serializer validation
The validation process can happen in 'Django Model level field declaration' or in 'Deserialization of data on DRF serialization section'. I have following concerns regarding this validation process: What is the separation of concerns? Which validation section should be placed where? Do we still need Model validation while we have validation on DRF serialization section? If yes, why? How the DRF serialization section restrict manual database entry with the validation? - 
        
Django Admin UI becomes smaller
I'm sure I did not do any changes to the admin html codes. The recent actions is no longer at the left position. Any idea what I might have changed to cause this problem? - 
        
Error connecting Python with MySQL
I received a python project and I'm having trouble running its requirements, particularly anything to do with MySQL. Whenever I run pip install mysqlclient, I get 13 warnings and this error in red. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-eBsQYy/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-sxHiel-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-eBsQYy/mysqlclient/ When I run pip install mysql-python I get 14 warning with a similar error in red. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-qW79lT/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-13maVa-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-qW79lT/mysql-python/ Any ideas? - 
        
Django - how to best integrate matplotlib
I am trying to display a graph using matplotlib and django. I've read quite a lot of questions on stack but still don't understand what the best way is to use matplotlib in Django. SITUATION: I have a model that has a bunch of data in. In views.py I then have a simple form that captures some data and queries the model and returns a subset of the data. Here is the relevant views.py section: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) context = {'form': form, 'query_data': map_data} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) When I got to play_outcomes/getinput and enter dwn ytg yfog the template then outputs a whole ton of data. It is this data I want to plot i.e., the data in map_data. QUESTION: How do I integrate matplotlib into this? Do I integrate the matplotlib code in views.py, should I set it up in a separate python module? Presumably I need to create a png file and then show that? - 
        
How I make a Calender app in Django using models?
I am working on my very first own project in Django and Backend Development in general. I am trying to build a Calendar app which show a weekly timetable for each room. The code below is my database models. Is there anything I need to change or any different way to buid a Calendar as I described? Thank you! from django.db import models # Create your models here. class Block(models.Model): block_id = models.CharField(max_length=10) class Room(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) room_id = models.CharField(max_length=10) class Lesson(models.Model): number = models.IntergerField() room = models.OneToOneField(Room, on_delete=models.CASCADE) start = models.DateTimeField("Start Time") end = models.DateTimeField("End time") occupied = models.BooleanField(default=False) - 
        
Error Creating Multiple Containers with multiple Django projects
How to run multiple Django Projects as individual containers. docker-compose.yml web1: build: ./test1 expose: - "8000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static command: python manage.py runserver 0.0.0.0:8000 web2: build: ./test2 expose: - "3000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static command: python manage.py runserver 0.0.0.0:3000 postgres: image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ My Project Structure looks like this. ├── docker-compose.yml └── test1 | ├── Dockerfile | ├── test1 | ├── manage.py | ├── requirements.txt └── test2 | ├── Dockerfile | ├── test2 | ├── manage.py | ├── requirements.txt This structure throws errors that file manage.py does not exist. Basically, the command is not looking for the file inside the folder. I started from this Link - Dockerizing Django. - 
        
ModuleNotFoundError: No module named 'yoursite'
I'm relatively new to both Python and Django, and I've had an app developed by someone else. I'm trying to write a script which automatically opens an SSH Tunnel and runs a command from my local machine to my remote postgres database so that I can do a parse locally - this is normally done from the terminal by typing python manage.py parse. This has worked previously when I have run a manual SSH tunnel but now want to set it up to run in a script and close the connection automatically. My script is currently set as below: import psycopg2 import sshtunnel from django.core.management import execute_from_command_line sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 with sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com'), ssh_username='ssh_username', ssh_password='ssh_password', remote_bind_address=('username2.postgres.pythonanywhere-services.com', port) ) as tunnel: params = { "dbname": 'dbname', "user": 'user', "password": 'password', "host": 'host', "port": tunnel.local_bind_port, } connection = psycopg2.connect(**params) cursor = connection.cursor() execute_from_command_line(["manage.py", "parse"]) cursor.close connection.close() I'm now getting the error below when I run the script (which is located in the root file of my app): /home/user/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most … - 
        
Is it suitable to delete my log.django file?
My log.django file is over 100,000 lines now. If I delete it, will it be re-generated again? It exists because I have LOGGING in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.django', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } - 
        
Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?
I have my main home template, that I would like to extend one of two sets of headers from but I am getting an error that seems to indicate the else does not work in this statement. I also tried changing to an elif for when user is not logged in and the elif was shown as undefined. These are the first lines of code in the file so there aren't other things loaded prior to these either. The problem code: {% if user.is_authenticated %} {% extends "main/header.html" %} {% else %} {% extends "landing/header.html" %} {% endif %} Is the extend not allowed to be conditionally added? If so is there a correct way of doing it? - 
        
In ModelAdmin, how do I get the object's previous values when overriding `save_model()`
When overriding ModelAdmin.save_model(), I want to be able to run some calculations between the object's new values vs its old ones. Is there any way that I can get the "old object" with all its previous data before the change? For example, if I have an Object with obj.name = "foo" that I update via the Django admin app to now be obj.name = "bar", upon saving the following code should print out accordingly: from django.contrib import admin class ObjectAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): old_object = self.get_old_object() print(old_object.name) # Should print out "foo" print(obj.name) # Should print out "bar" - 
        
Exception Value: 'many' is an invalid keyword argument for this function
, Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function, Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function views.py from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from student.models import Student from student.serializers import StudentSerializer @api_view(['GET', 'POST']) def Student_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Student.objects.all() serializer = Student(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = Student(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def Student_detail(request, pk): """ Retrieve, … - 
        
What is the namespace and app name for django auth urls?
I am using the Django built-in auth function. path('account/', include('django.contrib.auth.urls')), When I try to reference it using {% url 'password_reset' %} as seen in the Django code. I get an error. How do I reference it? There doesn't seem to be any namespace or app_name in the Django source. The answers on stack overflow are either outdated or require you to manually rebuild the URL one by one and reference it. - 
        
Access form data from one view function in another view function
In Django, how do I pass form_data variable from the below index view function to the results view function? Currently I get 'form_data not defined' error: def index(request): if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form_data = form.cleaned_data return HttpResponseRedirect('results') else: form = RoomForm() context = {'form': form} return render(request, 'javascript/index.html', context) def results(request): print(form_data) #function continues... I have also tried setting form_data as global variable, but no go. - 
        
Can't identify which variable does not exist in VariableDoesNotExist error
My site works fine but my log.django file is showing a django.template.base.VariableDoesNotExist error and I can't identify which variable is not valid. Here's the full traceback: Traceback (most recent call last): File "/home/zorgan/app/env/lib/python3.5/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [lst] in "[{'None': None, 'True': True, 'False': False}, {'user_inbox': <QuerySet [<Inbox: Inbox object>]>, 'allauth_login': <LoginForm bound=False, valid=False, fields=(login;password;remember)>, 'request': <WSGIRequest: GET '/post/'>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd0339c67f0>, 'user_settings': <UserSettings: UserSettings object>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd033a1db70>,'user': <SimpleLazyObject: <User: zorgan>>, 'DEFAULT_MESSAGE_LEVELS': {'ERROR': 40, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'DEBUG': 10}, 'csrf_token': <SimpleLazyObject: 'bagt2zVjPiMiyi0ojTxTVbHHOBiIei7hqZQZ5sDITfzZ9khSbszkDCvcawQuHSxR'>, 'allauth_signup': <SignupForm bound=False, valid=False, fields=(username;email;password1;password2)>, 'inbox_status': 'read'}, {}, {'form_post': <PostForm bound=False, valid=False, fields=(title;content;entered_category;image;imageURL;user)>, 'via': 'news'}, {}, {'block': <Block Node: footer. Contents: [<TextNode: '\\n\\n'>, <IfNode>, <TextNode: '\\n\\n'>]>}]" Any idea? - 
        
Heroku - Declare it as envvar or define a default value
I am trying to run my Heroku app locally and followed the instructions here: https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally When I tried to run the following command: python manage.py collectstatic i've got this error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python36-32\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Python36-32\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\robina\Ubelt-Dorm\ph_dorms\settings.py", line 25, in <module> SECRET_KEY = config('SECRET_KEY') File "C:\Python36-32\lib\site-packages\decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "C:\Python36-32\lib\site-packages\decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "C:\Python36-32\lib\site-packages\decouple.py", line 70, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. The SECRET_KEY has been declared as a Config … - 
        
Django - Uploading and viewing file on page without saving it
I'm writing a view function that just needs to display an image uploaded by the user. I have a form which has the file selector and upload button that will submit the image. In the class definition for the form, there is a field that stores a reference to a model which I thought should be left blank since I'm not actually going to be storing the image in a database but when I try to run the server I get the following error: ValueError: ModelForm has no model class specified. What would be the correct way to display an image after it is uploaded without having to save it to a db? - 
        
Expose the functionality of an installed app via REST
How can I expose the functionality of an installed app via REST in Django framework? - 
        
Generate PDF from html template and send via Email in Django
I'm trying to generate a pdf file from an HTML template and I need to send it via email. Here's what i have tried: def send_pdf(request): minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = str(round(testhours, 3)) user_info = { "name": str(request.user.first_name + ' ' + request.user.last_name), "hours": str(hours), "taggedArticles": str(request.user.tagging.count()) } html = render_to_string('users/certificate_template.html', {'user': user_info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=certificate_{}'.format(user_info['name'] + '.pdf') pdf = weasyprint.HTML(string=html).write_pdf(response, ) from_email = 'our_business_email_address' to_emails = ['Reciever1', 'Reciever2'] subject = "Certificate from INC." message = 'Enjoy your certificate.' email = EmailMessage(subject, message, from_email, to_emails) email.attach("certificate.pdf", pdf, "application/pdf") email.send() return HttpResponse(response, content_type='application/pdf') But it returns an error as TypeError: expected bytes-like object, not HttpResponse How can I generate and send a pdf file to an email from HTML template? Help me, please! Thanks in advance! - 
        
Dynamic, django rendering img tag Javascript/HTML
I am working on a multifaceted web project. I have ran into an issue that I don't know the answer to. I am running a Javascript function after an HTML page loads. I have a frame for images that I want to update with a timer. I am successfully able to run the timer, and I can even collect the latest source name for my img to be posting. But the images don't render. The views stays its default image: image1.png. I am loading this HTML through a django framework using templating. <article> <script type="text/javascript"> window.onload = startTimer(); function displayNextImage() { console.log("Next image should show") x = (x === images.length - 1) ? 0 : x + 1; document.getElementById("img").src = images[x]; console.log(document.getElementById("img").src) } function startTimer() { setInterval(displayNextImage, 3000); console.log("Timer started"); } var images = [], x = -1; images[0] = "../media/image1.png"; images[1] = "../media/image2.png"; images[2] = "../media/image3.png"; </script> <img src="{% static 'image1.png' %}" alt="Frame" id="img" /> </article> - 
        
No module found error in Django when trying to run Celery workers
I have a python script in my Django app that creates a celery app, and attempts to send a simple task to my Redis broker to be processed. In the directory where the script is, I run the celery command celery -A tasks worker --loglevel=info The test works, the task is processed, and all is well in the world. When I attempt to import a model in that script, and rerun that same celery command, I get a Module not found error ModuleNotFoundError: No module named 'wikipedia' Not sure why it can't communicate with the rest of my Django applicaton. celery_redis_rabbit_tut / wikipedia / tasks.py from celery import Celery import time import bs4 from wikipedia.models import WikipediaPage app = Celery('tasks', broker='redis://localhost') @app.task() def grab_idle_pages(): print('X') grab_idle_pages.delay() Traceback Traceback (most recent call last): File "/Users/tim/Timothy/virt_envs/xena/bin/celery", line 11, in <module> sys.exit(main()) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/__main__.py", line 14, in main _main() File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 279, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 481, in setup_app_from_commandline self.app = self.find_app(app) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", line 503, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/app/utils.py", line 355, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/tim/Timothy/virt_envs/xena/lib/python3.6/site-packages/celery/bin/base.py", … - 
        
Installing geodjango on Windows
I would like to use geodjango, but the error that I am getting when following the official installation guide is: File "c:\users\me\appdata\local\programs\python\python36-32\Lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 193] %1 is not a valid Win32 application I see that this error has been addressed here OSError: [WinError 193] %1 is not a valid Win32 application but I still don't know how to fix it in this case. Do I have to make some change to that line? - 
        
django rest framework get() returned more than one object after using filter() method
In model.py, I've two models class student(models.Model): name = models.CharField(max_length=255) registration_number = models.CharField(max_length=255) session = models.CharField(max_length=255) college = models.ForeignKey(to='college', on_delete=models.CASCADE) class Meta: db_table = 'student' class semester(models.Model): semester = models.IntegerField() student = models.ForeignKey(to='student', on_delete=models.CASCADE) sgpa = models.FloatField() grade = models.CharField(max_length=255) is_fail = models.BooleanField(default=True) class Meta: db_table = 'semester' Serializer classes looks like class SemesterSerializer(serializers.ModelSerializer): class Meta: model = models.semester fields = ('id', 'semester', 'sgpa', 'grade', 'is_fail',) class StudentSerializer(serializers.ModelSerializer): class Meta: model = models.student fields = ('id', 'name', 'registration_number', 'college', 'session',) and views.py contains class SemesterViewSet(viewsets.ModelViewSet): def get_queryset(self): if 'semester' in self.kwargs: return models.semester.objects.filter(semester=self.kwargs['semester']) else: return models.semester.objects.all() lookup_field = 'semester' serializer_class = serializer.SemesterSerializer url patterns are router = DefaultRouter() router.register('semester', views.SemesterViewSet, base_name='semester') urlpatterns = [ url(r'', include(router.urls)), ] When I tried url/semester/8, MultipleObjectsReturned exception raised and showes get() returned more than one semester -- it returned 2! error message. Here I've not used any get() method. Why this is happening and what is solution? - 
        
Django/Views executing two forms
I'm really having some trouble with this. I've got some custom user's setup and those users can be attached to companies via foreign key. I'm just having trouble saving them. I've tried a ton of different variations of getting the user attached to a company and I just can't crack it. The forms do work and it does both create a "customer" and a "customer company". I know this needs to be a variation of: if customer_form.is_valid() and customer_company_form.is_valid(): customer_company = customer_company_form.save() customer = customer_form.save(commit=False) customer.user = customer_company customer_company.save() models.py class CustomerCompany(models.Model): COUNTRIES = ( ('USA', 'United States'), ('CAN', 'Canada') ) name = models.CharField(max_length=100, blank=True, unique=True) website = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=255, blank=True) state = USStateField(blank=True, null=True) us_zipcode = USZipCodeField(blank=True, null=True) ca_province = models.CharField(max_length=50, blank=True, null=True) ca_postal_code = models.CharField(max_length=7, blank=True, null=True) country =models.CharField(max_length=3, choices=COUNTRIES, blank=True) def get_absolute_url(self): return reverse('accounts:customer_company_detail',kwargs={'pk':self.pk}) def __str__(self): return self.name class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='customer_profile') company = models.ForeignKey(CustomerCompany, on_delete=models.CASCADE, null=True) phone = models.CharField(max_length=10) def __str__(self): return self.user.first_name + ' ' + self.user.last_name forms.py class CustomerSignupForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=True) last_name = forms.CharField(max_length=50, required=True) phone = forms.CharField(max_length=10, required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User …