Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I how to check for authenticated user and show then show a different content in django
What am trying to do is have two different user locations. One is from my user model and the other is default from view. I want that anytime a user is authenticated, the location from the model shows but if not logged in the default location should be passed to the view. Views.py class Home(generic.TemplateView): template_name = "Home.html" def get_context_data(self, **kwargs): context = super(Home, self).get_context_data(**kwargs) if User.is_authenticated: map_location = self.request.user.location_on_the_map else: map_location = Point(longitude, latitude, srid=4326) context.update({ 'job_listing': JobListing.objects.annotate( distance=Distance("location_on_the_map", map_location) ).order_by("distance")[0:6] }) return context -
Django 403 Forbidden POST/PUT when requesting from Reactjs (strict-origin-when-cross-origin)
I have a reactjs project that makes requests using API to django-rest-framework. It was working fine and this problem suddenly appeared which is super weird. I'm already using django-cors-headers. My settings.py: INSTALLED_APPS = [ ... 'rest_framework', "corsheaders", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True My reactjs request: fetch('/api/user/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(obj) }) I just want to emphasize that it was working fine and suddenly after editing the code, it stopped working. -
how to prevent user from submitting the same form twice
I have the codes below in my views and models. But I want a situation in which a user cannot submit the same form twice. once a user submits the form he or she can only see a preview of what has been submitted but is unable to submit the same form. Any help would be highly appreciated. Thanks #views.py def index(request): form = MembershipForm() if request.method == 'POST': form = MembershipForm(request.POST) if form.is_valid(): form.save() return redirect("home") return render(request, 'index.html', {'form': form) #models.py class Membership(models.Model): fullname = models.CharField(max_length=500, blank=True, null=True) location = models.IntegerField(default='0',blank=True, null=True) department = models.IntegerField(default='0',blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return str(self.fullname) -
Dynamically change Char/IntegerField choices for each Model instance
I'm wondering if it's possible to dynamically change the choices of an IntengerField for each instance of a Model. I'm working with a video game API and i want PLATFORM_CHOICES to be unique for each game, since not every game is released on the same platform. For example, on the first iteration, the platform choices for game1 could be PlayStation & Xbox, but game2 could be PlayStation, Xbox, Nintendo, & PC. models.py class TestModel(models.Model): PLATFORM_CHOICES = [] platform_type = models.IntegerField(choices=PLATFORM_CHOICES, null=True) game = models.CharField(max_length=200, null=True) api.py def get_games(self): new_url = "{}{}".format(self.url, 'games') data = requests.get(new_url, params=self.query).json() games = data['results'] for game in games: t = TestModel() for platform in game['platforms']: id = platform['platform']['id'] # int name = platform['platform']['name'] # str t.PLATFORM_CHOICES.append((id, name)) # add tuple to list t.save() t.game = game['name'] t.save() I've tried different variations of this but the IntField always ends up empty. Please let me know if there's anymore info I can provide. -
Django Rest Framework - Unable to UPDATE Table Via AJAX through PUT HTTP Method
I have a small project where I have built an API and it feeds the frontend via ajax. All the other CRUD functions work apart from UPDATE. When I use Postman, the UPDATE API works perfectly. So I'm guessing the problem is on the ajax side. I have searched for a solution to no avail. Some help on this would be highly appreciated. Here is my UPDATE API @api_view(['PUT']) def EditProductAPI(request, id): product = Products.objects.get(id=id) serializer = ProductSerializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_304_NOT_MODIFIED) My Update From <!-- Edit Product Modal --> <div class="container"> <div class="modal fade" id="editProduct" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="editProduct" action=""> {% csrf_token %} <input type="hidden" id="Myid" value=""> <div class="form-group mb-3"> <label for="p-name">Product Name</label> <input type="text" class="form-control" id="p-name" name="name" placeholder="Product Name" required> </div> <div class="form-group mb-3"> <label for="p-category">Category</label> <select class="form-control form-select" aria-placeholder="Category" id="p-category" name="category" required> <option selected disabled>Category</option> <option value="Electronics">Electronics</option> <option value="Furniture">Furniture</option> <option value="Toys">Toys</option> <option value="Hardware">Hardware</option> <option value="Medicine">Medicine</option> <option value="Groceries">Groceries</option> </select> </div> <div class="form-group mb-3"> <label for="p-quantity">Quantity</label> <input type="number" class="form-control" id="p-quantity" name="quantity" placeholder="Quantity" required> </div> <div class="form-group mb-3"> <label for="p-price">Price</label> <input type="number" … -
django.db.utils.IntegrityError: (1048, "Column cannot be null") while using nested serializer
i got a problem while trying to serializer.save(). django.db.utils.IntegrityError: (1048, "Column 'person_id' cannot be null") i want to create a POST and PUT request, but i am getting the messege above. it is happand while i am adding a nested serializer at trainee serializer. person and fav_sport fields can not be null = true blank = true it is happans either when depth = 1 i hope you can help me why is that. this is the json i send: { "person":15, "sport_type":[1,2] } i do nested serializer because i want the api returns this at GET and POST and PUT requsets: { "person": { "id": 15, "first_name": "liad3", "last_name": "hazoot3", "birth_date": "1999-01-03", "gender": "M", "is_coach": true, "user": 11 }, "fav_sport": [ { "id": 2, "name": "Swimming", "raiting": 3 }, { "id": 3, "name": "soccer", "raiting": 2 } ] } sport type model class SportTypeDB(models.Model): name = models.CharField(verbose_name='name', max_length=255, unique=True) raiting = models.IntegerField(default=1, validators=[MaxValueValidator(5), MinValueValidator(1)]) spot type serializer class SportTypeSerializer(serializers.ModelSerializer): class Meta: model = SportTypeDB fields = '__all__' person model: class PersonDB(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('D', 'Different'), ) user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) first_name = models.CharField(unique=False, max_length=100) last_name = models.CharField(unique=False, max_length=100) birth_date = models.DateField() gender = models.CharField(max_length=1, … -
Django - IntegrityError ... NOT NULL constraint failed on save()
I'm very new to Python and Django so please bear with me. I'm running into a persistent error traced back to the "saleitem.save()" line in the below views.py. I'm trying to create a form that will allow me to populate various fields and then save and display that information on an active_listing.html page. views.py def create_listing(request): if request.method == "POST": saleitem = Listing() saleitem.user = request.user saleitem.item =request.POST.get("item") saleitem.description = request.POST.get("description") saleitem.category = request.POST.get("category") saleitem.bid = request.POST.get("bid") saleitem.image = request.POST.get("image_upload") saleitem.save() listings = Listing.objects.all() empty = False if len(listings) == 0: empty= True return render(request, "auctions/active_listing.html",{ "listings": listings, "empty": empty }) else: return render(request, "auctions/create_listing.html") models.py class User(AbstractUser): pass class Listing(models.Model): saleitem = models.CharField(max_length = 60) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller", null=True) description = models.TextField() category = models.CharField(blank = True, max_length= 60) bid = models.DecimalField(max_digits=5, decimal_places=2, default=0) image = models.URLField(blank=True, null=True) listing_status = models.BooleanField(blank=False, default= True) winning_bidder = models.ForeignKey(User, blank= True, on_delete= models.CASCADE, related_name = "winner", null = True) bidding_status = models.BooleanField(default=False) def __str__(self): return self.item I've tried using a Django form rather than an html template as well and run into the same issue. When I populate all the fields in my html form and hit the save button, … -
Django Apache2: Module Not Found
Looking for some help on this. Thanks in advance for any assistance that you are able to provide. Django 3.2.8 Python 3.8.10 Apache 2.4.41 Obtaining the following error when starting django w/apache: mod_wsgi (pid=74176): Failed to exec Python script file '/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py'. mod_wsgi (pid=74176): Exception occurred processing WSGI script '/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py'. Traceback (most recent call last): File "/home/adjutant/srv/dj/soulrendnd/venv/soulrendnd/soulrendnd/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/adjutant/srv/dj/soulrendnd/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'soulrendnd' Abbreviated output of tree -if from ~adjutant/srv/dj/soulrendnd/venv: . ./bin ... ./lib ... ./soulrendnd ./soulrendnd/manage.py ./soulrendnd/my_secrets.py ./soulrendnd/soulrendnd ./soulrendnd/soulrendnd/asgi.py ./soulrendnd/soulrendnd/__init__.py ./soulrendnd/soulrendnd/settings.py ./soulrendnd/soulrendnd/urls.py ./soulrendnd/soulrendnd/urls.py.bak ./soulrendnd/soulrendnd/views.py ./soulrendnd/soulrendnd/wsgi.py ./soulrendnd/static ./soulrendnd/templates ./soulrendnd/templates/index.html settings.py import os """ Django settings for … -
Django query with foreign key- output should be from two models
I am creating a querying website, which has two models, which connect with a foreign key. My goal is to have a searching page, where I given in a Person_ID as an input and get both Person and Report data (Report_ID, file_ID, Person_ID, name). Right now upon Person_ID entry it gives out Report data, but for some reasons, it does not give out the Person_ID itself and nothing from the Person table. my model: class Person(models.Model): Person_ID = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255) def __str__(self): return self.Person_ID class Report(models.Model): Report_ID = models.CharField(primary_key=True, max_length=255) file_ID = models.CharField(max_length=255) person = models.ForeignKey(Person, on_delete=models.CASCADE) def __str__(self): return self.Report_ID view.py: class HomePageView(TemplateView): template_name = 'home.html' class SearchResultsView(ListView): model = Person template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list= Report.objects.filter( Q(person__Person_ID__icontains=query) ) return object_list admin.py class ReportAdmin(admin.ModelAdmin): list_display = ("Report_ID", "file_ID",) admin.site.register(Report) admin.site.register(Person) -
User Model Customisation in Dotnet
I used to work with django , but recently i got a new project with dotnet and I got confused when creating the user model , should I extend IdentityUser or create a user profile and leave the IdentityUser unchanged . -
Can I display model Post and model Topic all in one
Can I display model Post and model Topic all in one and add virtual field for know when loop it in template class Topic(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField(default='0') class Post(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField(default='0') class allon(Topic,Post): def home(request): all_posts = allon.objects.all( ) return render(request, 'forum/home.html', {'edd': all_posts }) -
ODBC Driver 17 for SQL Server: Client unable to establish connection, macOS, django, pyodbc
Everything was working until I restarted my laptop. I have this setup: python 3.8.8 django 3.1.1 pyodbc 4.0.30 pyodbc.drivers(): ['ODBC Driver 17 for SQL Server'] SQLServer cat /etc/odbcinst.ini returns this: [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/usr/local/lib/libmsodbcsql.17.dylib UsageCount=10 cat /etc/odbc.ini returns this: # [DSN name] [MSSQL] Driver = ODBC Driver 17 for SQL Server Server = tcp:<my server>,1433 in the django settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } I reinstalled the ODBC Driver with this official Microsoft instruction. But it didn't help. I'm still failing to start the django server and facing this error: django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection (0) (SQLDriverConnect)') That's pretty weird that everything was working for a long time until I restarted my laptop (no OS update, just restarting). May be this issue related to exporting some variables with path? Or may be after the ODBC Driver installation on macOS I need to set up this driver somehow? P.S.: jdbc driver works without any issues with the same servername, … -
I keep getting this error NOT NULL constraint failed: lists_listcreate.user_id
I am trying to make a site where users can make lists and then view those lists. How my site is set up is the user creates the list and gives it a name and then they move on to the next page where they can add items to their list. The login prosses works fine and you can go to the creat list page just fine. however, when you hit next on the create list page and try to go to the page where you go to the page where you add items to the list it gives you this error: IntegrityError at /your_lists/new_list/ NOT NULL constraint failed: lists_listcreate.user_id Views: from django.shortcuts import render from .models import List, ListIcon, ListCreate from django.views.generic import TemplateView, CreateView from django.views.generic.edit import FormView from django.contrib.auth.mixins import LoginRequiredMixin from . import models from .forms import AddListItemForm, CreatListForm from django.http import HttpResponseRedirect # Create your views here. class CreateList(CreateView, LoginRequiredMixin): model = ListCreate form_class = CreatListForm template_name ="lists/list_form.html" success_url = '/add_item/' class AddListItem(CreateView, LoginRequiredMixin): model = List form_class = AddListItemForm template_name = "lists/AddListItem.html" def index(requst): list = CreateList.objects.all() if request.method == "POST": if "add_one_more" in requst.POST: list.save() return redirect("/") if "done" in requst.POST: return redirect("/lists/your_lists/") … -
Wagtail CMS how to validate the content of one page before publishing or saving it as draft
I am trying to make a page with Wagtail CMS that validates the content whenever I save/publish the page inside the admin editor. The content that I want to be validated is the content of 3 SnippetChooserPanels from within the page. Basically let's say I have these 3 snippets : SnippetA, SnippetB and SnippetC and these snippets (or Django models because that's what they really are) have the following relationships: SnippetA has one to many relationship with SnippetB SnippetB has one to many relationship with SnippetC. When the user saves/publishes the page I want to verify: that all the 3 snippet types have been chosen that there is a correct relationship between the snippets (ie SnippetC belongs to SnippetB , and SnippetB belongs to SnippetsA, or in other words the 3 snippets are joined together correctly in SQL database terms) Thank you! -
How do you initialize a Django FileField with multiple files?
I have a model that saves multiple uploaded files for a document. I was able to use the FileField widget on the form to allow for multiple file uploads. However, whenever I went to update the document object, the FileField widget would not populate with the initial data. I was finally able to figure out that I needed to set the initial data and a URL on the initial data for the widget to render appropriately. But it just wasn't working out with a list of File objects. How can I get this to work right? -
What's the best practice for requests.session sharing between requests in a Django Rest Framework web application?
Is it safe to use a global, static session to communicate with external APIs? Is there a reasonable indicator for when a session should be refreshed, or is using a session a bad idea? Background: I'm currently working through optimizing a Django Rest Framework application that is taking too long (>1.2 seconds) to get responses from a remote API. Based on their timings, and comparing it to a few run-throughs on Postman, the longest running components seem to be a combination of TCP and SSL handshake when they weren't cached (running django_cprofile_middleware against the endpoint showed a similar theme, with hundreds of milliseconds being spent on those aforementioned handshakes). I was able to get those interactions down to about the same in the application as in Postman after the first request by using a shared requests.session instead of a basic requests.get (closer to 200 ms per request). -
Django Admin can't display attributes in a model with multiple Foreign Keys to another model
Basically I have two models, one for Icons and another for Types which have 3 icons (business rule). In my models.py file I have the following: class Icon(models.Model): name = models.CharField(max_length=60) image_URL = models.CharField(max_length=255) modified_date = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length=60) modified_date = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) icon1 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon1") icon2 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon2") icon3 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon3") def __str__(self): return self.name In my admin.py file I have the following: class TypeAdmin(admin.ModelAdmin): list_display = ( 'name', 'icon1__name', 'modified_date', 'creation_date', 'id' ) ... admin.site.register(models.Type, TypeAdmin) Everything works fine but I can't get it to display the icon's name. This works for other classes which have a single Foreign Key attribute of the same model, however here since there's three Foreign Key attributes of the same model, I get an error: <class 'app.admin.TypeAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'icon1__name', which is not a callable, an attribute of 'TypeAdmin', or an attribute or method on 'app.Type'. What is causing this error? How may I fix it? The FK is allowed to be null (or blank) because some types are allowed to not have … -
Django Admin: Model Foreignkey has null & blank = True, but using formfield_for_foreignkey in Admin makes it required
My model has a ForeignKey with null=True / blank=True, but when I try to alter an object in Django Admin I am using def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'parent_locale': return ParentLocaleChoiceField(queryset=models.Locale.objects.all().order_by('display')) return super().formfield_for_foreignkey(db_field, request, **kwargs) to alter how the data displays there. But doing this now throws an error when submitting saying the field is required. How to do I make this field not required when using formfield_for_foreignkey to alter the choice field display? -
How to plot data in a Jupyter Notebook when the Python kernel is executed remotely?
I have a Django application running on a remote machine and I would like to plot some data in my local browser in a Jupyter Notebook. I can work locally with the models in a Notebook but for some reason I'm unable to display chart. What could be the reason ? Basic code example to display chart (source) : import matplotlib.pyplot as plt time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') My problem is that output is only string but no chart : Text(0, 0.5, 'Position (km)') This is how I execute the notebook using the shell_plus Django extension (source). First I connect to the remote machine with: local_machine:~$ ssh -L 8888:localhost:8888 username@194.123.456.123 Then in the remote machine I start the Notebook : remot_machine:~$ python manage.py shell_plus --notebook --no-browser [I 16:30:24.804 NotebookApp] Serving notebooks from local directory: /var/www/myapp [I 16:30:24.804 NotebookApp] The Jupyter Notebook is running at: [I 16:30:24.804 NotebookApp] http://localhost:8888/?token=21addee513e29c1d890bed70320d613b39d1441e12419490 [I 16:30:24.804 NotebookApp] or http://127.0.0.1:8888/?token=21addee513e29c1d890bed70320d613b39d1441e12419490 [I 16:30:24.804 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 16:30:24.808 NotebookApp] To access the notebook, open this file in a browser: file:///home/user/.local/share/jupyter/runtime/nbserver-23578-open.html Or copy … -
How to conditionally apply a template filter in Django?
Suppose I have a Django template with <div><b>{{some.long.expression.with.stuff|filter1}}</b></div> and I only wish to apply filter1 if my_condition is True. What is the best way? Here is a verbose way with repetition: {% if my_condition %} <div><b>{{some.long.expression.with.stuff|filter1}}</b></div> {% else %} <div><b>{{some.long.expression.with.stuff}}</b></div> {% endif %} Here is slightly less verbose, harder to read, still with some repetition: <div><b>{% if my_condition %}{{some.long.expression.with.stuff|filter1}}{% else %}{{some.long.expression.with.stuff}}{% endif %}</b></div> Suggestions? -
Create django model instances from dataframe without server timeout
I am uploading a zipped file that contains a single CSV file. I then unzip it on the server and load it into a dataframe. Then I am creating django objects from it. This works fine until my dataframe becomes too large. When the dataset is getting too large the django server shuts down. I am assuming that this happens because every iteration in my loop increases memory and when there is no memory space left it shuts down. I am working with big datasets and want to make my code work no matter how big the dataframe. Imagine I have a df like this: cola fanta sprite libella 2018-01-01 00:00:00 0 12 12 34 2018-01-01 01:00:00 1 34 23 23 2018-01-01 02:00:00 2 4 2 4 2018-01-01 03:00:00 3 24 2 4 2018-01-01 04:00:00 4 2 2 5 Imagine that the columns could be up to 1000 brands and the rows could be more than half a Million rows. Further imagine I have a model that saves this data in a JSONB field. Thus every column is a django object, the column name being the name. The time-stamp combined with the data in the column is the JSONB field. … -
Signals for a database view in Django
I have a model in django that has the meta option Managed=False set. This model is a postgres view that get data from another schema. I would like to detect whenever the view changes (add/update/delete an object). I have tried using post_save from django.db.models.signals, but it doesn't seem to work. Is there some other way to achieve this? -
How do you add a third-party app inside your django app?
I'm currently working on a personal project. I'm working with Django but I'm not very experienced yet. I wanted to know how do you add a third party application inside you app ? Example: You have a small web-app with few pages and in one of them you want to load and use some external program e.g. Microsoft Paint. What do you need to do to add it (in general) ? Can you theoretically add any program you want or there are limits ? I would also appreciate if you could kindly show me where I can find useful documentation on this topic. Thank you ! -
modelManager get_by_natural key method change the USERNAME_FIELD affecting my authentication?
I have a custom User model that inherits from AbstractBaseUser which defines the username_field = email so that users will login using emails. class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email", unique=True) username = models.CharField(max_length=100, unique=True) last_name = models.CharField(max_length=100, blank=True, null=True) first_name = models.CharField(max_length=100, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_site_administrator = models.BooleanField(default=False) is_developer = models.BooleanField(default=False) is_project_manager = models.BooleanField(default=False) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) create_on = models.DateTimeField(verbose_name="Date Created", default=timezone.now) # So that we will be working primarily with email and not username USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() As the objects = UserManager() and this one contains a get_by_natural_key method as follows: def get_by_natural_key(self, username): return self.get(username=username) Now rather using the email to login it uses the username to login. Note that the userManager inherits from BaseUserManager like this class UserManager(BaseUserManager): Can somebody explain to me what is going on here. Is the problem coming from the inheritance or the get_by_natural_key() itself ? -
auth_permission table is empty after migrate on new database
I configured a django project to use a new database. After run migrations, all tables are there, custom migrations to insert some data are ok, but the auth_permission table is empty. My project uses the permissions everywhere and is now returning Permissions.DoNotExist exception. I couldn't find if there's something in the new version of Django (updated last week), but I've done the same procedure two months ago, and the permissions were created. Now, with the Django updated, it wasn't.