Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UpdateVIew form data not getting prepopulated when form is used in Detials View
[Base Update View details][1] [1]: http://ccbv.co.uk/projects/Django/3.0/django.views.generic.edit/BaseUpdateView/ I am trying to have a Update form(updateview) in in my detailView template which updates one of the foreign key object of my detailview's object. I am getting output as expected and logics are working completely fine. I am using updateviewform as popup form but previous data is not getting prepopulated in the form. Views.py file class EducationUpdateView(LoginRequiredMixin,UpdateView): model = Education form_class= EducationCreateForm class PortfolioDetailedView(DetailView): model = Portfolio success_url = 'portfolio:index' def get_context_data(self, **kwargs): context = super(PortfolioDetailedView, self).get_context_data(**kwargs) context['education_form'] = EducationCreateForm() return context template here portfolio is the detailsView object and education is its foreign key {% for item in portfolio.education.all %} <form method="POST" class="form-group" action="{%url 'portfolio:eduupdate' pk=item.pk %}" {% csrf_token %} <div class="form-row"> {% bootstrap_form form %} </div> <input type="Submit" class="btn btn-primary" value="Submit"> </form> pasting this for an idea this is not complete code. The only problem is data is not getting prepopulated into update view form -
Python-django typeerror: expected string or bytes-like object error -- object.save()
I'm learning django-orm my code is this: from django.db import models # Create your models here. class Author(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50) created = models.DateTimeField() class Book(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50) created = models.DateTimeField() author = models.ForeignKey(Author, on_delete = models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=4, null=True) and I'm creating a shell then I'm instantiation objects like this: python manage.py shell >> from books.models import Author,Book >> Author.objects.all() >> from django.utils import timezone >> author = Author(name="Victor Hugo",created = timezone.now) >> author.save() But when i try to .save() my objects it's giving this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 740, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 777, in save_base updated = self._save_table( File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 907, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1276, in as_sql value_rows = [ File "C:\Users\Casper\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1277, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] … -
How to send an email using a html template that contains javascript django?
I have an email template that is rendering certain datetime strings from django. I would like to render this time based on the user's timezone. To solve this I have opted to use momentjs however once, it seems the javascript in the template is not run and anything wrapped in javascript doesn't appear in the email. Based from this answer https://stackoverflow.com/a/42056995/8513875 email clients don't include external css, I assume it's the same issue with javascript, how would I go about making this recognized. -
Showing instagram follower count on dashboard template
During development I was able to scrape the follower count of my client's instagram page and show it in the dashboard. However, after deploying to Heroku it is not working as expected. I always thought there might be problems with this down the road but it was working for the time being. views.py def dashboard_view(request): def insta_follower_count(): user = "username" url = "https://instagram.com/" + user try: r = requests.get(url).text start = '"edge_followed_by":{"count":' end = '},"followed_by_viewer"' count = (r[r.find(start)+len(start):r.rfind(end)]) except: count = 'Could not fetch followers' return count context = { "insta_followers": insta_follower_count(), } return render(request=request, template_name='dashboard/dashboard.html', context=context) Surely there's a better way of doing this because instagram will block you if too many people load the dashboard view too fast. -
I need help adding more features to my django web app
Hi guys i am a newbie django web developer that built a community web app, now i want to add more functionalities to the app for example the post section only has "The message to be written and a group to post the message", now I want to add "a title to each post", "file upload function". I also want to add "comment function when you read the message in the group section". I have added some code to the POST models.py which I learnt from another tutorial, and when I run my development server the effect does not show on the site. Please I really need help Below is the sample of the POST models.py sample code from django.db import models from django.conf import settings from django.urls import reverse import misaka from groups.models import Group from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): title = models.TextField(default="") user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() image = models.FileField(upload_to='image/', blank=True, null=True) message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = … -
update a field in a M2M connection Model.m2m_field.through
i want to update a field which have a M2M connection for example : class SelectMobile(models.Model): #others imei = models.ManyToManyField(Imei) status = models.BooleanField(default=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileModels,on_delete=models.CASCADE) active = models.BooleanField(default=True) i need to update active in Imei only when an instance of SelectMobile been created and its status field equal to True i tried this def update_imei_m2m(sender,instance,**kwargs): if instance.status == True: #this doesnt work , now it works on `Imei` instead of `SelectMobile` Imei.objects.filter(pk__in=kwargs.get('pk_set')).update(active=True) m2m_changed.connect(update_imei_m2m,sender=SelectMobile.imei.through) thanks for helping -
Django: change model value if associated to other model
I have two models: VehicleForm and Vehicle. I created a field in VehicleForm using the other Vehicle model as a ForeignKey. CHOICES = ( (0, 'Yes'), (1, 'No'), ) class VehicleForm(models.Model): ... vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE) class Vehicle(models.Model): ... available = models.BooleanField(choices=CHOICES, default=0) When I create a record for VehicleForm and associate a vehicle to that form, I want to mark that particular vehicle's availability as 'No' once the form is valid. How do I go about this? -
Japanese characters insert into MYSQL DB with Django returns 500 error
On my Django website I can't insert from the auto generated admin dashboard any Japanese or Chinese characters, it returns a 500 error. Here is my my.cnf config : [client] default-character-set = utf8 [mysql] default-character-set=utf8 [mysqld] bind-address = 0.0.0.0 collation-server = utf8_unicode_ci init-connect='SET NAMES utf8' character-set-server = utf8 the database is encoded in utf8 (COLLATE utf8_general_ci) What could cause this bug? -
Heroku refuses to load my django css files
my site loads without being styled. when i inspect elements, it says cannot load style.css and all therest of images and file. i am just trying to upload a simple projet, having couple images, and CSS files. this is the first time heroku does this rejection to me. -
Django don't create the user given image on MEDIA_ROOT
It works if i add a new image from the Django admin, but it is not working by my way. models.py class ModelX(models.Model): photo = models.ImageField(upload_to='photos/') def __str__(self): return 'Picture' views.py from django.shortcuts import render, redirect from .models import ModelX # Create your views here. def photo(request): if request.method == 'POST': model = ModelX( photo=request.POST['photo'] ) model.save() return redirect('show') return render(request, 'index.html') def showphoto(request): model = ModelX.objects.last() return render(request, 'photo.html', {'photo' : model}) -
Django Rest framework + Angular 9 not getting full Image url issue
I'm trying to get a full URL which is in RichTextEditor. I'm getting all the content of richtextEditor but not getting full URL, and browser looking for URL in angular server! Django URL Pattern from django.urls import path, include from rest_framework import routers from .views import ArticleViewSet from django.conf import settings from django.conf.urls.static import static from django.views.static import serve router = routers.DefaultRouter() router.register('article', ArticleViewSet) urlpatterns = [ path('', include(router.urls)), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML code:- <div class="row" *ngFor="let item of dataItems | slice:0:2; let i=index"> <div class="col-6 m-auto" [innerHTML]=" item.description"> </div> <div class="col-6 m-auto" > <h3>{{ item.title }}</h3> </div> </div> I have added all the CORS Headers. I'm getting cool in POSTMAN but not in browser for better understanding some images are console error DRF browser view POSTMAN View -
ssl not working with nginx + uwsgi + django
hi i'm coding my own server with django ,nginx, and uwsgi the problem is when i access https://localhost , ssl work. but https://domainname , it wont work. what is wrong in my code? nginx.conf #user nobody; #Defines which Linux system user will own and run the Nginx server worker_processes 1; #Referes to single threaded process. Generally set to be equal to the number of CPUs or cores. events { worker_connections 1024; # worker_processes and worker_connections allows you to calculate maxclients value: # max_clients = worker_processes * worker_connections } http { include mime.types; default_type application/octet-stream; keepalive_timeout 65; upstream django { server 172.30.1.40:8000; // localserver } "nginx.conf" 66L, 1729C #user nobody; #Defines which Linux system user will own and run the Nginx server worker_processes 1; #Referes to single threaded process. Generally set to be equal to the number of CPUs or cores. events { worker_connections 1024; # worker_processes and worker_connections allows you to calculate maxclients value: # max_clients = worker_processes * worker_connections } http { include mime.types; default_type application/octet-stream; keepalive_timeout 65; upstream django { server 172.30.1.40:8000; // local } server { server_name fidochallenge486.tk; location / { uwsgi_pass django; include /usr/local/etc/nginx/uwsgi_params; proxy_redirect off; proxy_pass_header Server; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto … -
Returning a filter result in a different page - Django
I've searched up but nothing seams to do the trick or be on point. Let's say i have two websites on page A.html i have a filter (djnago_filter) and B.html is empty. If the user submits the search form he is redirected from page A.html to page B.html where the results are displayed with for loop. How do i to that? I was thinking about passing the data from querry set to another view but there must be better solution to this. -
django extra views with CreateWithInlinesViews rendering in template
let's say, I have following django code...... views.py from extra_views import CreateWithInlinesView, UpdateWithInlinesView, InlineFormSetFactory class ItemInline(InlineFormSetFactory): model = Item fields = ['sku', 'price', 'name'] class ContactInline(InlineFormSetFactory): model = Contact fields = ['name', 'email'] class CreateOrderView(CreateWithInlinesView): model = Order inlines = [ItemInline, ContactInline] fields = ['customer', 'name'] template_name = 'order_and_items.html' def get_success_url(self): return self.object.get_absolute_url() and in the html template: <form method="post"> ... {{ form }} {% for formset in inlines %} {{ formset }} {% endfor %} ... <input type="submit" value="Submit" /> </form> Now the problem is: I need both inlines i.e. ItemInline and ContactInline in different section of html code within a single template. What should the solution for this? -
How to use Count over multiple fields in django?
How to use Count over many fields in Django? How to count row only if given multiple columns are unique? For example for a model below. class ProductViewed(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True, related_name="viewed") ip_address = models.CharField(max_length=255, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="views") created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{str(self.product)} viewed on {self.created_at}' class Meta: ordering = ('-created_at', ) verbose_name_plural = "ProductViewed" I want to achieve followings. Count based on user_id, ip_address, created_at__day. Is there any way to do so? Currently I could achieve the following Product.objects.annotate(vcount=Count('views__ip_address')) -
Gunicorn/Nginx configuration for Django 2.2 gives 502 Bad gateway
I am getting bad gateway 502 error when I access the site. This is how my configuration looks like /etc/nginx/sites-enabled/django upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/my_project/current/my_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/my_project/current/my_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/local/lib/python3.6/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn daemon for Django Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/my_project/current ExecStart=/usr/bin/gunicorn3 --name=my_project --pythonpath=/home/django/my_project/current --bind unix:/home/my_project/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py my_project.wsgi:application --log-file /var/log/gunicorn.log --log-level debug --workers=2 Restart=always SyslogIdentifier=gunicorn User=django Group=django [Install] WantedBy=multi-user.target When I run service gunicorn status, I can see this: ● gunicorn.service - Gunicorn daemon for Django Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2020-07-19 19:28:37 UTC; 7min ago Process: 9373 ExecStart=/usr/bin/gunicorn3 --name=my_project --pythonpath=/home/django/my_project/current --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py my_project.wsgi:application --log-file /var/log/gunicorn.l Main PID: 9373 (code=exited, status=1/FAILURE) Jul 19 19:28:37 admin-panel-s-2vcpu-4gb-fra1-01 systemd[1]: gunicorn.service: Service … -
In Pycharm, I can't fetch a JSON file and cannot install fetch
I am working on a Django project in Pycharm. I need to fetch API in the Javascript file, but it gives me an internal server error and error in the console showing the fetch line. It seems like it is not recognizing fetch at all. This is an example of how I use fetch in my code; document.querySelector('#compose-form').onsubmit = function () { fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: in_recipients, subject: in_subject, body: in_body, }) }) .then(response => response.json()) .then(result => { if (result.message !== "Email sent successfully."){ alert(result.error) } }); }; My code is actually working on Vscode but can't make it work in Pycharm. I tried pip install fetch I got the following error; ERROR: Command errored out with exit status 1: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\bilge\AppData\Local\Temp\pip-install-n1v3op9a\fetch\setup.py", line 6, in <module> description = file(os.path.join(here, 'README.txt')).read() NameError: name 'file' is not defined ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Also tried python setup.py egg_info says: can't open file 'setup.py': [Errno 2] No such file or directory Thank you in advance. -
Algorithm Visualization using Django
I'm building a website using the Django framework. I want to add an algorithm visualization tool. The way I think about it is: I want to create different .py files that will contain the algorithms (example: bubble_sort.py, insertion_sort.py ...) Then I want to create some animations files (using js or CSS), and then feed the .py files to the animation files, in order to separate the algorithm's logic from the animation logic. I have looked on the internet, but I can't find some useful resources. If you have any idea how I can proceed, feel free to suggest them. Thanks, -
TypeError("Unable to serialize datetime.time(11, 0, 6, 499000) elasticsearch
I'm trying to save a data in django database to be indexing in elasticsearch. I always receive the error below Error : SerializationError({'id_MyClass': 1916, 'date': datetime.date(2020, 7, 19), 'system_username': user11, 'system_computer_name': 'NOCOMPUTERNAME','time': datetime.time(11, 0, 6, 499000)}, TypeError("Unable to serialize datetime.time(11, 0, 6, 499000) (type: <class 'datetime.time'>)")) data exemple : time :10:25:07.039000 system_username : user32 system_computer_name : nosystemcomputername models.py class MyClass(models.Model): id_MyClass=models.AutoField(primary_key=True) date = models.DateField(default=date.today) time = models.TimeField() system_username = models.CharField(max_length=50, null=True, blank=True) system_computer_name = models.CharField(max_length=50, null=True, blank=True) forms.py class MyClassForm(forms.ModelForm): class Meta: model = MyClass fields = ( 'system_username', 'system_computer_name', 'time') views.py from datetime import time from .forms import MyClassForm from django.shortcuts import redirect def my_class(request): # If the form has been submitted by user if request.method == 'POST': data["time"]=time.fromisoformat(request.POST['time']).isoformat() data["system_username"]=request.POST['system_username'] data["system_computer_name"]=request.POST['system_computer_name'] try: form = MyClassForm(data) if form.is_valid(): form.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass return HttpResponseRedirect(reverse("my_html_page")) document.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import MyClass # write an index (like a model in models.py) @registry.register_document class MyClassDocument(Document): class Index: # Name of the Elasticsearch index name = 'myclass' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = MyClass # The model associated with … -
I want the project to named something else. How can I safely rename the project?
I have worked on my django project for quite a while, but realized I want the project to named something else. How can I safely rename the project? -
Uploading images with ajax to django rest framework
i want to upload images to my django app using drf and ajax i dont have a model to do i just want to serialize data here is serializers.py first_name = serializers.CharField() last_name = serializers.CharField() password1 = serializers.CharField() password2 = serializers.CharField() prof_img = serializers.ImageField() bio = serializers.CharField() email = serializers.EmailField() this is views.py @api_view(['POST']) def register_api(request): if request.user.is_authenticated: return redirect('/') print('register_api') # print(request.data) serialized = RegisterSerializer(data=request.data) print('hi') if serialized.is_valid(raise_exception=True): print('valid') print('data -> ', serialized.data) return print('invalid') i just want to print data, everything gets serilized but shows prof_img = {} this is my function from where i am sending data async function register_form_submit(event) { event.preventDefault() var formElm = event.target const myFormData = Object.values(event.target).reduce((obj, field) => { obj[field.name] = field.value; return obj }, {}) console.log(myFormData) myFormData.prof_img = imgElm.files[0] console.log('new -> ', myFormData) const csrftoken = getCookie('csrftoken') const options = { method: 'POST', headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken }, body: JSON.stringify( myFormData ) } const resp = await fetch('/accounts/register_api', options) console.log(resp) console.log(resp.message) console.log(resp.status) } i tried removing "Content-Type": "application/json", but then python console showed Unsupported Media Type: /accounts/register_api this is my snipped from settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': DEFAULT_AUTHENTICATION_CLASSES, 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES, 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ) } -
Django CSRF Token with Axios
Situation: I am attempting build a full SPA using Vue.js as my front end and Django as my back end. These systems are entirely separate (not a hybrid app with the index.html page served by the back end). Approach I created a services directory in my Vue-CLI generated project that provides the general accessibility for my REST API via the api.js file (contents below): import axios from "axios"; import Cookies from "js-cookie"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; const BackEnd = "http://127.0.0.1:8000/"; //local backend from manage.py runserver export default axios.create({ baseURL: `${BackEnd}api/`, timeout: 5000, headers: { "Content-Type": "application/json", "X-CSRFToken": Cookies.get('csrftoken') } }); How do I know there is such a token to get? I wrote an API endpoint that provides the token in the Response headers (shown below): Access-Control-Allow-Origin: * Content-Length: 77 Content-Type: application/json Date: Sun, 19 Jul 2020 18:04:06 GMT Server: WSGIServer/0.2 CPython/3.7.6 Set-Cookie: csrftoken=HdM4y6PPOB44cQ7DKmla7lw5hYHKVzTNG5ZZJ2PqAUWE2C79VBCJbpnTyfEdX3ke; expires=Sun, 18 Jul 2021 18:04:06 GMT; Max-Age=31449600; Path=/; SameSite=Lax Vary: Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Problem While my Django REST Framework API is doing a create job serving up all the data for my GET requests, I cannot seem to assign the csrftoken properly to authenticate my POST requests. Even with the X-CSRFToken … -
Django ignores hierarchy inside media
I want to save an image: def upload_file(f, path, filename): logging.info(os.path.join(settings.MEDIA_ROOT, path)) logging.info(os.path.join(settings.MEDIA_ROOT, path, filename)) if not os.path.exists(settings.MEDIA_ROOT + '/' + path): os.makedirs(settings.MEDIA_ROOT + '/' + path) with open(settings.MEDIA_ROOT + '/' + path + filename, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) Output of the both logging lines: D:\Programmierung\Python-Projekte\JourneyMap\media\0c472090-fb97-403f-84be-6972a0b4465e\1 D:\Programmierung\Python-Projekte\JourneyMap\media\0c472090-fb97-403f-84be-6972a0b4465e\1\img_3363.jpg But every time I want to save django throws the error: FileNotFoundError at /journey/1 [Errno 2] No such file or directory: '/media/IMG_3363.JPG' 0c472090-fb97-403f-84be-6972a0b4465e\1 always gets ignored, but why? -
Problem declaring django oauth toolkit urls
I am trying to declare django-oauth-toolkit endpoints in my main app's urls.py like below: #urls.py oauth2_endpoint_views = [ path("authorize/", oauth2_views.AuthorizationView.as_view(), name="authorize"), path("token/", oauth2_views.TokenView.as_view(), name="token"), path("revoke-token/", oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] urlpatterns = [ path("admin/", admin.site.urls), ... re_path(r"^o/", include(oauth2_endpoint_views, namespace="oauth2_provider")), ] Which is based on this part of Django-oauth-toolkit's tutorial. But I get this error: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Can anybody help me solve this? -
Two different types of user with different username field types
Default User Model: class User(AbstractBaseUser, PermissionsMixin): avatar = models.ImageField(upload_to='user/avatar', null=True, blank=True) date_joined = models.DateField(auto_now_add=True) username = models.EmailField(unique=True, null=False, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_employer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) object = managers.UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' Employer model that extends from User: class Employer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=256, blank=False, null=False) address = models.CharField(max_length=256, blank=False, null=False) fax = models.DecimalField(max_digits=11, decimal_places=2, blank=True, null=True) email = models.EmailField(unique=True, blank=False, null=False) economic_code = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) national_id = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) Employee model that extend from User: class Employee(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) employer = models.ForeignKey(Employer, null=False, blank=False, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) national_id = models.PositiveIntegerField(null=False, blank=False) date_of_birth = models.DateField(blank=False, null=False) post = models.CharField(max_length=100, null=True, blank=True) mobile = models.DecimalField(max_digits=11, decimal_places=2, null=False, blank=False) personnel_code = models.PositiveIntegerField(null=True, blank=True) eligible_leave = models.FloatField(default=0, blank=False, null=False) sick_leave_per_month = models.FloatField(default=0, null=False, blank=False) rfid_card_code = models.CharField(max_length=256, blank=False, null=False) I want the employer to be authenticated by email and the employee by national code (username filed). How?