Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django Postgres CREATE postgres schema on database. Multitenancy
the docs are not clear. Is it possible to create a schema system on postgres database in order to use postgres schemas as isolated data collection for a multi-tenant app directed by a sub-domain request. -
Page not found (404) The current path, media/15611349.jpg, didn’t match any of these
I cannot understand what my error is. I have a django project. In order to set up my media url, I followed the django doc Django doc - Managing static files and static media. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// IMAGE LINK RESULT DIR product_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Product Image: <img src="{{products.image.url}}"> </body> </html> shop/urls.py from django.urls import path from .views import shop_home, ProductDetailView urlpatterns = [ path('', shop_home, name='shop_home'), path('products/<str:ct_model>/<str:slug>/', ProductDetailView.as_view(), name='product_detail') ] shop/views.py from django.shortcuts import render from django.views.generic import DetailView from .models import CPU, Smartphone def shop_home(request): return render(request, 'shop/index.html') class ProductDetailView(DetailView): CT_MODEL_MODEL_CLASS = { 'cpu': CPU, 'smartphone': Smartphone } def dispatch(self, request, *args, **kwargs): self.model = self.CT_MODEL_MODEL_CLASS[kwargs['ct_model']] self.queryset = self.model._base_manager.all() return super().dispatch(request, *args, **kwargs) context_object_name = 'products' template_name = 'shop/product_detail.html' slug_url_kwarg = 'slug' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('shop/', include('shop.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_dev') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Using RSA private key for decrypt data in Web Application
I am developing a web application that can help people encrypt data. The idea is to use different RSA encryption pairs for different user groups. But I want to hide both public key and private key like on password manager software. I mean, like users in a certain group will only receive encrypted pairs as *****/*******. Even users cannot see private pass strings. I read they can use USB token or PKI. But i dont know how can it connect to web app (django). Anyone have idea???? Thank -
Django Rest Framework and django rest framework simplejwt two factor authentication
I am using django version 3.2.4 in combination with Django Rest Framework. I also use https://github.com/jazzband/djangorestframework-simplejwt for JWTs. Problem: I need to enable Two Factor Authentication in the following way. User uses an endpoint that he submits his username & password. He receives back a jwt token that includes in a claim the verification code he needs to enter hashed. At the same time an email with this code goes to his email. Once the user receives the email he posts in another enpoint the verification code received and the jwt token he received in the previous step. If the code the user submitted matches the hashed code then he obtains the jwt token that it will be used in the subsequent requests. P.S. Any other ideas, that achieve something similar with the above are welcomed. -
DRF: Image page not found
I want to add ImageField to my module and follow the instruction Serializer returns http://127.0.0.1:8000/media/images/lkdj/unnamed.jpg but the link doesn't work (Page not found) How can I receive a valid link? Added MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # 'http://myhost:port/media/' models.py def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=name_image, blank=True, null=True) views.py class ConstructionView(viewsets.ModelViewSet): serializer_class = ConstructionSerializer queryset = Construction.objects.all() pagination_class = ConstructionSetPagination def get_construction_create_serializer(self, *args, **kwargs): serializer_class = ConstructionSerializer kwargs["context"] = self.get_serializer_context() return serializer_class(*args, **kwargs) def create(self, request, *args, **kwargs): serializer = self.get_construction_create_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) response = {"result": serializer.data} return Response( response, status=status.HTTP_201_CREATED, headers=headers) serializer.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = PointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() class Meta: model = Construction fields = ( 'id', 'developer', 'name', 'image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance -
Queries related to Django Signals
To begin with, Here Profile and Seller model is created when a User model is created through Signals.What I want to do is When profile model is first created or updated,I want all the fields of Seller model to be same as all fields of Profile.Similarly when I first created Seller model,I also want all fields of Profile Model to be same as that of Seller model.But,I couldn't figure out how to do? from typing import Tuple from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.db.models.fields import DecimalField from django.dispatch import receiver from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) #cascade is for deleting the customer first_name = models.CharField(max_length=10, null=True) second_name=models.CharField(max_length=10,null=True) email = models.EmailField(max_length=70, null=True,blank=True) @receiver(post_save, sender=User) def create_profile(sender, instance,created,**kwargs):#Signal receivers must accept keyword arguments (**kwargs). if created: Profile.objects.create(user=instance) ... @receiver(post_save, sender=Profile) def create_seller(sender, instance,created,**kwargs):#Signal receivers must accept keyword arguments (**kwargs). if created: Seller.objects.create(user=instance) class Seller(models.Model): user = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True, blank=True) #cascade is for deleting the customer first_name = models.CharField(max_length=10, null=True) second_name=models.CharField(max_length=10,null=True) email = models.EmailField(max_length=70, null=True,blank=True) ... -
How to use one Jquery function to handle multiple onchange (HTML) events
I have multiple item name drop-down fields along with price fields. When item is selected corresponding price should be updated in price field. -----HTML----- <tbody> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem1" class="form-control" onchange="myFunction(event)"> <option selected disabled="True">--- select --- </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control" style="color:gray" font-size="20">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-2"> <div class="form-group"> <input id="myText1" type="text" class="form-control price" value=" " name="price"> </div> </td> <tr class="d-flex"> <td class="col-sm-5"> <div class="form-outline"> <select id="selectitem2" class="form-control" onchange="myFunction(event)"> <option selected disabled="True">--- select --- </option> {% for item in showdrop %} <option value="{{item.item_price}}" class="form-control" style="color:gray" font-size="20">{{item.item_name}}</option> {% endfor %} </select> </div> </td> <td class="col-sm-2"> <div class="form-group"> <input id="myText2" type="text" class="form-control price" value=" " name="price"> </div> </td> </tbody> ---- function----- function myFunction(e) { document.getElementById("myText1").value = e.target.value } -
is there any way to make my dynamic django webpage as realtime webpage
please any suggest me anything how to make my django website as realtime website. i my case iam doing a auction site so i need to make the products soldout=True automatically when the period of the time ends for a particular product -
How to register users in Django while maintaining frontend bootstrap template?
I am trying to register users for a multi user complaint management system using django. The frontend is already ready and I just have to do the backend. I am fairly new at django and this is my first project so I'm very confused in how to maintain the bootstrap view while being able to register users and authenticate them. The bootstrap template is: ```<div class="col-lg-4 login-bg"> <h4 class="reg-title"><strong>Get Started...</strong></h4> <p class="login-reg">Already have an account? <a class="log-reg-link" href="login.html">Log In </a> here</p> <hr> <form class="" action="/Dashboard/" method="post"> <p class="reg-field-title"><strong>First Name*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="First Name" required> <p class="reg-field-title"><strong>Last Name*</strong></p> <input type="text" class="form-control col-lg-10 log-inp-field" placeholder="Last Name" required> <p class="reg-field-title"><strong>Email ID*</strong></p> <input type="email" class="form-control col-lg-10 log-inp-field" placeholder="Enter email" required> <p class="reg-field-title"><strong>Password*</strong></p> <input type="password" class="form-control col-lg-10 log-inp-field" placeholder="Enter Password" required> <button type="submit" class="btn btn-dark btn-lg col-lg-10 reg-btn">Register</button> </form>``` this is my accounts model: ```from django.db import models class Person(models.Model): first_name = models.CharField(max_length=130) last_name = models.CharField(max_length=130) email = models.EmailField(blank=True) Password = models.CharField() I don't understand what to do? What to put in the views and the forms? -
Is this a problem Deploying Heroku before working in AWS?
I've deployed my site on Heroku with no problems. After that, I've uploaded my static and media folder to AWS and i get this error: raise ImproperlyConfigured("Could not load Boto3's S3 bindings. %s" % e) django.core.exceptions.ImproperlyConfigured: Could not load Boto3's S3 bindings. No module named 'boto3' I've installed everything, I've done pip freeze < requirements.text. Please help me. -
How can i add multiple address in django?
I am trying to add multiple addresses but only 1 address is getting created This is models.py class Customer(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) name = models.CharField(max_length = 100) locality = models.CharField(max_length = 200) city = models.CharField(max_length = 50) zipcode = models.IntegerField() state = models.CharField(choices = STATE_CHOICES, max_length=50) This is views.py def address(request): add = Customer.objects.filter(user=request.user) return render(request, 'app/address.html', {'add':add}) This is address.py {% for ad in add %} <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h3>Address {{forloop.counter}}</h3> <p>Name: {{ad.name}}</p> <p>Locality: {{ad.locality}}</p> <p>City: {{ad.city}}</p> <p>Pin Code: {{ad.zipcode}}</p> <p>State: {{ad.state}}</p> </div> </div> </div> {% endfor %} -
Parent directory symbol not working in html
<meta charset="utf-8"> <title>Exam Page</title> <link rel="stylesheet" href="../../../static/css/teststyle.css"> </head> Im using this code in exam folder and i wanted to go to parent directory so i used ../../ but it is showing the below error Not Found: /exam/static/css/teststyle.css -
automatically creating a PDF file from pytesseract in django
I m creating an OCR mobile application with django on backend, so i created two seperate applications: 1 for the image processing and another for prefroming the OCR, i want for my app to automatically create an PDF file once an image is added on my Image model however i m getting this error 'bytes' object has no attribute '_committed'. This is my Image model from tesseract.models import File from tesseract.ocrImage import Create_Pdf from django.db import models import uuid import pytesseract import PIL.Image import cv2 # Create your models here. class Image(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=50) image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if self.id : File.objects.create( file=Create_Pdf(self.image)) def __str__(self): return str(self.id) and this is my File model: class File(models.Model): label=models.CharField(max_length=50, default='none') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) This is my OCR use case: import io import PIL.Image import pytesseract #from reportlab.pdfgen import canvas pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): buffer = io.BytesIO() doc=pytesseract.image_to_pdf_or_hocr(PIL.Image.open(image)) return doc and this is my error: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper … -
Generate Dynamic Links in Django : Company and Employee
I am making a project in Django which is an Employee Management System. I made the Company Home page where we have options to add a new Company, Delete Previous Company or Delete it. Now I want when I click on that Company Name, it generates a dynamic link for that particular company name (which will have the same features of adding, deleting and editing the Employee) Currently, I am stuck. Not able to generate Dynamic links for each Company which gives Employee details. Here is my Models.py File from datetime import date, datetime from django.db import models from django.db.models.fields.related import ForeignKey from django.utils import timezone # Create your models here. class companyModel(models.Model): company_name = models.CharField(max_length=100,blank=False) company_created = models.DateField(default=datetime.now,blank=False) class employeeModel(models.Model): employee_company_name = models.ForeignKey(companyModel,on_delete=models.CASCADE) employee_name = models.CharField(max_length=100,blank=False) employee_created = models.DateField(default=datetime.now,blank=False) Forms.py File from django import forms from django.forms import widgets from empman.models import companyModel,employeeModel class companyForm(forms.ModelForm): class Meta: model = companyModel fields = ['company_name','company_created'] widgets = { 'company_name' : forms.TextInput(attrs={'class':'form-control '}), 'company_created':forms.TextInput(attrs={'class':'form-control'}) } class employeeForm(forms.ModelForm): class Meta: model = employeeModel fields = ['employee_company_name','employee_name','employee_created'] Views.py File from django import forms from django.shortcuts import render,HttpResponsePermanentRedirect from empman.forms import companyForm,employeeForm from empman.models import companyModel,employeeModel # Create your views here. def companyShowView(request): if request.method … -
matching query does not exist, DoesNotExists
Tell me how to do that in the absence of an object in the database, not an exception "DoesNotExists" would be displayed, but that my error text would be displayed. def get_queryset(self): try: city_name = self.request.GET.get('name') return City.objects.get(name__iexact=city_name) except DoesNotExist: return HttpResponse('Not found') Doesn't help, if there is no object, just a blank page. -
Ajax Django add button not adding on first click
So I have a dynamically rendered table in Django, the items in the table represent the order items so for each order item I have added to cart, it will show in the table on my Cart page. Now I have a quantity, a product name, order item total and so on. Now I'm using two buttons, add and subtract. Here's a code so that you can get the idea. <tbody> {% for order in orders %} <tr> <th scope="row"> <div class="order-quantity"> <span class="order_quantity">{{order.quantity}}</span> <button data-url="{% url 'add' order.id %}" class="edit-quantity plus" id="plus">+</button> <button data-url="{% url 'subtract' order.id %}" class="edit-quantity subtract" id="subtract">-</button> </div> </th> <td><img src="{{order.item.product_image.url}}" alt="" width="70" height="70"></td> <td>{{order.item.product_name}}</td> <td> <span>&#8369;</span> {{order.total_item_price}}</td> </tr> {% endfor %} </tbody> </table> Now notice that I have two buttons, each with a data url so that Jquery can make AJAX calls for me to a specified url in Django. Everything is working fine but when I click the add button, on my logs it shows that the item is not yet changed but rather just printed out. But when I click for the second time, the action just takes place, but not during the first click. How to solve this? Here's an example. … -
How to save JSON array data in POSTGRESQL database using DJANGO python?
How to save JSON array data in POSTGRESQL database table using Python Django API? I am getting belowJSON array data from JAVASCRIPT API call in the body of the http request which I want to save in POSTGRESQL database table. #JSON ARRAY DATA [ { "id": 16, "todoItem": "shopping", "checked": false, "todoitemid": "1", "Date": "26/06/2021" }, { "id": 17, "todoItem": "grocery", "checked": false, "todoitemid": "14646", "Date": "26/06/2021" }, { "id": 18, "todoItem": "dropoff", "checked": false, "todoitemid": "1467", "Date": "26/06/2021" }, { "id": 19, "todoItem": "movie", "checked": false, "todoitemid": "297", "Date": "26/06/2021" } ... ... ... ... ] #Model class Todo(models.Model): todoItem=models.CharField(max_length=100,blank=False,default='') checked=models.BooleanField(default=False) todoitemid=models.CharField(max_length=20 , blank=False,default='') Date=models.CharField(max_length=20 , blank=False,default='') #serializer class todoserializer( serializers.ModelSerializer): class Meta: model= Todo fields=('id', 'todoItem', 'checked', 'todoitemid', 'Date' ) #Views.py @api_view(['POST']) def todo_list(request): request.method == 'POST': todo_data = JSONParser().parse(request) todo_serializer =todoserializer(data=todo_data) if todo_serializer.is_valid(): todo_serializer.save() return JsonResponse(todo_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(todo_serializer.errors, status=status.HTTP_400_BAD_REQUEST) what am I making wrong ? OR How do I Iterate through parsed JSON Array Data from request? -
hi, I have a problem with how I can show errors in the template like username is already taken? please, help me
how i can show errors like email or username is alerdy taken in this page Aaccounts/sign-up.html because when try to to put a username and this username is already taken the page only refrech without any message before enter image description here after enter image description here class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'Aaccounts/sign-up.html' def login (request) : if request.method=='POST': passwordtest=request.POST ['password'] usernametest=request.POST ['username'] user=auth.authenticate(username=usernametest,password=passwordtest) if user is not None : auth.login(request,user) current_user = request.user correctUSER = get_object_or_404(CustomUser, pk=current_user.id) need_to_cheack=correctUSER.main_affilitee kain=False if need_to_cheack !="": objs=CustomUser.objects.all() for aleratwar in objs: if kain==False: if aleratwar.username==need_to_cheack and aleratwar.afilliteuser==True and aleratwar.username !=correctUSER.username : kain=True if kain== False: correctUSER.main_affilitee='' correctUSER.save() return redirect('home') else: return render(request,'Aaccounts/login.html',{'eroor':True}) else: return render(request,'Aaccounts/login.html') -
django accoubts/login overwrite
path('accounts/login/', auth_views.LoginView.as_view(template_name ='users/registration /login.html')), I using this path for login and this is working but I want to show authentication error in login page i use this html code for this purpose <small class="message" style="color: red;">{{form.non_field_errors}}</small> <small class="message" style="color: red;">{{form.errors}}</small> <form class="form" id="signin-form" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Login" class="btn btn-block btn-secondary"> But I just show fields error if any fields will be empty but not show authentication error if I enter wrong password or email this screen will be show as a error How I overwrite accounts/login path Also when I logedin my session and I re enter login path login page will be appear, I want handle also this bug with accounts/login I write my own function for this purpose but my clients require that no write extra function and just use accounts/login url. -
django factory boy couldn't import
I've created directory cheeses(myapp)/test/factories.py with code from django.template.defaultfilters import slugify import factory import factory.fuzzy from ..models import Cheese class CheeseFactory(factory.django.DjangoModelFactory): name = factory.fuzzy.FuzzyText() slug = factory.LazyAttribute(lambda obj: slugify(obj.name)) description = factory.Faker('paragraph', nb_sentences=3, variable_nb_sentences=True) firmness = factory.fuzzy.FuzzyChoice( [x[0] for x in Cheese.Firmness.choices] ) class Meta: model = Cheese then in shel_plus i typed this from cheeses.tests.factories.py import CheeseFactory and got ModuleNotFoundError: No module named 'cheeses.tests.factories'; 'cheeses.tests' is not a package. What have i done wrong? -
How to handle MethodNotallowed exception in django rest framework by creating seperate file for exceptions
In my Django RestApi project I want to apply Exceptions errors. I create a separate file (common.py) for all my exceptions file is located out side the project where our manage.py file located. this is in my file: HTTP_VERB_STRING = { 'get': 'get', 'post': 'post', 'put': 'put', 'patch': 'patch', 'delete': 'delete', } Also I set it in settings.py: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', Now In my view I create a modelviewset. In modelviewset we get all built in functions to perform oprations like (put, patch, delete, create, update) but in this view I don't need put, patch, and delete. So I want to block this and want to give exception on it I tried this : from rest_framework import viewsets from common_strings import HTTP_VERB_STRING class MeterReadingModelViewSet(viewsets.ModelViewSet): queryset = MeterReadingModel.objects.all() serializer_class = MeterReadingModelSerializer def update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['put']) def partial_update(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['patch']) def destroy(self, request, pk=None): raise MethodNotAllowed(method=HTTP_VERB_STRING['delete']) But giving error on MethodNotAllowed is not defined. Why this is happenning? -
ManyToManyField value in Django REST Framework
So when I am routing to api/ to view my models I am not seeing what I expected to see. I wanted to see the names of the strats that I grouped in Strat_Basket model in the variable basket but instead I see their ids which is generated by DJANGO automatically. I want to see the names rather than numbers in the strat_basket view. It is more informative that's why. models.py class Strats(models.Model): name = models.CharField(max_length=64) class Strats_Basket(models.Model): name = models.CharField(max_length=64) basket = models.ManyToManyField(Strats, blank=True, related_name='list') serializers.py: class StratsSerializer(serializers.ModelSerializer): class Meta: model = Strats fields = ('id', 'name') class Strats_BasketSerializer(serializers.ModelSerializer): class Meta: model = Strats_Basket fields = ('id', 'name', 'basket') views.py: class StratsView(viewsets.ModelViewSet): serializer_class = StratsSerializer queryset = Strats.objects.all() class Strats_BasketView(viewsets.ModelViewSet): serializer_class = Strats_BasketSerializer queryset = Strats_Basket.objects.all() urls.py: router = routers.DefaultRouter() router.register(r'strats', views.StratsView, 'strats') router.register(r'strats_basket', views.Strats_BasketView, 'strats_basket') API OUTPUT: strats: [ { "id": 1, "name": "strat1" }, { "id": 2, "name": "strat2" }, { "id": 3, "name": "strat3" }, { "id": 4, "name": "strat4" }, { "id": 5, "name": "strat5" }, { "id": 6, "name": "strat6" } ] strats_basket: Instead of 1,2,4 I want to see strat1, strat2, strat4. [ { "id": 1, "name": "Basket 1", "basket": [ 1, 2, … -
How to convert datetime like `2021-06-25 15:00:08+00:00` to local timezone datetime.datetime python?
I have many datetime.datetime object like 2021-06-25 15:00:08+00:00 where the timezone is different for different data.Eg.another data is 2021-06-24 06:33:06-07:00 .I want to save all of them by converting into a local tmezone.How can I do that? -
Django 'ManyToManyDescriptor' object has no attribute 'count'
I am writing an application where users can add events and other users can add likes to them. I'm stuck at the point where Django needs to sum up all likes for all posts. Based on similar answers, I tried the code below for one event: views.py @login_required(login_url='/oauth2/login') def Events(request, *args): ... likes = EventModel.likes.count() return render(request, 'base/events.html', {..., 'likes': likes}) models.py class EventModel(models.Model): ... likes = models.ManyToManyField(User, related_name='event_likes') But when I refresh it returns an error 'ManyToManyDescriptor' object has no attribute 'count' How can I count all likes for all posts? I think it is too naive to execute loops and write them all in, for example, a dictionary. Here is how the site looks like. I am happy to provide more details regarding my problem. -
Django Setting for Default Related Name Pattern
The Django documentation: Models page mentions that the default related_name for foreign keys uses the pattern f"{ModelClass.__name__.lower()}_set" (or childb_set in the specific example). Is there a way to configure Django to convert CapWords to cap_words (instead of capwords) when creating these default related_names? For example, take the following models: from django.db import models class BlogChannel(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class ArticleAuthor(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class TextEntry(models.Model): blog_channel = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() article_authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline Accessing BlogChannel records through TextEntry is intuitive: >>> text_entry = TextEntry.objects.first() >>> blog_channel = text_entry.blog_channel But the reverse is not: >>> blog_channel.text_entry_set # should be `blog_channel.textentry_set` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-19-0402bfca7d1f> in <module> ----> 1 blog_channel.text_entry_set AttributeError: 'BlogChannel' object has no attribute 'text_entry_set' Rather than modifying every foreign key field of every model to specify a related_name that uses underscores, I'm curious if there is a setting or something to effect this style change.