Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Node Js vs Django
I am just a 14 year old trying to learn web development I am fairly good with Django. And I recently heard of Node Js is it worth learning Node Js. Well, I wanted to make a live chatting website I wanted to know which would be better at making it. I also checked Firebase's real-time NoSQL Database as well but I heard some as it's not good when the project gets bigger. So is node js really worth learning? -
Salom Savolbor menda Pythondan
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 13, 2021 - 11:54:44 Django version 3.1.3, using settings 'school.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Shu narsani qande korsam bo`ladi? -
How to save model instance in Django through JavaScript in HTML
I am Building a BlogApp and I am stuck on a Problem What i am trying to do I made a instance named user_location in model. I accessed it in template and I write JavaScript code to access User's Location using JavaScript BUT i want my model instance to save the JavaScript's Output country in the Database. The Problem I don't know how to save model instance through JavaScript. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') user_location = models.CharField(mac_length=100,default'') profile.html <script> $.ajax({ url: "https://geolocation-db.com/jsonp", jsonpCallback: "callback", dataType: "jsonp", success: function(location) { $('#country').html(location.country_name); } }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div>Country: <span id="country"></span></div> #This is my model instance. {{ profile.user_location }} What have i tried I also tried THIS. BUT it didn't work for me. I don't know what to do. Any help would be Appreciated. Thank You in Advance. -
Handling three forms on the same page with one having multiple instances - Django
I am working on an Invoice that has three forms of which one has multiple instances. The first two forms each has one instance and the last one can accommodate as many as the user wants. meaning the user will be adding instances of the last form using JavaScript. With the below code I am getting an error that is saying that the fields of the first two forms are missing data cause whenever the user add extra fields to the last form Django thinks I am also adding extra forms to the other two forms. Please help This is an example of the POST data with two extra fields for the last form: form-TOTAL_FORMS '2' form-INITIAL_FORMS '0' form-MIN_NUM_FORMS '0' form-MAX_NUM_FORMS '1000' form-0-number '215' form-0-customer '4' form-0-sales_person '1' form-0-product '2' form-0-quantity '20' form-0-price '20' form-1-product '2' form-1-quantity '40' form-1-price '50' This is my view.py def createInvoice(request): invoiceFormSet = formset_factory(InvoiceForm) retailPriceFormSet = formset_factory(RetailPriceForm, extra=2) saleItemFormSet = formset_factory(SaleItemForm) if request.method == 'POST': invoiceform = invoiceFormSet(request.POST or None) retailPriceform = retailPriceFormSet(request.POST or None) saleItemform = saleItemFormSet(request.POST or None) if invoiceform.is_valid() and saleItemform.is_valid(): for si in saleItemform: saleItem = si.save() saleItem_id = get_object_or_404(SaleItem, id=saleItem.id) for i in invoiceform: inv = i.save(commit=False) inv.sale_item = saleItem_id … -
Django Error: local variable 'fav' referenced before assignment
I got an error in Djang, When I try to pass the favourite_add to ajax I got local variable 'fav' referenced before assignment def favourite_add(request, id): data = {} video = get_object_or_404(Video, id=id) if request.method == "POST": account = request.user.id if video.favourites.filter(id=account.id).exists(): fav = False video.favourites.remove(account) else: video.favourites.add(account) fav = True data["fav"] = fav print(data) return JsonResponse(data) -
i get this error in django ProgrammingError at /admin/persona/empleado/add/
the runserver runs correctly, but when i'm in django admin and try to add an employee i get that error message I suspect that the error is in the models.ManyToManyField, because I could add employees and they were saved correctly in the database, the ManyToManyField options were added to the django manager but when trying to save I get the error message https://i.stack.imgur.com/gZnKX.jpg from django.db import models from applications.departamento.models import Departamento from ckeditor.fields import RichTextField class Habilidades(models.Model): habilidad = models.CharField('Habilidad', max_length=50) class Meta: verbose_name='habilidad' verbose_name_plural='habilidades empleado' def __str__ (self): return str(self.id) + '-' + self.habilidad JOB_CHOICES=( ('0', 'CONTADOR'), ('1', 'ADMINISTRADOR'), ('2', 'ECONOMISTA'), ('3', 'OTRO'), ) class Empleado(models.Model): Firts_name = models.CharField('Nombre', max_length=50) Last_name = models.CharField('Apellido', max_length=50) Job = models.CharField('Trabajo', max_length=1, choices=JOB_CHOICES) departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE) habilidades = models.ManyToManyField(Habilidades) hoja_vida= RichTextField() def __str__ (self): return str(self.id) + '-' + self.Firts_name + '-' + self.Last_name -
I'm trying to add env var to django secret_key on github action but showing error
name: MoneyTracker Test on: push: branches: - master pull_request: branches: - master jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up python 3.7 uses: actions/setup-python@v2 with: python-version: 3.7 - name: Install dependency run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Lint with flake8 run: | pip install flake8 flake8 - name: Coverage report env: secret_key: ${{secrets.SECRET_KEY}} debug: ${{secrets.DEBUG}} db: ${{secrets.DB}} run: | pip install coverage coverage run MoneyTracker/manage.py test coverage report - name: Django testing run: | python3 MoneyTracker/manage.py test MoneyTracker Project link is in here. How should I add secret key to my project on GitHub action? Environment variables are case-sensitive. Commands run in actions or steps can create, read, and modify environment variables. To set custom environment variables, you need to specify the variables in the workflow file. You can define environment variables for a step, job, or entire workflow using the jobs. -
adding many to many relations is producing an empty queryset
I have a model called Occurrence with a number of foreign key and manytomany relationships (i've only shown a few fields here). I am having issues when attempting to create any manytomany relation to an Occurrence instance after I have loaded bulk data to my postgres (postgis) database using the sqlalchemy engine. Before this upload of data I can make relations as usual with: Occurrence.objects.get(ind='1010106').minmat.add(Material.objects.get(code='Li')) I then check the relation was successful with: Occurrence.objects.get(ind='1010106').minmat.all() which returns a queryset of all the relations. I have dropped the database and after a fresh migrations everything worked as it should, but once I reloaded the data which consists of tables up to 150,000 rows, I am no longer able to create these relations. No errors occur, but no additions are mad to the model instance after running add(). Here is the model: class Occurrence(models.Model): ind = models.CharField(max_length=14, blank=False, null=False, primary_key=True) majmat = models.ManyToManyField(Material, related_name="majmat_occurrence", blank=True,) geom = models.PointField(srid=4202) def __str__(self): return self.ind class Material(models.Model): code = models.CharField(max_length=6, primary_key=True) name = models.CharField(max_length=50, blank=False, null=False) category = models.ManyToManyField(MaterialCategory, related_name="category_material", blank=True) def natural_key(self): return self.name Everything works properly before loading the data, so I assume the issue lies with loading the data outside of django, but … -
How to access html's <span> into {{ variable accessor }}
I am Building a BlogApp and I am stuck on an Error. What i am trying to do I am trying to access <div>Place: <span id="place"></span></div> into {{ place }} or {% if place %} The Problem It is not accessing when i insert it in {{ place}} I don't know what to do. Any help would be Appreciated. Thank You in Advance -
Django model admin custom get_queryset pagination is not working
In my django code i am displaying user list with custom queryset: class UserAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(UserAdmin, self).get_queryset(request) qs.filter(is_staff=0,is_superuser=0) paginator = Paginator(qs, 5) qs = paginator.get_page(1) return qs i dont know what is getting wrong here but it is returning me the error like . KeyError: 'request' but when i remove the paginator from there it is working fine. here i want to use client side datatable pagimation for my user list .can anyone have any idea why i am getting this -
How can I update sqlite database in django without original migration files and preserve the data in db.sqlite3 at the same time?
I am a beginner in django. I accidentally deleted the original migration files and the only remaining related file is db.sqlite3. Now I made some changes to models.py and want to update my database while preserving the previous data in db.sqlite3. How can I do this? Will python manage.py makemigrations work? -
Django Project OperationalError at /admin/products/product/add/
So when I am trying to add a product and click save on the browser I get this error message. I don't know what to do, and have tried looking for solutions. I attached the error image to this link -
Django wont import pages app to urls file
While I was following this tutorial https://www.youtube.com/watch?v=F5mRW0jo-U4&t=3838s I was trying to customize the home page of my django project by creating a new project called pages by doing python manage.py startapp pages the only edit I made to this app was in the view.py file by doing this But whenever I try to reference this file in the urls.py file in the trdjango folder it gives me an import error like this This is really frustrating because I am new to this web framework and I was following the tutorial exactly and yet I still get this error Does anyone know why it isn't recognizing the import or how I would fix this? -
Django - don't post that specific form if left blank
I am building on the learning django tutorial (relatively new to both python and django), with a page where a user can create a question and some optional polls for users to vote on. I have a standard 4 options for choices, right now they are each a separate 'form' that will submit that choice to the question. Only issue is I would like to make it so if that specific one is left blank, the others will be submitted but that one will not. Right now when I try and leave it blank it says it is a required field and I am unable to submit. Is there any way around this? I have tried to change put before validation that the field is not required, but since I cannot submit, it does not hit that logic. The way the form is laid out right now has multiple forms inside, one for the question and 4 for choices, and all are wrapped within one form in the html. -
ImportError: No module named social_django.middleware.in import_module __import__(name)
Hello I am trying to execute a project that is made in django 1.10.8 and pyhon 2.7 and the python_social_auth library. When I try to execute the project I get the following error.I hope you can help me manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7f4b908eb488> Traceback (most recent call last): File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 39, in inner_run http_consumer=self.get_consumer(*args, **options), File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 134, in get_consumer return StaticFilesConsumer() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 327, in __init__ self.handler = self.handler_class() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/staticfiles.py", line 18, in __init__ super(StaticFilesHandler, self).__init__() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 177, in __init__ self.load_middleware() File "/home/mauricio/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named social_django.middleware -
Django-filter fields to select
my code: import django_filters from django_filters.views import FilterView User = get_user_model() class supplierFilter(django_filters.FilterSet): class Meta: model = Supplier fields = ['supplier_name', ] class SupplierFilterList(FilterView): template_name = "supplier/Supplier_list.html" model = Supplier context_object_name = 'supplier' filter_class = supplierFilter def get_queryset(self): organisation = self.request.user.userprofile.company return Supplier.objects.filter(organisation=organisation) my template: <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> I just want to have a filter on name but my template looks like this: So I have all fields of my model and not only name -
Environment Variables Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
During the last couple days I have been trying to use environment variables in django but it just seems impossible. I made my .env file and put it in my project directory with all the variables. When I run the server it says that my secret key is not defined even though I am loading my environment variables. I do not know what I am doing wrong in this project because this approach work just fine in another one i made. If someone can find the error I would really appreciate it a lot. settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import django_heroku from pathlib import Path import os import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent dotenv_file = os.path.join(BASE_DIR, "env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Joining multiple models in order to get an orm query in Django?
I have to return the average length of the most sold tracks in a certain time, using 3 models i manage to form an sql query that looks something like this select *, AVG(m.milliseconds) as lengthTrack from InvoiceItem as il join invoices as i on i.invoiceid = il.invoiceid join track as t on t.trackid = il.trackid where i.invoicedate between '2012-01-01' and '2013-12-31' order by lengthTrack I manage to come up with this as I got really confused about how to join both tables in order to get the average length track of the 10 most sold ones : start_date = datetime.date(2012, 01, 01) end_date=datetime.date(2013, 12, 31) InvoiceItem .objects.filter(ino_date__range=(start_date, end_date),) in the views do i need to add the 3 serializers in erializer_class? i also wanna ask if my query right ? -
Cant complete a complex query in Django
I have this two tables: class HotelInfo(models.Model): country_area = models.CharField(max_length=45) hotel_id = models.CharField(primary_key=True, max_length=32) hotel_name = models.TextField(blank=True, null=True) hotel_url = models.TextField(blank=True, null=True) hotel_address = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_qty = models.IntegerField(blank=True, null=True) clean = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) comf = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) loct = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) fclt = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) staff = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) vfm = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) wifi = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'hotel_info' unique_together = (('hotel_id', 'country_area'),) verbose_name_plural = "hotels" class HotelReviews(models.Model): uuid = models.CharField(primary_key=True, db_column='UUID', max_length=36, blank=True) hotel = models.ForeignKey(HotelInfo, on_delete=models.DO_NOTHING) review_title = models.TextField(blank=True, null=True) review_url = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_date = models.DateField(blank=True, null=True) reviewer_name = models.TextField(blank=True, null=True) hash_reviewer_name = models.CharField(max_length=200, blank=True, null=True) reviewer_location = models.CharField(max_length=100, blank=True, null=True) posting_conts = models.IntegerField(blank=True, null=True) positive_content = models.TextField(blank=True, null=True) negative_content = models.TextField(blank=True, null=True) tag_n1 = models.TextField(blank=True, null=True) tag_n2 = models.TextField(blank=True, null=True) tag_n3 = models.TextField(blank=True, null=True) tag_n4 = models.TextField(blank=True, null=True) tag_n5 = models.TextField(blank=True, null=True) staydate = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'hotel_reviews' verbose_name_plural = "Reviews" And I want get the hotels with more than 5 reviews_qty in 2019 and then get … -
How to use Django form-wizard on a model using ModelForms?
How to use django-formtools Form wizard on a model using ModelForms? My forms are rendering but the data is not being saved for some reason, and the form is therefore invalid so never reaches done method. I've never used Form wizard before and finding it hard to find much in terms of documentation or tutorials. models.py [abbreviated for simplicity] class Applicant(models.Model): first_name = models.CharField(max_length=150, null=False, blank=False) last_name = models.CharField(max_length=150, null=False, blank=False) phone = models.CharField(validators=[phone_regex], max_length=60, null=True, blank=True) email = models.EmailField(blank=False, null=True) .... forms.py [abbreviated for simplicity] class ApplicationStepOne(ModelForm): class Meta: model = Applicant fields = ('first_name', 'last_name', 'phone', 'email', ...,) class ApplicationStepTwo(ModelForm): class Meta: model = Applicant fields = ('age', ...,) class ApplicationStepThree(ModelForm): class Meta: model = Applicant fields = ('cats', 'dogs', ...,) class ApplicationStepFour(ModelForm): class Meta: model = Applicant fields = ('yard', ...,) views.py class FormWizardView(SessionWizardView): template_name = 'animals/application_form.html' model = Applicant form_list = [ApplicationStepOne, ApplicationStepTwo, ApplicationStepThree, ApplicationStepFour] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) success_url = reverse_lazy('animals:animals') def dispatch(self, request, *args, **kwargs): self.instance = Applicant() return super(FormWizardView, self).dispatch(request, *args, **kwargs) def get_form_instance( self, step ): if self.instance is None: self.instance = Applicant() return self.instance def done( self, form_list, **kwargs ): self.instance.save() for form in form_list: form.cleaned_data() return redirect(self.success_url) urls.py path('apptest/', FormWizardView.as_view([ApplicationStepOne, … -
Django wsgiref/handlers.py throws exception like always with python 3.9
I'm doing some django TDD samples following this article http://www.tdd-django-tutorial.com/tutorial/1/. But when I try to run my testing I always got this problem, $ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 12, 2021 - 16:58:38 Django version 2.1, using settings 'web_app.settings.develop' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [12/Mar/2021 16:58:40] "GET / HTTP/1.1" 200 1587 Traceback (most recent call last): File "c:\users\aleja\appdata\local\programs\python\python39\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 66, in __call__ return super().__call__(environ, start_response) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\core\handlers\wsgi.py", line 142, in __call__ response = self.get_response(request) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 58, in get_response return self.serve(request) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 51, in serve return serve(request, self.file_path(request.path), insecure=True) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\views.py", line 33, in serve absolute_path = finders.find(normalized_path) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 263, in find result = finder.find(path, all=all) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 98, in find matched_path = self.find_location(root, path, prefix) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 115, in find_location path = safe_join(root, path) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\utils\_os.py", line 47, in safe_join raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (C:\favicon.ico) is located outside of the base path component (C:\Users\aleja\Documents\Projects\th-web-app\static) [12/Mar/2021 16:58:41] "GET /static//favicon.ico HTTP/1.1" 500 59 [12/Mar/2021 16:58:43] "GET /static/develop/35e6fb86d66a830d45e377494420c11b.woff2 HTTP/1.1" 304 0 -
"no such column: id" Django AbstractUser model
I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this: "django.db.utils.OperationalError: no such column: social_app_user.id" And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password" I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless. Please help, thanks! Note: the 'id' field in this models.py file was added after i got the error. from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class User(AbstractUser): is_verified = models.BooleanField(default=True) id= models.AutoField(primary_key=True, null=False) REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): f"{self.username} {self.email}" return class main_feed(models.Model): content= models.CharField(unique=True, max_length=255, default='', null=False) poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username') likes = models.IntegerField(default=0, null=False) favorites = models.IntegerField(default=0, null=False) date_posted = models.DateTimeField(auto_now=True) def __str__(self): f"{self.content} {self.likes} {self.poster} {self.date_posted}" return -
How I'll fix it - NameError at /account/signup/ name 'SignUpForm' is not defined
I defined SignUpFrom but still, the server shows that name 'SignUpForm' is not defined by anyone, please suggest to me how I'll fix it. Thanks in advance. Code Location: App_Login Views.py views.py--App_Loginstrong text [from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, authenticate, logout from django.shortcuts import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. def sign_up(request): form = SignUpForm() registered = False if request.method == 'POST': form = SignUpForm(data=request.POST) if form.is_valid(): form.save() registered = True dict = {'form':form, 'registered':registered} return render(request, 'App_Login/signup.html', context=dict) def login_page(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('index')) return render(request, 'App_Login/login.html', context={'form':form}) @login_required def logout_user(request): logout(request) return HttpResponseRedirect(reverse('index')) -
Django: database for admin purposes on local db.sqllight and app requests made on another database (PostgrSQL)
I am new to Django. I would like to have the admin part being managed by a local db.sqlight database and the app/web requests being made to another database (PostgreSQL). Do I need to create a Router class, in which folder (project or app). I went through the Django documentation/ tutorials but it was still unclear to me as of how to implement this. An example with directories/folders paths and settings.py values would be greatly apreaciated. Best Django3, Windowas, PyCharm community, PostgreSQL 12 -
Create object if doesn't exist when calling it by related_name
NOTE: I'm aware of get_or_create and it does not apply here. I have a Django app with a lot of users. One of my project apps must keep some kind of user preferences relating to this app, so in its' models.py I've created: [models.py] class UserPreferences(models.Model): user = models.ForeignKey( get_user_model(), related_name='adminpanel_preferences' ) ... (more boolean fields, integer choices etc) I don't want to use signals for creating a UserPreferences objects every time new user is being created. My idea was to only create an object when such object is somehow requested. This might sound like a perfect get_or_create use case, however I need to call this object from a template using the related_name e.g: [template.html] {% if request.user.adminpanel_preferences.hardcore_mode_enabled %} ... {% endif %} And while normally the request.user.adminpanel_preferences would return UserPreferences.None, I want it to silently create the object (using default field values) instead. Is there a possibility to achieve such behavior without interfering the User model? The UserPreferences are not global app preferences, they only refer to this particular app and I'd love to keep these two independent. I have also tried using a custom objects manager with customized get_queryset method but it doesn't seem to work when using …