Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save a writable file into database?
I am using django 1.8 and python 3.4 and trying to create a json file and then writing into it, after that I need to save it to my database but on save it returns me an error '_io.TextIOWrapper' object has no attribute '_committed'. Can anyone please help where I am doing wrong? Here is my models.py class ConvertedFile(models.Model): file = models.FileField(upload_to='json/upload', max_length=5000) created_on = models.DateTimeField(auto_now_add=True) My views.py is- def convert_file(request): url = request.GET.get('q', None) r = requests.get(url, stream=True) with open('file.csv', 'wb') as out_file: shutil.copyfileobj(r.raw, out_file) csvfile = open("file.csv", "r") jsonfile = open("file.json", "w") csv_rows = [] reader = csv.DictReader(csvfile) title = reader.fieldnames try: for row in reader: csv_rows.extend([{title[i]: row[title[i]] for i in range(len(title))}]) except: pass jsonfile.write(json.dumps(csv_rows, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False)) os.remove("file.csv") jsonfile.close() new_json = ConvertedFile.objects.create() new_json.file = jsonfile new_jsone.save() -
I am getting the following error while running Django Project
We are still using Django 1.7.9 for an old legacy project and we are running into the following issue. Unhandled exception in thread started by <function wrapper at 0x10b6c4f50> Traceback (most recent call last): File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper fn(*args, **kwargs) File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run self.check_migrations() File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in __init__ self.build_graph() File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/db/migrations/loader.py", line 177, in build_graph self.load_disk() File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/db/migrations/loader.py", line 103, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/contrib/contenttypes/migrations/0002_remove_content_type_name.py", line 17, in <module> class Migration(migrations.Migration): File "/Users/myusuf3/.virtualenvs/gyroscope/lib/python2.7/site-packages/django/contrib/contenttypes/migrations/0002_remove_content_type_name.py", line 34, in Migration migrations.RunPython.noop, AttributeError: type object 'RunPython' has no attribute 'noop' There is bug on the issue tracker saying its been resolved but it hasn't for me locally. Weird issue. I am on python 2.7.10 with a clean database. Ideas? Oh, here is also the issue where the outline the problem saying something about polluted Django1.8 files causes the issue. https://code.djangoproject.com/ticket/25084 -
Create HTML Mail with inline Image and PDF Attachment
I want to write a HTML mail in Python/Django containing these parts: HTML linking to logo.png logo.png which should be displayed inline (not as attachment) in the mail user agent info.pdf which should be displayed as attachment Text which should be displayed if the mail user agent can't display HTML. I followed this blog post. Result: The HTML and the inline image works but the info.pdf file gets treated like the inline logo.png, and some mail user agent don't show it :-( How to create both ways (download (info.pdf) and inline (logo.png)) in one mail in python? -
Passing related model to vue 2.0 component
I am building a vue.js frontend to a Django-based JSON REST API (which uses DREST - Dynamic Rest Views and DRF - Django Rest Framework). In the vue frontend, I have an item list which iterates through an array with v-for using a single-item component. Basically: <ul> <book v-for="book in books" :book="book" :author="authors*[book.author]"> </book> </ul> The asterisk indicates the bit which is obviously incorrect at present. The idea is that the component receives two props, the primary object that is being displayed (book) and the secondary, referenced, object from the related model (author). The data for the parent component contains an array of books and an array of authors which the API "side-loads", providing only the authors who are referenced in the page of books. In the book object, the author is referenced by their ID. An alternative is obviously to have the serializer nest the relevant author data in each JSON book object. But this is obviously inefficient since some pages will only contain one a few authors so there would be needless repetition. Does vue.js have a way of getting the right author object from the author array (using the author UID that the book's author field contains), … -
Change permission denied HTTP Status Code
In django rest framework, whenever a permission is denied, it returns 401 to the client. However this is very bad for items that are hidden. By sending 401 you acknowledge the user that infact, there is something there. How can I instead return 404 in specific permissions? This one for example: class IsVisibleOrSecretKey(permissions.BasePermission): """ Owner can view no matter what, everyone else must specify secret_key if private """ def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): key = request.query_params.get('secret_key') return ( obj.visibility != 'P' or request.user == obj.user or obj.secret_key == key ) -
Mysql in a separate container or in the same
So, I am buildin a docker container for a django app and after reading a decent amount on the internet I found out that I can either include in docker-compose.yml an already made image for Mysql or I can include it in the container of the app. I was wondering what are the positive sides of the one and of the other. Is one of them more secure and the other not or does the one work faster than the other? -
Correct way to set optional Django field to blank?
If you have an optional Django model field, what is the correct way to create that Django object when the user leaves the form field blank? I have the following model and form (By the way, I know I could use a ModelForm): # models.py class Club(models.Model): hostname = models.CharField(max_length=128) co_hostname = models.CharField(max_length=128, null=True, blank=True) # forms.py class ClubForm(forms.Form): hostname = models.CharField(max_length=128) co_hostname = models.CharField(max_length=128, required=False) If the user leaves the co-host field blank, should I enter a blank as shown below when I create the object? I've been under the impression that if you're inserting a blank into your database table, you're still giving it a value which you may not want to do. What's the correct way to handle this situation? Thanks. # views.py club = Club.objects.create( hostname = form.cleaned_data['hostname'], co_hostname = '' ) -
create a short cut in mac terminal
I'm trying to create a short cut for a mac terminal such that when I write 'jj' the following line of code used in terminal will run: python 5_7_16.py My partner can write the program for Linux but he's not able to do it for Mac. He managed to write the path of the code as follows FPTH="/Users/kylefoley/PycharmProjects/inference_engine2/inference2/Proofs/5_7_16.py" When I'm using the pycharm software these are the first two lines of code I use before I can use python 5_7_16.py cd inference2 cd Proofs We already have the python file 'jj' saved in the right location and we can almost get it to work but not quite. Also, software has three modes: output to excel, output to django, output to mysql. For reasons that I don't understand my partner thought we needed to write down in our file what type of mode is active. I don't understand why this is the case because all that information is already stored in the 5_7_16 file. Just in case it helps, here are the first lines of the python code. excel = True mysql = False if not excel and not mysql: from inference2.models import Define3, Archives, Input from inference2 import views if … -
What are CMS_TEMPLATES in settings of a django app used for?
In a app i have seen CMS_TEMPLATES = ( ('template_general.html', gettext('General template')), ('template_no_menu.html', gettext('Template without menu')) ) Should i do anything specific with them such as add them in django admin cms?? -
TemplateDoesNotExist & {% extends "base.html %} error
I'm having an issue that I personally have been unable to resolve and I think the easiest way to ask for help is to link to the github folder where the error references I've been pushing to and include this screenshot. I've looked at the other questions with very similar context and I've actually tried almost every single thing I've found. Some of it was related to project structure, some of it related to syntax or logic but I cannot find any such problem in my code and as a result, I've also probably added things/changed things that I didn't need to. It's a sign I need help with the problem. -
Deploying Django to Azure leads to failure without output
I am trying to deploy a Django project for the first time to Azure through Web Deploy in Visual Studio. My project runs correctly on my local machine, and I got the polls example project running on Azure through Web Deploy already. It appears that Web Deploy is not able to find the files to push out to the server since the preview shows no files. I have compared everything I can think of between the working polls example app and my Django project which does not work. Interestingly, deploying from the app level works in my Django project, but deploying from the project level does not. I believe that I need to be able to deploy it from the project level to get it working. ------ Publish started: Project: projectname, Configuration: Release Any CPU ------ ========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ========== ========== Publish: 0 succeeded, 1 failed, 0 skipped ========== Thanks for any help. -
Django giving error ImportError: No module named 'corsheaders'
I am a newbie to Django and trying to enable CORS for my server. I couldn't find a built-in solution so I went with django-cors-headers. I am running my server in conda environment on python 3.5 in Ubuntu 15.04. So I installed it with pip3 install django-cors-header. When I do pip3 list it shoes django-cors-header installed at version 1.2.2. In my django app I did. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'polls', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True But when I run python3 manage.py runserver It stops saying ImportError: No module named 'corsheaders'. I have read all SO posts regarding it but none seem to solve my problem. Kindly help -
TabularInline for many to many relationship not displaying all fields
I hope someone can help me with this. I have a Crawl model and a Website model. Crawls contain many websites, and websites can have many crawls. class Crawl(models.Model): websites = models.ManyToManyField(Website, related_name='crawls') class Website(models.Model): domain = models.CharField(max_length=255) # website's relationships with other models industry = models.ForeignKey(Industry, null=True, blank=True, default=None) location = models.ForeignKey(Location, null=True, blank=True, default=None) The CrawlAdmin contains a TabularInline for its websites. class CrawlAdmin(admin.ModelAdmin): inlines = [WebsiteAdminInline,] exclude = ('websites',) class WebsiteAdminInline(admin.TabularInline): model = Crawl.websites.through extra = 0 The problem is the Website TabularInline is only showing the Crawl_websites object. I need it to show domain, industry, and location. I'm able to get TabularInlines to work if the relationship is a simple foreign key relationship (e.g. website has a foreign key to crawl), but for some reason it won't work for many to many relationships. Do you know how I can fix this? Thank you. -
Log user activity to file in Django
I would like to log all changes to a file that the user makes. Users change data mostly with generic views. (DeleteView, UpdateView, CreateView) and I must be able to track all changes. For example: [timestamp] User: [username] added [all] [additions] [to] [database] [here] [timestamp] User: [username] deleted [all] [deleted] [fields] [timestamp] User: [username] edited [old] [fields] to [new] [data] [fields] There could be even more info (like users full name etc.) but I atleast try to keep the question simple. Also the log must work in production for obvious reasons. So far what I've found is about logging error messages etc. to files or console. Does anybody have any idea where to start? -
How should I iterate over this dictionary of objects in this Django Template?
I have the below view. def select_classes(request): ... classesBySelectedGrade = courseBlock.objects.filter(grades__grade__contains=form['grade'].value()).order_by( 'time') classOptionCount = classesBySelectedGrade.all().count() classOptionDict = {} for i in range(classOptionCount): classOptionDict["option " + str(i + 1)] = classesBySelectedGrade return render(request, 'select-classes.html', {'classesOptions': classOptionDict}) The goal of the above view: Is to take a set of "courses" sorted by time. Create a copy of the set of course nth many times as courses.count() Add each copy to a dictionary Pass this dictionary to my template. My current goal in my template: To iterate over passed in dictionary to read the values out. Here is the current loop I am using. {% for classesOption in classesOptions %} <p> {{ classesOption }} {% for classes in classesOption %} {{ classes }} {% endfor %} </p> {% endfor %} And this is my output. option 2 o p t i o n 2 option 1 o p t i o n 1 The above output is expected with the particular data I am testing. That is I am expecting 2 copies in this test case. For more context here are my models: class Course(models.Model): title = models.CharField(max_length=200) limit = models.IntegerField(default=10) description = models.TextField(max_length=800) location = models.CharField(max_length=200, default="") teachers = models.TextField(max_length=800, default="") class … -
Django 1.9 The contact form display a 405 error on submit
I'm getting a 405 Not Allowed error (nginx/1.10.2) on my production site but in the dev site I have no error. I'm trying to process a contact form. I tryied on function view instead of a class view and I'm getting the same error. # views.py class ContactFormView(TemplateView): form_class = ContactForm template_name = "main/contact.html" success_url = '/success/' logger.info('Contact form') def get_context_data(self, *args, **kwargs): context = super(ContactFormView, self).get_context_data(*args, **kwargs) context['form'] = self.form_class() return context def post(self, request, *args, **kwargs): logger.info('Contact form process POST') context = self.get_context_data(*args, **kwargs) form = self.form_class( data=request.POST, ) if form.is_valid(): form.save() #messages.add_message(request, messages.INFO, 'Your message has been sent.') #import ipdb; ipdb.set_trace() return redirect(reverse('main:success')) #forms.py class ContactForm(forms.Form): email = forms.EmailField(label=_("E-mail"), required=True) CHOICES = [ (i.event_title, "Register to the Workshop: " + i.event_title)for i in ClubEvent.objects.all()] CHOICES.insert(0, ('Contact us form: general question', 'Contact us form: general question')) subject = forms.ChoiceField( #help_text=_("Select a Subject"), # use this to detect type label=_("Subject"), widget=forms.Select(attrs={'class': 'form-control'}), required=True, choices=CHOICES, ) content = forms.CharField(widget=forms.Textarea(), required=True, label=_("Message")) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.laber_class = 'col-lg-6' self.helper.form_action = reverse('main:contact') self.helper.layout = layout.Layout( layout.Fieldset( _("UOPy contact form"), Field("subject", css_class="form-control input-contact input-md input-block-level form-group lead"), Field("email", css_class="form-control input-contact input-md input-block-level form-group lead"), Field("content", css_class="form-control … -
Setting Jinja2 globals by Django reusable application
What I have: I have a Django project called my_project. Project's structure: my_project/ manage.py my_project/ __init__.py settings.py urls.py views.py my_app/ __init__.py admin.py migrations/ static/ templates/ tests.py urls.py views.py templates/ Also I have a reusable app my_app inside my_project. What I want to achieve: I want to automatically set Jinja2 global var inside my_app application (e.g. my_var_or_func) right after adding my_app to the project's INSTALLED_APPS setting. This variable should be accessible globally inside my_project as: <div>{{ my_var_or_func }}</div> or <div>{{ my_var_or_func() }}</div> -
Django convert JSON to CSV
I am working on a function to load data from Data SF and download it as a CSV. I can make a query to their database and accurately display the results in a template, but I cannot write those results to a CSV. I've been reading online about issues converting JSON to CSV, but I can't seem to connect them to my project. The code from this view will make a query and display the results in a template: if request.POST: qAddress = request.POST.get('qAddress') url = 'https://data.sfgov.org/resource/2zah-tuvt.json?qAddress=%s' % qAddress search_request = requests.get(url, verify=False) search_results = search_request.json() args = {'url': url, 'search_results': search_results} args.update(csrf(request)) return render(request, 'sts_soda_search_results.html', args) However, this code fails: if request.POST: response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Search Results.csv"' url = request.POST.get('url') search_request = requests.get(url, verify=False) search_results = search_request.json() writer = csv.writer(response) writer.writerow(['Tree ID', 'Species', 'DBH', 'Address', 'Latitude', 'Longitude']) for obj in search_results: writer.writerow([obj.treeid, obj.qspecies, obj.dbh, obj.qaddress, obj.latitude, obj.longitude]) return response I instead get this error: 'dict' object has no attribute 'treeid' replacing writer.writerow([obj.treeid....]) with writer.writeror(obj.values()) works, but is inconsistent since some queries have additional fields that I don't want to include. json.loads(), json.load() and json.dumps() don't return the query, so is there a way to make it … -
Displaying blog posts on homepage in Wagtail
I am building a Wagtail site that has blog postings listed on a blog index page, but I would also like to display the latest three posts on the home page of the website as well. My current code to display blogs on the blog index page is as follows: blog_index_page.html: {% for blog in blogs %} <div class="col-sm-12"> <div class="blog-post post-format-image"> <div class="blog-post-side"> <div class="blog-post-date"> <p class="date-day">{{ blog.date.day }}</p> <p class="date-month">{{ blog.date|date:"M" }}</p> </div> </div> <div class="blog-post-content"> <div class="post-media"> {% image blog.main_image width-1225 %} </div> <div class="post-info"> <h3 class="post-title"><a href="{{ blog.slug }}">{{ blog.title }}</a></h3> </div> <div class="post-content"> <p>{{ blog.intro }}</p> </div> <a class="btn btn-primary btn-sm" href="{{ blog.slug }}">Read More<i class="fa iconright fa-arrow-circle-right"></i></a> </div> </div> {% endfor %} models.py class ResourcePage(Page): main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) date = models.DateField(blank=True, null=True) intro = models.CharField(max_length=250) body = RichTextField(blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), ImageChooserPanel('main_image'), FieldPanel('intro'), FieldPanel('body', classname='full'), ] class ResourceIndexPage(Page): intro = RichTextField(blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), ] @property def blogs(self): # Get list of live blog pages that are descendants of this page blogs = ResourcePage.objects.live().descendant_of(self) # Order by most recent date first blogs = blogs.order_by('date') … -
Django template - dynamic variable name while include
I would like to know if it is possible to set dynamically variable name while a template inclusion, like this : {% with classname="article" %} {% include "generic_template.html" with classname=object %} {% endwith%} classname is a dynamic variable name. Then in article.html, I could use object as article in the context. I need that because I would like to include sub templates dynamically functions of the object. Of course, the example is silly, but simple to understand. Thanks. -
Reverse for '' with arguments '()' and keyword arguments not found. Django
I have been having trouble with this for a few dayss and havent been able to find any answers. Basically I want the url to be the / as in if its print then I want /print. I understand that my regex is probably wrong and will need changed, but here is my code. Myproject/urls.py url(r'^(?P<pk>)/$', views.page_detail, name='page_detail'), It throws the error on line 5 function_list.html {% extends 'wiki/base.html' %} {% block content %} {% for page in pages %} <h1><a href="{% url 'page_detail' pk=page.pk %}">{{ page.function }}</a></h1> <p>{{ page.usage|linebreaksbr }}</p> {% endfor %} {% endblock %} views.py def page_detail(request, pk): page = get_object_or_404(Page, pk=pk) return render(request, 'wiki/page_detail.html', {'page': page}) page_detail {% extends 'wiki/base.html' %} {% block content %} <h1>{{ page.function }}</h1> <p>{{ page.usage|linebreaksbr }}</p> {% endblock %} The specific error is Reverse for 'page_detail' with arguments '()' and keyword arguments '{'pk': 'print'}' not found. 1 pattern(s) tried: ['page/(?P<pk>)/$'] if anyone has any ideas or resources for me to look at I would appreciate it. -
ModelForm won't validate because missing field is assigned in clean()
I have a ModelForm with a custom save method to populate a model field with a kwarg from the url params (that was passed to the form): from app.models import MyModel class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fk_customer = kwargs.pop('customer') super(MyModelForm, self).__init__(*args, **kwargs) class Meta: model = MyModel fields = '__all__' def clean(self): cleaned_data = super(MyModelForm, self).clean() cleaned_data['fk_customer'] = self.fk_customer return cleaned_data When I inspect cleaned_data in my view, fk_customer is present and valid. However is_valid() is false, and the ModelForm won't save(). If I override a few things and force save, the field fk_customer is saved as None. What's going on and how can I alter cleaned_data and still validate? -
Show nested field in django rest framework without explicitly using include in the url
I'm using DRF and DRF-jsonapi. I'm trying to display nested objects without putting the argument include=field in the URL. My model: class Inventory(models.Model): site_id = models.CharField(max_length=75) sample_id = models.CharField(max_length=50, primary_key=True) parent_id = models.ManyToManyField("self", symmetrical=False) otherfield = models.CharField(max_length=75) My serializer class InventorySerializer(serializers.ModelSerializer): included_serializers = { 'parent_id': 'inventory.serializers.InventorySerializer', } parent_id = ResourceRelatedField(read_only=True, many=True) class Meta: model = Inventory exclude = ('site_id',) read_only = True depth=2 This works great whenever I use http://localhost:8000/inventories?include=parent_id I want to make it work just by hitting http://localhost:8000/inventories Whenever I try to access that last url, it only shows the ID of the nested object and not the whole nested object. Any ideas? -
Not able to serve media files in django
I am trying to create an online music player. I was trying to play a song in django. But it was not able to play since it was not able to detect the audio file. I have set up the media in django as I read on the internet but it's not working. Here is the screenshot of my project directory: detect and music are two apps. I am currently working with music app. Settings.py(included this at last of file). STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR,"media") MEDIA_URL = '/media/' urls.py: from django.conf.urls import * from django.contrib import admin from detect import views from music import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/$',views.play,name = 'play') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py: from django.shortcuts import render from django.http import HttpResponse def play(request): return render(request,'music/song.html',{}) song.html: <html> <audio id="Player" autoplay> <source src="{{MEDIA_URL}}/audio/test.mp3"/> </audio> </html> -
django-registration-redux: 'AnonymousUser' object has no attribute '_meta'
I'm using a custom form with a custom User model with django-registration-redux. When the user registers, the user gets created but it displays the stack trace at the bottom of this post. However, if I am already logged in, and I register as a user, I do not get this stack trace. I did a bit of logging in the RegistrationView class of this library and None gets returned from new_user = authenticate( username=getattr(new_user, username_field), password=form.cleaned_data['password1'] ) in the code below: class RegistrationView(BaseRegistrationView): """ A registration backend which implements the simplest possible workflow: a user supplies a username, email address and password (the bare minimum for a useful account), and is immediately signed up and logged in). """ success_url = 'registration_complete' def register(self, form): new_user = form.save() username_field = getattr(new_user, 'USERNAME_FIELD', 'username') new_user = authenticate( username=getattr(new_user, username_field), password=form.cleaned_data['password1'] ) logging.debug("new_user") logging.debug(new_user) login(self.request, new_user) logging.debug("Logged in") signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) logging.debug("After signals") return new_user UserModel: class User(AbstractBaseUser): email = models.EmailField(max_length=100, unique=True) first_name = models.CharField(max_length=30, blank=False, null=True) last_name = models.CharField(max_length=30, blank=False, null=True) date_joined = models.DateTimeField(editable=False, default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def get_full_name(self): return self.first_name + " " + self.last_name def get_short_name(self): return self.last_name def __str__(self): return self.email Form: class …