Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
users.models.Profile.user.RelatedObjectDoesNotExist: Profile has no user
I am designing a website to take in and store a users information under a profile. The main issue I am running into seems to be between the profile and user relationship. When I try and delete empty profiles from the admin page it gives me this error: (py3) (base) Ethans-MBP-2:opinions_app ethanjay$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 05, 2020 - 00:09:33 Django version 2.2.10, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [05/Mar/2020 00:09:42] "GET / HTTP/1.1" 200 3142 Not Found: /favicon.ico [05/Mar/2020 00:09:42] "GET /favicon.ico HTTP/1.1" 404 4608 [05/Mar/2020 00:09:46] "GET /admin/ HTTP/1.1" 200 8342 [05/Mar/2020 00:09:47] "GET /admin/ HTTP/1.1" 200 8342 [05/Mar/2020 00:09:50] "GET /admin/users/profile/ HTTP/1.1" 200 6300 [05/Mar/2020 00:09:50] "GET /admin/jsi18n/ HTTP/1.1" 200 3223 Internal Server Error: /admin/users/profile/ Traceback (most recent call last): File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, … -
filtering Django models by JSONField's date attribute when less that or greater then criteria
I have run into a situation where I have a JSONField as one of my model fields (running Postgres as DB). Json stored in DB looks something like this: {"date": "2020-06-06", "reason": "test reason"} I would like to write a filter which would get me all rows where date is less than today. I'm using Q object to setup my filter, but read somewhere that such lte and gte queries aren't supported yet. ex: query = Q(my_json_field__date__lt=today) &= Q(another_field=some_value) MyModel.objects.filter(query) Is there anyway to get around that limitation and may be combine raw sql with the other Q objects? There are several more Q objects in that query, so I don't want to drop to a complete SQL just yet if possible -
What is the best way to download log file (large text file) from server service
In my production have folder to store the log file. I want to make the html page to download 'log file' (large .txt file, around 1.5 gb/file) from server to client computer using Django (python) views. What is the best solution to do that (no lose data in downloaded file, good performance) now i use this code but the size of downloaded file is less than the original file in the server :C with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response -
How to use Customize Model extends from User Model in Django?
I'm new to Django and I have a problem that makes me quite confused. I have a page when users click to change profile, the corresponding page shows up and lets users update their profile. Here is my model: from django.db import models import os from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Account(models.Model): user = models.ForeignKey(User, on_delete="CASCADE") phone = models.CharField(max_length=18) room = models.CharField(max_length=8) dob = models.DateField(default=timezone.datetime.now()) active = models.BooleanField(default=True) avatar = models.ImageField(upload_to='images/', default=os.path.join(settings.STATIC_ROOT, 'avatar.png')) def __str__(self): return self.user.username Here are my forms: class UserForm(forms.ModelForm): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) class Meta: model = User fields = ['first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Account fields = ['phone', 'room', 'dob', 'active', 'avatar'] And I have my views.py like this: def show_form(request): user_basic_info = UserForm(request.POST) form = ProfileForm(request.POST) if form.is_valid() and user_basic_info.is_valid(): form.save() and user_basic_info.save() messages.sucess(request, _('Your profile has been successfully updated')) redirect('my_account') else: UserForm() ProfileForm() context = { 'user_basic_info': user_basic_info, 'form': form, } return render(request, 'my_account.html', context) Here is my_account.html template: {% extends 'base.html' %} … -
choice: flask, django api render to user search
I'm totally new to Django and working on a project to query data from a MongoDB usually my project is meant for the data, but in order to give it a sense and let the user see how is it, I'm required to create an API to fetch data based on queries sent by the user. My questions are: is there any preexisted views in rest_framework that can satisfy my needs(All I want is let the user search the data, based on fields that he can enter) Or should I use react as a frontend to send queries? Another Q, would it be easy, how is this task on flask can it be done so quickly? Please, if something is not clear, just ask? -
django model form modelform multipart
I'm newbie to web development. started with Django since I already do Python for AI. I'm trying to use multipart to model. but it appears doesn't support. /models.py from django.db import models from django.forms import ModelForm class ImageData(models.Model): lot_number = models.CharField(max_length=100) images = models.FileField(widget=ClearableFileInput(attrs={'multiple': True})) class ImageDataForm(ModelForm): class Meta: model = ImageData fields = ('lot_number', 'images') It seems I need to use 'forms' https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/ than... do I need to write same code for forms? like /forms.py from django import forms class ImageData(forms.Form): lot_number = forms.CharField(max_length=100) images = models.FileField(widget=ClearableFileInput(attrs={'multiple': True})) guess must be a way to handle model and form in one code but could find it. -
Why is max_length being ignored in BinaryField?
I am attempting to create an invite system to register users, which stores a md5 hashsum based on the object's ID. Here's how my model is defined: class Invite(TimestampedModel): user = models.ForeignKey(User, default=None, null=True, blank=True, on_delete=models.CASCADE) _code = models.BinaryField(max_length=16, unique=True) @classmethod def create(cls): invite = cls.objects.create() hash_obj = hashlib.md5() hash_obj.update(str(invite.id).encode('utf-8')) invite._code = hash_obj.digest() invite.save() return invite Thus when I call Invite.create(), I see a row in the database that has a _code that is 16 characters long (e.g. ��#�"��Zo�n�%��V). The problem arises, however, when I adjust max_length to 2. I expected Django to either throw an error or truncate the value to two bytes, but it did neither; I am still seeing 16 bytes in new rows. Yes, I ran makemigrations and migrate. What is going on here? This is a bit concerning that I can't limit the length at all. I assume it's defaulting to 50 but I have no idea why. Any thoughts are appreciated. BinaryField description here. -
How do I properly configure my app to use the Django phonenumber field module?
I'm using the Django 2.0, Python 3.7, and the Django PhoneNumber field -- https://github.com/stefanfoulis/django-phonenumber-field and have set up my model thusly ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have added this in my settings.py file ... PHONENUMBER_DB_FORMAT="RFC3966" However, when I submit my form using the following JSON ... { "name": "3999", "type": { "name": "Coworking Space" }, "address": { "street_number": "222", "route": "1212", "raw": "222 W. Merchandise Mart Plaza, Suite 1212", "formatted": "222 W. Merchandise Mart Plaza, Suite 1212", "latitude": 41.88802611, "longitude": -87.63612199, "locality": { "name": "Chicago", "postal_code": "60654", "state": 1 } }, "enabled": true, "phone": "303-234-1234", "email": null, "web_site": "http://www.1871.com/" } I get this error (a 400 response) ... {"phone":["The phone number entered is not valid."]} How else can I configure my server to recognize my phone number format (or do I need to change the format)? -
Django, Ajax and GET requests
There are plenty of similar questions here but I can't solve that problem I have. Situation is simple in theory - I send json to Django view, I get a json response. I did it with python, with Django, with REST framework. But with Ajax I can't do it, there's something with URLconf and ajax's relative url kind of stuff and I can't figure out what's wrong and how to make it work. I mean with some URL confs I can send a request with my chrome plugin and I have a response I need, but ajax is getting 404 with that confs. If I change it Django starts to return my html page instead of json response. What am I missing here? My ajax request: $.ajax({ url: 'ajax/apply_city/', type: 'GET', data: { 'city': obj.textContent }, dataType: 'json', success: function(data) { var str = ''; data.districts.forEach(function (district) { str += '<a class="dropdown-item" href="#" onclick="applyDistrict(this)">' + district + '</a>'; }); window.alert(str); document.getElementById("district_dropdown").innerHTML = str; }, }); urls that works with requests from everything but not ajax: re_path('^index/$', views.index, name='index'), re_path('^index/ajax/apply_city/', views.apply_city, name='apply_city'), Logs show Not Found: /index/... when ajax makes request and GET /index/... 404. I've seen that for ajax I … -
django drf big querys is very slow, how to optimize?
I'm new to python,and I'm doing my project with django, drf and postgreSQL,and my model has millions data,here is my model: class FetchdataByno(models.Model): bureau_name = models.CharField(max_length=16) station_name = models.CharField(max_length=20) board_train_code = models.CharField(max_length=10) start_station_name = models.CharField(max_length=16) end_station_name = models.CharField(max_length=16) corporation_name = models.CharField(max_length=20) sale_count = models.IntegerField(blank=True, null=True) price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price1 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price2 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price3 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price4 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) price5 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) date = models.CharField(max_length=8, blank=True, null=True) class Meta: managed = False db_table = 'fetchdata_byno' and the station/bureau/traincode has three possible values, my api is: @api_view(['GET', 'POST']) def report_no_list(request, format=None): if request.method == 'GET': # now = datetime.datetime.now() # date_end = datetime.datetime(now.year, now.month, now.day, 0, 0) # date_start = date_end - datetime.timedelta(7) # start = time.time() date = str(request.GET.get('date', '')) date = re.sub('-', '', date) try: bureau = request.GET.get('stations', '') station = request.GET.get('saleStation','') traincode = request.GET.get('trains','') except: raise if bureau == '' and station == '' and traincode == '': data = get_train() snippets = data.all_data(date=date) #111 elif bureau !='' and station == '' and traincode == '': if bureau == '[]': data = get_train() snippets = data.all_data(date=date) #211 else: select_data … -
Weird Behaviour in Django Forms
I was working with Django Forms , I was doing custom validation for a field, but encountered weird problem. forms.py class RegistrationForm(forms.Form): username = forms.CharField(max_length=50) email = forms.EmailField(required=False) password = forms.CharField(max_length=50) password1 = forms.CharField(max_length=50) def clean_password(self): password = self.cleaned_data['password'] print(self.cleaned_data) # all fields are present except password1 in cleaned Data re_password = self.cleaned_data['password1'] #Gives Key Error here # Do something Here when I try to do some validation for password field in clean_password function, It gives key error for password1 field ,I don't get why that happens. I tried searching a lot but couldn't find anything relevant, about what causes this error.But then I tried making some change in code and It worked but I don't know why it worked. modified_forms.py class RegistrationForm(forms.Form): username = forms.CharField(max_length=50) email = forms.EmailField(required=False) password1 = forms.CharField(max_length=50) #swapped position password = forms.CharField(max_length=50) def clean_password(self): password = self.cleaned_data['password'] print(self.cleaned_data) # all fields are present in cleaned Data re_password = self.cleaned_data['password1'] #Doesn't Give Key Error here # Do something The changes I made was I just swapped the line position of password1 and password ,that is I just changed the order of password and password1. I changed order password1 at line of password, password at position where … -
How to concatenate django countries with primary key to create custom code
Below is my Participant class. I want to create a custom code that concatenates the country field with the auto-generated primary key. Whatever I've tried till now has failed, can anyone help me, please. The structure of the code is supposed to be the country first and the primary key second. I need this because when I print my report the code should be present in it class Participant(models.Model): first_name = models.CharField(max_length=100) last_Name = models.CharField(max_length=100) country = CountryField()`enter code here` trainer = models.CharField(choices = trainer, max_length=100, ) gender = models.CharField(choices= gender, max_length=50) title = models.CharField(choices= title_Choice, max_length=100, blank=True, null=True) date_of_birth = models.DateField(null=True, blank=True ) contact_address = models.CharField(max_length=1000, blank=True, null=True) work_phone = models.CharField(max_length = 30, blank=True, null=True) fax_number = models.CharField(max_length = 100, blank=True, null=True) home_phone = models.CharField(max_length=30, blank=True, null=True) email = models.EmailField #previous_employment = models.CharField(max_length=100, blank=True, null=True) organization = models.ManyToManyField(Organization, blank=True) #role = models.ForeignKey(Role, on_delete=models.CASCADE) education_level = models.CharField(choices = education_level_choice, max_length=100, blank=True, null=True) comments = models.CharField(max_length=1000, blank=True, null=True) -
Django Celery Beat
My times keep drifting with django-celery-beat, and seems to be related to the last_run_date being wrong. The time drift gets worse over time and seems to be related to Will resetting the last_run_at on every run fix this? >>> from django_celery_beat.models import PeriodicTask, PeriodicTasks >>> PeriodicTask.objects.all().update(last_run_at=None) >>> PeriodicTasks.changed() -
I need a button to redirect me to other page
I am trying to redirect to other page when clicking a button, i have been using href but this time it does not work. Html <div class="float-right"> <a href="edit/{{ created_items.id }}/" class="btn btn-outline-warning btn-sm" style="margin-right: 5px;" role="button">Edit</a> </div> views.py def edit(request, id): created_items = Create.objects.get(id=id) if request.method == "POST": new_item = request.POST.get("content") item_id = request.POST.get("id") Create.objects.filter(id = id).update(text = new_item) return HttpResponseRedirect("/") else: return render(request, 'my_app/edit.html', {"created_items": created_items}) urls.py path('edit/<int:id>/', views.edit, name='edit'), -
Django sending email with html and embedded image only showing images
I tried to send html rendered email with images. I tried two methods send_mail(subject='', message='', from_email='noreply@test.com', recipient_list=[email], fail_silently=True, html_message=render_to_string('mail_template.html', context)) and html file used cid on to shows image. when I checked mail, this shows html template but images or not loaded. To embed image, I use different method basepath = os.path.dirname(__file__) + '/templates/' mailpath = basepath + 'mail_template.html' html_content = render_to_string(mailpath, context) msg = EmailMultiAlternatives(subject='', body='', from_email='noreply@test.com', to=[email]) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' for f in ['logo.png', 'logo2.png']: imagepath = basepath + f fp = open(imagepath, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send(fail_silently=False) This does not contain html rendered template, but only include two images. So I want to know if I send html email with embedded image. -
using django context processor to display a form with post method allowed
I have created an email form, using django context processor and included it in base template. The Idea is to be able to send email from all web pages. So far I can render form but cannot submit it. How do I handle post? Or is there other better way to do it? -
Django_Tables2 Not Loading Default Bootstrap Styles
I am following the tutorial on django-tables2 website (https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html) and I am unable to get my tables to display using bootstrap styles. I followed the exact tutorial and was successful in getting bootstrap styled tables, however, when implementing within my main project, it keeps the base formatting without bootstrap. Here is my html that includes the table: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block extra_head %} <link rel="stylesheet" type="text/css" href="/adminEdits/tatic/mainStyles.css" /> <script type="text/javascript" src="/static/scripts.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> {% endblock %} {% block content %} {% if user.is_authenticated %} {% load render_table from django_tables2 %} <h1>Edit Drivers</h1> {% render_table table %} {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} And my tables.py import django_tables2 as tables from tickets.models import User class UsersTable(tables.Table): class Meta: model = User template_name = "django_tables2/bootstrap.html" fields = ("user_id",)#"first_name", "last_name", "position", "admin_level", "email", "distribution_company_id") And my views.py from django_tables2 import SingleTableView from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.views.generic import ListView from tickets.models import User from .tables import UsersTable # Create your views here. def index(request): return render(request, 'adminEdits/index.html', context) class UsersListView(SingleTableView): model = User table_class … -
I built an image using docker, but an error was reported when I tried to run the image
I used dockerfile to build a Django image. Here's my dockerfile. An error was reported when I executed the docker run. enter image description here enter image description here -
Django Max DateTime Aggregation
What is the best way of getting the max datetime of related objects of related objects of a Django instance? I need this value as an instance property. For example, with these models, class Show(Model): is_live = BooleanField() ... class Season(Model): show = ForeignKeyField(Show, on_delete=CASCADE, related_name='seasons') is_live = BooleanField() ... class Episode(Model): season = ForeignKeyField(Season, on_delete=CASCADE, related_name='episodes') is_live = BooleanField() live_date = DateTimeField(blank=True, null=True) ... How could I get the most recent episode live_date of a show instance, including only episodes where the season is_live == True and the episode is_live == True? I have tried this in the Show model: @property def max_episode_live_date(self) return self.seasons.filter( is_live=True ).aggregate( max_=Max( 'episodes__live_date', filter=Q(episodes__is_live=True) ) ).get('max_') but I get this error AttributeError: 'str' object has no attribute 'tzinfo' I've tried using Django SubQuery expressions, @property def max_episode_live_date(self) episodes = Episode.objects.filter( is_live=True, season=OuterRef('pk') ).values('live_date') return self.seasons.filter( is_live=True ).aggregate( max_=Max(Subquery(episodes)) ).get('max_') but then I get django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') I believe this is due to some episodes containing null live_date, but I'm not sure how to work around. Any insight would be appreciated. -
How can I circumvent Suspicous UserAgent error using Django and Selenium with headless option set to Chrome
I am trying to launch a "Headless" version of Selenium using Django. When I run this script using python manage.py <script> using the command prompt through Django and adding 'headless' to Chrome options chrome_options.add_argument("headless"). I am getting this error because of the headless chrome option I can see but am unsure if I actually need to write Javascript to handle the issue or what is the best solution. How can I circumvent this problem using Django and Selenium? [0304/182708.625:INFO:CONSOLE(2919)] "A parser-blocking, cross site (i.e. different eTLD+1) script, https://ssl.google-analytics.com/ga.js, is invoked via document.write. The network reques t for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console me ssage. See https://www.chromestatus.com/feature/5718547946799104 for more details.", source: https://shop.tcgplayer.com/magic/lorwyn/oonas-prowler (2919) [0304/182708.625:INFO:CONSOLE(2919)] "A parser-blocking, cross site (i.e. different eTLD+1) script, https://ssl.google-analytics.com/ga.js, is invoked via document.write. The network reques t for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console me ssage. See https://www.chromestatus.com/feature/5718547946799104 for more … -
vue.js array into Django
So I want to go through my array which ive crated on vue.js and then check against the arrary to decide where to save it. To explain it a bit more here's the code i have so far Vue.js var app= new Vue({ el: '.con', data:{ posts: [ { title:'', content:'', type:'' } ], }, methods:{ addHead(index){ this.posts.push({ content:'', type:'header', }) }, addPara(index){ this.posts.push({ content:'', type:'para', }) }, removeForm(){ this.posts.splice(index, 1) } } }) HTML <div class="con"> <button type="button" name="button" @click='addHead()'> header </button> <button type="button" name="button" @click='addPara()'> Para </button> <input type="text" name="" placeholder="Title" v-models='posts.title'> <div id="body-fields"> <div class="car-body" v-for="(post, index) in posts"> <input type="textbox" name="" placeholder='{{post.type}}' v-models='post.content'> <span style="float:right;background-color:green" @click='removeForm(index)'> x </span> </div> </div> </div> So i want to save the posts array depending on the type so if its a header save it to one model and if its the other type save it to another, i'm using python and django, thanks for any help -
Django Deployment - the lack of access from outside of network (VPN / Proxy Issue)
I've developed a Django app for an organization that connection to their servers is only possible via VPNs. I tried to deploy it on the server (First I needed to connect to the VPN they provided to me), following digitalocean's instructions found here. I had deployed some other django projects using it and there was no problem. According to the instructions everything works and there is no error in up and running gunicorn + nginx. However, the connection to the websites could not be established (after about 20 secs, the browser throws timout error). I found that the problem is not about nginx + gunicorn config as the issue still appears when Django's development server is running. So I thought it is probably due to the VPN. I mean the website could not be accessed because the server is not accessible from the outside world. I would be grateful if you could provide a solution to this, or express your experiences. -
Adding Text to an Image in Django 2
I have added text to image using PIL in a python script. from PIL import Image, ImageDraw, ImageFont image = Image.open('my_img.png') draw = ImageDraw.Draw(image) myfont = ImageFont.truetype("calibrib.ttf", 40) points = 20,20 string = "My text for my_img.png" draw.text(points, string, "black", font=myfont ) image.save('my_img_WithTxt.png') image.show() exit() I was hoping to use the above script in Django when I am uploading images to the media folder. The script below works fine for uploading and retrieving images. def create_room(request): if request.method=='POST': form = RoomForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/core/roomlist') else: form =RoomForm() return render(request, 'create_room.html', { 'form':form }) The issue I have is that before I execute 'form.save()', I want to write some text on the image. Is there a way to extract the image field from 'request.FILES before saving it, write the text on image and then save it. -
Django - working with a 3rd party API along with pagination
Currently trying to learn Django. As a side project, I am trying to build a site that utilizes a 3rd party API. The user does a search, and my site displays photos based on that search once the search parameters are passed onto the 3rd party API and a response is received. The photos are displayed in a paginated manner. The API itself gives me a result in the form of: { page: 1 pages: 60000 photos: [...] //could contain anywhere from 10-100 items. Each item is a dict containing id, photo URL, as well other info } At the moment I have it set so that with each 'previous' or 'next' page, a new request is made to the API, after which the response could look like: { page: 2 pages: 60000 photos: [...] } Of course, this isn't really ideal as it involves constantly making calls to the API. My question is: would it be bad practice to convert these items into django models and store them in my database? Considering the number of items that would have to be stored. However, the advantage of having them in makes it easier to do things like 'liking' the photo, … -
get_user_model() vs settings.AUTH_USER_MODEL usage
I am new to Django and I am following a video tutorial to learn django. I am trying to understand get_user_model() and setting.AUTH_USER_MODEL. my directory looks like below: | simplesocial | accounts | | models.py | | views.py | | forms.py | | simplesocial |settings.py # models.py from django.db import models from django.contrib import auth from simplesocial import settings # Create your models here. class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return '@{}'.format(self.username) #forms.py from django.forms import forms from django.contrib.auth.forms import get_user_model from django.contrib.auth.forms import UserCreationForm from simplesocial import settings class UserCreateForm(UserCreationForm): class Meta: model = settings.AUTH_USER_MODEL fields = ('username', 'email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' #settings.py AUTH_USER_MODEL = 'accounts.User' I am getting below error ERRORS: accounts.User.user_ptr: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. Since I have a custom user model to be used. What am I doing wrong. If I replace settings.AUTH_USER_MODEL with get_user_model() will it use my custom User class? I could not understand how get_user_model() works