Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly authenticate with both username and email with oauth2 toolkit
I would like to be able to login either with username or email using oauth2 toolkit - when I log with an email, I want to pass email parameter, not username to distinguish them. This is what I came up with from django.contrib.auth import get_user_model from oauth2_provider import views class TokenView(views.TokenView): def create_token_response(self, request): try: email = request.GET.copy().pop('email')[0] self.set_username_from_email(request, email) except (KeyError, get_user_model().DoesNotExist): pass return super().create_token_response(request) @staticmethod def set_username_from_email(request, email): """ Parameters used for request are for some reason stored in request.META['QUERY_STRING'] which is just url query string, we need to parse it, and replace email with username """ a = [] for pair in request.META['QUERY_STRING'].split("&"): username = get_user_model().objects.get(email=email).username items = pair.split('=') if items[0] == 'email': items[1] = username items[0] = "username" a.append('='.join(items)) request.META['QUERY_STRING'] = "&".join(a) This works, but it feels really ugly to alter the parameters like this. Is there a better way how to do it? Perhaps extend something else then TokenView? I was inspired by https://stackoverflow.com/a/44226177/4710968 but the request.POST attribute is empty and adding something to it changed nothing. I am using Django 2.1.7 and oauth2_toolkit 1.2.0 -
Paginating without model in django
this is my first post ever related to programming therefore please forgive if it is a bit silly. I'm making a website that will aggregate real estate data from some classified ads websites. I've already managed to write simple scrapers that update the website's database and now I wanted to make the actual web app using Django. The website would take data from users that can search the real estate database according to their criteria (already set up a django form and provisionary interface for that.) I'm a newbie and don't know a lot about django therefore I've been trying to use a simple function-based-view to process queries and display results based on user's choices. I've got completely stuck on pagination - as some queries might have thousands of results it's absolutely essential to implement it but django paginator seems to only be working with a predefined django model. I've tried using django paginator to no avail as it appears to require defined models. I've tried the paginate library but there is no real documentation or examples so I couldn't make it work https://pypi.org/project/paginate/ I'm thinking of writing the pagination script by myself but it will take me a very … -
updating web site witout deleting database
I am using docker for my django project with ubuntu server. When I was chaning something always I am removing my docker images and building it again and my database also removed and I have to be populate my database again. I am trying these steps: pulling new code from git docker stop $(docker ps -aq) docker rm $(docker ps -aq) docker-compose up --build -d and as I mentioned my database also removed. I have tried without stopping and removing. Only docker-compose up --build -d but it did not worked. Also I tried docker-compose restart it also not worked. What I have to be tried. Please note that I am new in docker and django. Its my first project. -
How to add section titles/headers in between form fields in django?
I'm trying to get my form to look like this: except with empty checkboxes (could't find icons without a check) Drive and Woods ☑ Driver ☑ 3-Wood ☑ 5-Wood Irons ☑ 1-Iron ☑ 2-Iron ☑ 3-Iron ☑ 4-Iron ☑ 5-Iron Wedges ☑ SW ☑ PW I'm using Crispy Forms by the way. I can only get the checkboxes going down without the headers and without spaces they look like this right now: ☑ Driver ☑ 3-Wood ☑ 5-Wood ☑ 1-Iron ☑ 2-Iron ☑ 3-Iron ☑ 4-Iron ☑ 5-Iron etc... my forms.py looks like this right now class inputForms(forms.Form): Driver = forms.BooleanField(required=False) _3_wood = forms.BooleanField(required=False) _5_wood = forms.BooleanField(required=False) Hybrid = forms.BooleanField(required=False) _1_iron = forms.BooleanField(required=False) _2_iron = forms.BooleanField(required=False) _3_iron = forms.BooleanField(required=False) _4_iron = forms.BooleanField(required=False) _5_iron = forms.BooleanField(required=False) _6_iron = forms.BooleanField(required=False) _7_iron = forms.BooleanField(required=False) _8_iron = forms.BooleanField(required=False) _9_iron = forms.BooleanField(required=False) SW = forms.BooleanField(required=False) PW = forms.BooleanField(required=False) my views.py looksl like this: def inputsuser(request): forms = inputForms() return render(request, 'users/inputsuser.html', {'form': forms}) my template form looks like this: <form method="POST" style="margin-top:50px;" > {% csrf_token %} {{ form|crispy }} <div class="row"> <button class="btn green white-text">Submit</button> </div> </form> Trying to get each group of checkboxes separated by a title or header -
Is there any way I can relate multiple users(different type) from my custom user model to my other models?
I am trying to make to take advantage of django's authentication system, but having difficult time with user models I tried to extend my user model using these tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html. It was easy to follow and understandable until I got stuck while relating my newly extended user model to my existing models. My model has fields that relate to two types of my users at the same time, and I am using tuple within the field to differentiate my users. I searched for answers but the solutions are generic and I keep getting clash error messages when I tried to migrate. class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'Registral'), (2, 'Teacher'), (3, 'Parent'), (4, 'Admin'),) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) telephone = models.CharField(max_length = 50, null=True) is_active = models.BooleanField(default=False) class Registral(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) Admin_created=models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) parent_of = models.ForeignKey('Student',on_delete=models.CASCADE) class Student(models.Model): first_name = models.CharField(max_length = 50, null=True) last_name = models.CharField(max_length = 50, null=True) grade = models.IntegerField() member_of = models.ForeignKey('communicate.Class', on_delete=models.CASCADE) contact_parent = models.ForeignKey('Parent', on_delete=models.CASCADE) registered_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) How to migrate without error -
LDAP connect failed: socket connection error while opening: [Errno 111]
I recently deployed my Django project on a Linux Ubuntu server using LDAP backend for user authentication. Everything was working fine, but now I am receiving the error: LDAP connect failed: socket connection error while opening: [Errno 111] Connection refused when I attempt to login. The only real change I have made since the last working version was that I switched to using Google DNS (8.8.8.8). Would this cause any issues? Additionally, the LDAP backend works fine on the localhost. -
Multiple nested inheritance in templates
I have 4 models that need to be presented by chain inheritance each other. I'll show first two models to show what problem is - Parent and Child: I've tried to extend a parent template from base.html - it's works. But next, when i extend a child.html template from parent.html it outputs nothing. models.py: class Parent(models.Model): title = models.CharField( max_length=150, ) class Child(models.Model): title = models.CharField( max_length=150, ) parents = models.ManyToManyField( Parent, blank=True ) views.py: class ParentListView(ListView): model = Parent template_name = 'parent_list.html' context_object_name = 'parent_objects_list' class ChildListView(ListView): model = Child template_name = 'child_list.html' context_object_name = 'child_objects_list' parent_list.html: {% extends '_base.html' %} {% block title %}Parents_list{% endblock title %} {% block content %} {% for parent in parent_objects_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ parent.title }}</span> </div> </div> {% endfor %} {% endblock content %} shows parent list right. child_list.html {% extends 'parent_list.html' %} {% block title %}Childs_list{% endblock title %} {% block childs_block %} {% for child in child_objects_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ child.title }}</span> </div> </div> {% endfor %} {% endblock childs_block %} that returns empty. I think i need to pass an argument with key into childs block to filter childs of certain … -
"Authentication credentials were not provided." and terminal says Unauthorized: /api/auth/login/ django-rest-framework
I am using postman. when i do a post request to api/auth/login/, I get a 401 response "Authentication credentials were not provided.". In terminal, I do not get my print statement inside of the login serializer, I get Unauthorized: /api/auth/login/. This is my code: settings.py #just including the rest framework one here REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',) } views.py #just everything user related class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) print(user) if user:# and user.is_active: return user print("failed") raise serializers.ValidationError("No no to log in with provided credentials.") #Views class RegistrationAPI(generics.GenericAPIView): serializer_class = CreateUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(generics.GenericAPIView): serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) urls.py router = routers.DefaultRouter() router.register('api/games', GameViewset, 'games-name') urlpatterns = [ re_path(r"^", include(router.urls)), re_path(r'^api/auth/', include('knox.urls')), re_path(r"^api/auth/register/$", RegistrationAPI.as_view()), re_path(r"^api/auth/login/$", LoginAPI.as_view()) ] -
How to generate ping-pong api using Django Rest Framework?
I want to build a simple Ping-Pong using Django Rest Framework, so I don't need Model. I watch the api's status via swagger(drf_yasg), but I cannot find any parameters of it. I want to create Serializer, View and some code for routing. And I got some error lines from terminal. Serializer from rest_framework import serializers class PingPongSerializer(serializers.Serializer): ping = serializers.CharField(allow_blank=True, default="ping", max_length=20, help_text="please input 'ping'") # example_ping = PingPongSerializer({"ping": "hoge"}) # => {'ping' : 'hoge'} # example_ping = PingPongSerializer({}) # print(example_ping.data) # => {'ping' : 'hoge'} View from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from ping_pong.serializers import PingPongSerializer # Create your views here. class PingPongView(APIView): def get(self, request, format=None): serializer = PingPongSerializer(data=request) print(request) if serializer.is_valid(): print(request.data) return Response(serializer.data) else: print(serializer) print(serializer.errors) return Response({'result': "I don't know anything"}) Urls from django.contrib import admin from django.urls import path from django.conf.urls import url from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import routers from ping_pong import views from django.conf.urls import include # router = routers.SimpleRouter() # router.register(r'ping', views.PingPongView, base_name='ping') schema_view = get_schema_view( openapi.Info( title="Restful API Lists", default_version='v1', description="Ping Pong", license=openapi.License(name="MIT"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), # url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), … -
"Manager isn't accessible via model instances" when add data on ForgeinKey from ManyToManyField data
In models: class MyTeam(models.Model): captain_first_team = models.ForeignKey(FirstTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_first_team_set") team_player_first_team = models.ManyToManyField(FirstTeamPlayer, blank=True, related_name="team_player_first_team_set") In views: amar_team = get_object_or_404(MyTeam, pk=team_id) first_team_player = get_object_or_404(amar_team.team_player_first_team, pk=player_id) amar_team.objects.create(captain_first_team=first_team_player) Here, In MyTeam model I have a ManyToManyField field and a ForeignKey field. I want to add data in a ForeignKey field from ManyToManyField field data. I also try: amar_team.captain_first_team.add(first_team_player) amar_team.captain_first_team.save(first_team_player) But it's not working. How can I do this?? -
Model translation in Django Rest Framework
I'm developing an API with Django Rest Framework, and I'd need some models with a few fields that should support translation in multiple languages then, of course, serializers should have to retrieve the field with the expected language. I've thought about two options: adding extra fields to the model (one field for language) or creating another model with all texts in every language. On the other hand, I've seen that there are some libraries such as django-modeltranslation that are intended to solve that issue, however, I'd like to know some opinions about them. What do you think? What would you recommend to me? Thank you very much -
Why my_task.delay() works only within tasks module, not in models or views modules?
I have created tasks.py in my app. Celery tasks I have created can be called in cmd or inside tasks.py itself. But it is not possible to call them in views.py or models.py. -
'django.contrib.messages.context_processors.messages' must be enabled in DjangoTemplates
When I try to migrate or createsuperuser in my project I get this error. I shouldn't be getting error since it's a starter project and I'm not even using templates. SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E404) 'django.contrib.messages.context_processors.messages' must be enabled in DjangoTemplates (TEMPLATES) in order to use the admin application. -
Is there a way i can add the swagger integration to django project after adding i dont see all the endpoints on swagger api
I'm trying to integrate the swagger in Django project with DRF, but when i try to access the endpoint i dnt see all the endpoints https://django-rest-swagger.readthedocs.io/en/latest/ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_PAGINATION_CLASS': 'finishline.pagination.Paginator', 'PAGE_SIZE': 100, 'PAGINATE_BY_PARAM': 'page_size' } these are my settings -
How to show the correct name object in Django admin instead 'XXX object'
I've two apps in my Django Project and I created an ManytoManyField relationship between then. However, when I check it on my admin site, the references appears showing the model name plus object inside the Many to Many box. I already tried write a str in my model as you can see below: def __str__(self): return str(self.course.name) Below there is my models code. from django.db import models from cursos.models import Course class Person(models.Model): name = models.CharField(max_length=50) course = models.ManyToManyField(Course, blank=True) def __str__(self): return str(self.course.name) -
Parallel stored procedure execution in MySQL
I have a web application with following setup: Django 2.1.7 web application. I'm using gunicorn as my web server. Script to startup gunicorn server: gunicorn project_config.wsgi:application --worker-class=gevent --worker-connections=1000 --workers=8 I have concurrent API requests (It does some heavy processing, but mostly it is stored procedure calls - most time spent in doing IO). So when serving multiple API calls, I'm running multiple stored procedure calls parallely. Since I'm starting up my gunicorn server using gevent worker class, it creates 8 worker processes (not green-threads). Which means there is no context switching happening between each API requests. But my stored procedure call execution time doubles with number of API calls. So essentially a API request which gets completed is 10 minutes takes 20 minutes if there is another API call getting served parallely. Similarly if there are 3 requests being served parallely, each request is taking 30mins. Initially I thought this is something to do with multi-threading and GIL lock, as python threads do not actually run parallely. But when I print the PID (using os.getpid()), each requests prints unique PID (pid of the gevent worker process). My stored procedure is a complex select statement. It does not perform any DELETE/UPDATE … -
Django: Reference to an outer query may only be used in a subquery
I use the following queries: def get_queryset(self): posts = Post.objects.filter(topic_id=OuterRef('pk')) unread_posts = posts.exclude(read_by=self.request.user) return Topic.objects.all().annotate(is_unread=Exists(unread_posts), number_of_replies=Subquery(posts.count())).order_by('-latest_post') Unfortunately, I get the following error message: This queryset contains a reference to an outer query and may only be used in a subquery. I'm confused because I explicitly set Subquery(posts.count()). Can someone give me a hint? -
Django - What is the most pythonic way to update my page via AJAX?
I want someone with "manager" access to be able to view all user activity, and the page should continuously update after every couple of minutes via AJAX. Should I have both users and AJAX requests get sent to the same URL? Or should I have two separate URLs (one that renders a template and another one that only returns JSON)? Here is how I imagine this should be structured: def index(request): context = get_user_activity() if request.is_ajax(): # Process the data and only return updates they don't already have on their screen return JsonResponse(updated_data, status = 200) return render(request, 'activity.html', context) domain.com/activity/ <-- Users and AJAX requests are sent to this url OR domain.com/activity/ <-- Users get sent to this page domain.com/api/update-activity <-- AJAX requests are made to this URL -
ValueError: Cannot use object with type list for a spatial lookup parameter. Geodjango Model
In trying to build a Geodjango app, I encounter a ValueError. I have not done any spatial queries but I get stuck with ValueError: Cannot use object with type list for a spatial lookup parameter. I made the Point object as a GEOS Point Object, How can I solve this? from __future__ import unicode_literals from django.contrib.gis.db import models as geomodels from django.utils.crypto import get_random_string from django.contrib.gis.geos import GEOSGeometry,Point # Create your models here. geos_pnt=Point(4314498.56, 1003834.600) #pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt class Apartment(geomodels.Model): apt_id = get_random_string(length=8) location = geomodels.PointField(default=pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31), blank=True, null=True, srid=3857, help_text="Point(longitude latitude)") apt_cost = geomodels.FloatField(default=0.0) apt_area = geomodels.FloatField(default=0.0) SUBCITY_CHOICES = (('ADK','Addis Ketema'),('AKLTY','Akaki-Kality'),('ARD','Arada'), ('BL','Bole'), ('GL','Gulele'), ('KLF', 'Kolfe-Keranio'), ('LDTA','Ledeta'), ('NFS','Nefas Silk'), ('YK','Yeka')) apt_subcity = geomodels.CharField(default='NFS',max_length=100, choices=SUBCITY_CHOICES) register_date = geomodels.DateTimeField('Register Date',auto_now_add=True,null=True) def save(self, *args, **kwargs): #self.Latitude = self..y #self.Longitude = self.location.x super(Apartment, self).save(*args, **kwargs) class Meta: # order of drop-down list items ordering = ('apt_cost',) # plural form in admin view verbose_name_plural = 'apartments' def __unicode__(self): return self.apt_id -
Cannot assign "(<User: jack>, True)" "Profile.user" must be a "User" instance
i Use One-To-One Link With a User Model (Profile) and i got this error when i try to make user registration Cannot assign "(, True)": "Profile.user" must be a "User" instance. and this is user_registration uses in my project thanks for help def user_registration(request): form = UserRegistrationForm() if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] structure= form.cleaned_data['structure'].id user = User.objects.get_or_create (username=username, password=password) profile=Profile.objects.create (structure_id=structure,user=user) profile.save() messages.success(request, 'Enregistrement avec succés {}'.format(user.username)) return HttpResponseRedirect(reverse('compte:login')) else: form = UserRegistrationForm() return render(request,'compte/register.html',{'form':form}) -
Is there a way to initialize None-type class's attributes?
I have a 2 classes in my model. I would like to initialize a class and one of it attribute should contains another class (just for reference). My model is simple: class Base (models.Model): class Meta: abstract = True class Foo(Base): model = None field = models.CharField(max_length = 255) field2 = models.IntegerField() class Bar(models.Model): pass I opened shell and ttying to initialize an instance of Foo: f = Foo(model = Bar) Unfortunately I got an error: TypeError: Foo() got an unexpected keyword argument 'model' How should I properly pass this argument to Foo-constructor? I just trying not to overwrite __init__ -
Django: The page shows "(<django.forms.fields.BooleanField object at ...>)" at variable location in a template
I was trying include a checkbox on my template, but it showed me some text on the browser instead. I have a form (forms.py) that contains boolean field, e.g: Class MyForm(forms.Form): my_checkbox = forms.BooleanField(required=False, label='my_checkbox') and I have the following in my templates/my_app/my_form_template.py: <form id="form" method="post"> {{ form.my_checkbox }} <form> In the browser after running the server, I've got: (<django.forms.fields.BooleanField object at 0x0000014BE3CF9208>,) The CharField and ChoiceField work perfectly except BooleanField. What is a way to represent a checkbox on the template? I've tried {{ form }} in the template and it shows the checkbox, but I wish to custom the attributes of the checkbox. -
Django unit-test for custom backends authenticate function locks database
Unit-test for custom django backend's authenticate function is locking the test db I have a unit-test that tests the authenticate function of a custom backend that I have written in my django application. The test itself runs fine. However come cleanup time, django complains that there are active users connected to the test db django.db.utils.OperationalError: database "test_db" is being accessed by other users Following is a complete stack trace: Destroying test database for alias 'default'... Traceback (most recent call last): File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.OperationalError: database "test_dms_db" is being accessed by other users DETAIL: There is 1 other session using the database. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/ptvsd_launcher.py", line 43, in main(ptvsdArgs) File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/main.py", line 434, in main run() File "/Users/uname/.vscode/extensions/ms-python.python-2019.6.24221/pythonFiles/lib/python/ptvsd/main.py", line 312, in run_file runpy.run_path(target, run_name='main') File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/uname/Projects/python/data_mgmt_soln/manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/Users/uname/envs/dtmgmtenv/lib/python3.7/site-packages/django/core/management/base.py", line 316, … -
Column does not exist when altering model schema
So i have a model EpicData: class MiddlewareEpicData(models.Model): total_story_points = models.IntegerField() completed_story_points = models.IntegerField() code_review_story_points = models.IntegerField() incomplete_story_points = models.IntegerField(null=True) completion_percentage = models.IntegerField(null=True) code_review_percentage = models.IntegerField(null=True) Now i wanted to add a primary key called key so i alter this like so class MiddlewareEpicData(models.Model): total_story_points = models.IntegerField() completed_story_points = models.IntegerField() code_review_story_points = models.IntegerField() incomplete_story_points = models.IntegerField(null=True) completion_percentage = models.IntegerField(null=True) code_review_percentage = models.IntegerField(null=True) key = models.TextField(primary_key = True, default = "None") I add the default so when i migrate for the first time it will go through with no hitch. The problem is that now when i try to save a value to key it says that the column does not exist for some reason. For this particular migration i am also changing the name of another model so it deletes and adds a new one for that specific one, and i had to use python manage.py migrate --fake without really knowing what it does and it will go through. Here is the migration file: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kpi', '0006_auto_20190723_1520'), ] operations = [ migrations.CreateModel( name='ComponentMap', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.TextField()), ('component', models.TextField()), ('type', models.TextField()), ], options={ 'db_table': 'component_bug', }, ), … -
Django error admin.E033: username is not an attribute of users.CustomUser. Why is my custom user admin not working?
I am creating a custom user model in Django. I have defined a custom user model (users.CustomUser) which subclasses AbstractBaseUser. I have created a custom user manager (users.CustomUserManager) which subclasses BaseUserManager and works properly. I have also created a custom user admin which subclasses UserAdmin since my CustomUser model does not have a username field (it uses 'email' instead). As far as I can tell, I have coded everything properly, but when I run 'python manage.py makemigrations' I get an error message: <class 'users.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'users.CustomUser'. I'm stuck here. I have already tried the following: (1) Defined username field to be email in my custom user model class (2) Tried setting username to None in my custom user model class and custom user admin (3) Created custom user registration and change forms and registered them with my custom user admin # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): username = None firstname = models.CharField(max_length = 60) lastname = models.CharField(max_length = 60) email = models.EmailField(max_length = 240, unique=True) phone = PhoneNumberField(null=True, blank=True) company …