Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter on multiple GET parameters
I have a search field and two extra search parameters (category and platform) on the side of the results on my search page. my queryset looks like this on the list view: def get_queryset(self): query = self.request.GET.get('q') category = self.request.GET.get('category') platform = self.request.GET.get('platform') text_query = ( Q(name__icontains=query) | Q(category__name__icontains=query) | Q(tags__name__icontains=query) ) object_list = Results.objects.all() if query: object_list = object_list.filter( text_query ) if category: object_list = object_list.filter(Q(category__name=category)) if platform: if platform == "windows": object_list = object_list.select_related('versions').latest().filter(windows=True) elif platform == "linux": object_list = object_list.select_related('versions').latest().filter(linux=True) elif platform == "mac": object_list = object_list.select_related('versions').latest().filter(mac=True) return object_list I know the last part can be one line with exec, but this does not work because you cant filter the result of a filter (object_list). What is the best way to filter based on multiple GET parameters? -
user.is_authorised returns false in particular django template
username is showing up in all templates except one template. What is missing there? user.is_authorised returns false in one particular template. -
Galler images very big in size using html
Is there a way to make these images smaller? and fit into a box? I followed according to a tutorial and images are bigger.This is zoomed out to 25% view. I'm looking for a way to resize the images to fit into the gallery like view, in the tutorial, the person ended up with a perfect gallery type output unlike me xd .This is for a django project and thanks in advance :) This is normal zoomed out view html code: {% extends 'portofolio/base.html' %} {% load static %} {% block content %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.8.2/css/lightbox.min.css"> <link rel="stylesheet" href="{% static "portofolio/css/photogallery.css" %}"> <body> <h1 style="margin-top: 70px;">Image Gallery</h1> <div id="jLightroom" class="jlr"> <a href="{% static "portofolio/images/1.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/1.jpg" %}"> </a> <a href="{% static "portofolio/images/2.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/2.jpg" %}"> </a> <a href="{% static "portofolio/images/3.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/3.jpg" %}"> </a> <a href="{% static "portofolio/images/4.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/4.jpg" %}"> </a> <a href="{% static "portofolio/images/5.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/5.jpg" %}"> </a> <a href="{% static "portofolio/images/6.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/6.jpg" %}"> </a> <a href="{% static "portofolio/images/7.jpg" %}" data-lightbox="lb1" class="jlr_item"> … -
Implementing pageviews in Django
I am working on a small a small website and I want to display the total views of every object in the detail view. But sincerely, I don't know how to actualise this. Let me post my models.py and views.py Models.py class Music(models.Model): artist = models.CharField(max_length=300) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) audio_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Music, self).save() def __str__(self): return self.title + ' by ' + self.artist def get_absolute_url(self): return reverse('music:detail', kwargs={'slug': self.slug}) Views.py return Music.objects.order_by('-uploaded_date') def detail(request, slug): latest_posts = Music.objects.order_by('-uploaded_date')[:5] song = get_object_or_404(Music, slug=slug) comments = Comment.objects.filter(post=song) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = song comment.save() return HttpResponseRedirect(song.get_absolute_url()) else: comment_form = CommentForm() context = { 'latest_posts': latest_posts, 'song': song, 'comments': comments, 'comment_form': comment_form, } return render(request, 'music/detail.html', context) -
Does 'list_editable' work with files in the django admin?
I'm trying to get a way to rename my uploaded files in the django admin using list_editable. I tried it but it doesn't seem to be working, since it only shows a 'Save' button below, but nowhere where I can edit my files names. Is this even possible or does it now work with FileFields? I looked on forums but nothing seemed to be similar to what I was trying to do. Thanks in advance! -
Django how to query a nested object
I have a Index model that saves all object IDs/PKs of all my diffrent post models: collectable_post_models = models.Q(app_label='App', model='post_model1') | models.Q(app_label='App', model='post_model2') | models.Q(app_label='App', model='post_model3') class PostCollection(models.Model): id = models.AutoField(primary_key=True, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=collectable_post_models, related_name='collections', related_query_name='collection', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=36, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: unique_together = ('content_type', 'object_id') verbose_name = "Post Collection - HELPER TABLE" verbose_name_plural = "Post Collections - HELPER TABLE" ordering = ['-date_added'] Each of my post models looking very similar e.g.: class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=40) collection = GenericRelation(PostCollection, related_query_name='post') Now I have a view that should generate a list of proposals the user may also like to see: def post_proposals(): post_elements = sorted( chain( PostCollection.objects.values_list('id', flat=True), ) ) post_elements_list = list(post_elements) post_proposals = random.sample(post_elements_list, 1) # 1 is the number of elemets that should get returned return post_proposals At my template I currently just get back the ID value of the PostCollection object but actually I want to get the title of the post element behind the Index object. How do I do that? This is what I do at my template e.g.: {% for … -
Django: cannot connect to web with domain name (but fine with IP address)
for the life of me I cannot figure what is going on with this deployment. I am using EC2, route 53 domain(freshly acquired a domain), nginx and gunicorn with supervisor. similarly to this post How do I deploy Django app to (AWS) domain name?, I can acess the app in the web with the IP address but not with the domain name. it gives the error : 'this site refuse to connect'. But when I ping the website with nmap on the port and IP address and also with the domain name i get a positive response. Here are my ALLOWED_HOSTS in settings.py ALLOWED_HOSTS = ['xx.xxx.xx.xx', 'mysite.net', 'www.mysite.net'] nginx django.conf server { listen 80; server_name xx.xxx.xx.xx mysite.net www.mysite.net; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /static { autoindex on; alias /home/ubuntu/exostocksaas/inventory4/collected_static/; } } Really I cannot figure out what is going, could it be that the domain has not propagated yet, but why would it give me such error then? I hope that someone has a clue, I am looking everywhere and I feel like I might up accidently breaking my setup! -
Cannot use pipenv to install django. PermissionError: [Errno 13] Permission denied: 'Pipfile'
Currently trying to install django 2.1 in my command prompt through pipenv command. However there's an error where it says Pipfile access denied. C:\windows\system32>pipenv install django==2.1 Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Scripts\pipenv .exe\__main__.py", line 9, in <module> File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python38-32\Lib\site-packa ges\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\cli\command.py", line 235, in install retcode = do_install( File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\core.py", line 1734, in do_install ensure_project( File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\core.py", line 567, in ensure_project project.touch_pipfile() File "c:\users\lenovo\appdata\local\programs\python\python38-32\lib\site-packa ges\pipenv\project.py", line 677, in touch_pipfile with open("Pipfile", "a"): PermissionError: [Errno 13] Permission denied: 'Pipfile' I'm new. I'm in the process of learning on how to build a website. -
How to return a 404 in case of a queryset is true for Django DetailView
Having a field inside my model class myModel(models.Model): published = models.BooleanField( default=False, help_text="Whether this is visible." ) I'm looking for a way to render a 404-error on corrosponding django.views.generic.DetailView in case of the boolean is False. How can this be achieved? -
3d models path in django using three js
Hi anyone knows about what is the correct way of giving 3d model path in django. Like in which folder i have to put my 3d model. Btw i am using three js. Error Failed to load resource: the server responded with a status of 404 (Not Found) {% load static %} <!DOCTYPE html> <html> <head> <title> 3D Model </title> <link rel="stylesheet" type="text/css" href="{% static 'css/cona.css' %}"> </head> <body> <canvas id="cona"> </canvas> <script src="{% static 'js/three.min.js' %}"></script> <script src="{% static 'js/OrbitControls.js' %}"></script> <script src="{% static 'js/GLTFLoader.js'%}"></script> <script src="{% static 'js/donutCopy.js' %}"></script> <script > var icing="{% static 'INO.glb'%}" </script> </body> </html> </pre> -
Site cannot be reached error while accessing admin page page in Django
I have tried running my Django code it's working fine for all pages except the admin page it takes a long time to run and at last displays message that site cannot be reached. Please help me with this. Note: All other pages like index, about, welcome, home all are working fine. Even sometime admin page comes but most of the time it doesn't -
Range of dates and go through each date at a certain hour
I am trying to iterate through a date range (8/1/19-3/31/20) and go through each date and print a count for hours 4 AM, 5 AM, and 6 AM. However, I'm having some general trouble getting the required dates and iterating. I keep getting various datetime and datetime.timedelta errors. Here is the code: start = datetime.timedelta(2019, 8, 1) end = datetime.timedelta(2020, 3, 31) days = (end - start).days + 1 for i in (start + end for n in range(days)): for j in range(4, 7): print "Hour: ", i print ("Residents: ", Checkin.objects.filter(desk__name="Desk", datetime__hour=i.hour(j)).count()) print("Guests: ", Guest.objects.filter(desk="Desk", datetime__hour=i.hour(j)).count()) I am just hoping for the best way to do this, as I am trying to gather this data for someone. The error I'm getting currently from this code is timedelta doesn't have an hour attribute. I'm just hoping for help getting this code functional. I am filtering Checkin and Guest by their datetime field, which is: datetime = models.DateTimeField(auto_now_add=True) -
Django how to put togheter form, crispy and ajax call
I have an interesting question for you. I have the following form created with a simple html structure: <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required> </div> <button class="btn btn-primary form-control" type="submit">SUBMIT</button> </form> And now I introduce you my javascript code to send the data from front-end to back-end using an ajax call. {% block javascript %} <script> // Create Django Ajax Call $("form#addUser").submit(function() { var nameInput = $('input[name="name"]').val().trim(); var addressInput = $('input[name="address"]').val().trim(); var ageInput = $('input[name="age"]').val().trim(); if (nameInput && addressInput && ageInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_create" %}', data: { 'name': nameInput, 'address': addressInput, 'age': ageInput }, dataType: 'json', success: function (data) { if (data.user) { appendToUsrTable(data.user); } } }); } else { alert("All fields must have a valid value."); } $('form#addUser').trigger("reset"); return false; }); It works perfectly, But now I want to implement it. I want to insert the form not with html code, but with crispy_forms. How can I do it? I tried but the ajax does not work. Could you help me? -
Project structure Django/Plotly/Websocke - display data from DB with Plotly
I'm just getting started with Django, Plotly and SQL so this question is relatively general, but I'm struggling to get my head around the general structure of a project i'm working on. I've set myself a learning task of setting up a page that displays charts of asset prices (Apple stock, Bitcoin etc). I will then build this out to have user accounts and various other functionality. This leads me to a few questions: 1) Should I store the price data etc in the same database as Django is using for the rest of the page or is it best practice to separate these out. I currently have 'default' set to a local postgres db, should i set up a new db for all the asset price data? 2) I currently plan to connect a websocket stream to receive the live price data. Each time a message is received I then write that data to the database. My plotly charts would then update. Is that the most efficient way to do this or is there away to connect the ws directly to the database without the connector? This database will be written to at potentially the same time the page … -
Django dumpdata into docker
I have a docker container where is running a django app. I'm trying to backup my database using cron. The django app is located in /usr/src/app. This is my crontab file:*/1 * * * * cd /usr/src/app && python manage.py dumpdata>dump.json The issue is that the dump.json file is created but nothing is in it. I tried to run directly python manage.py dumpdata>dump.json bash in my container and it actually works (dump.json is filled with my db content). Could you help me please. Thank you. -
How can I serialize django object which was created?
I want to serialize Statuses to get id of them, and finally get response like this: { "status_id: "1", "id": "16", "users": "2" } My View function: def update(self, request, *args, **kwargs): course = TrainingCourse.objects.get(id=self.kwargs['course_id']) users = self.request.data['user'] print(users) users = users.split(',') course.user.set(users) course_statuses = [] for user in users: try: Status.objects.create(course=course, user_id=user)# HERE I CREATED STATUS AND WANT TO SERILIAZED IT except Exception as e: print(e) data = { # 'course_status': course_statuses, "id": self.kwargs['course_id'], "users": self.request.data['user']} return Response(data) -
How to set values for dropdown options and make some calculations in Django?
I'm trying to create an order form for customers, the customer has to choose the quantity and the card_number, based on that, there must be some calculations to get total price (price per card * quantity). How can I set values (price) for each card_number and then do the calculation and store the total price in the database? I'm using Django NOTE: each card_number has a different price. forms.py from django import forms from .models import cardDatabase card_number_choice = { (7239, 7239), (7227, 7227), (7230, 7230), (7217, 7217), (2167, 2167), (7214, 7214), (7233, 7233), (7237, 7237), (7230, 7230), (7229, 7229), (7228, 7228), (3730, 3730), (5660, 5660), (7224, 7224), (7221, 7221), (7241, 7241), (7252, 7252), (5642, 5642), (2680, 2680), (5659, 5659), (2767, 2767), (3718, 3718), (5644, 5644), (5645, 5645), (5646, 5646), (5665, 5665), (5580, 5580), } quantity_choices = { (50, 50), (100, 100), (150, 150), (200, 200), (250, 250), } class cardForm(forms.ModelForm): card_number = forms.IntegerField(help_text="ex: 7643", widget= forms.Select(choices=card_number_choice)) content = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'placeholder': 'What do you want to write on the card!'}), max_length=3000) quantity = forms.IntegerField(help_text="Multiple of 50", widget=forms.Select(choices=quantity_choices)) phone_number = forms.IntegerField(help_text="ex: +966000000000") class Meta: model = cardDatabase fields = ['card_number', 'quantity', 'phone_number', 'content'] views.py from django.shortcuts import render_to_response, redirect, render … -
Django 3 set django_language cookie
In my application the user can store the preferred language. After selecting the language this is stored in the user model an I set the session variables like this: current_user = request.user request.session[translation.LANGUAGE_SESSION_KEY] = current_user.language request.session[settings.LANGUAGE_COOKIE_NAME] = current_user.language But the 'django_language' cookie does not change at all and pages are not translated. I found this doc which tells me exactly the same. Is this still valid for Django3? I also have the middleware 'django.middleware.locale.LocaleMiddleware' set and all messages are compiled. What may be the cause pages are not translated? -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/signup/signup/
This error occurs when click on submit after form filling.I am tring to follow this tutorial but using a bootstrap templates for signup page https://dev.to/coderasha/create-advanced-user-sign-up-view-in-django-step-by-step-k9m views.py from django.shortcuts import render from django.contrib.auth import login, authenticate from .forms import SignUpForm from django.shortcuts import render, redirect def home(request): return render(request, 'home.html') def signup(request): form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) app1/urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('signup/', views.signup, name='signup'), ] signup.html <form role="form" action="signup" method="POST"> {% csrf_token %} forms.html from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ('username','first_name','last_name','email', 'password1', 'password2', ) -
django rest framework how to stop child repetition at the root
i am working with django's nested self referential objects and i have following Category model class CategoryManager(models.Manager): def all(self): qs = super(CategoryManager, self).filter(parent=None) return qs class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True) description = models.TextField(blank=True) # description_json = JSONField(blank=True, default=dict) parent = models.ForeignKey( "self", null=True, blank=True, related_name="sub_category", on_delete=models.CASCADE ) background_image = models.ImageField( upload_to="category-backgrounds", blank=True, null=True ) objects = CategoryManager for recursive representation i applied following serializers class RecursiveSerializer(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) return serializer.data class CategoryListSerializer(ModelSerializer): sub_category = RecursiveSerializer(many=True, read_only=True) class Meta: model = Category fields = ( # 'url', 'name', 'slug', 'description', 'parent', 'background_image', 'sub_category' ) its generate the following result. [ { "name": "Food", "slug": "food", "description": "", "parent": null, "background_image": null, "background_image_alt": "", "sub_category": [ { "name": "Rice", "slug": "rice", "description": "", "parent": 20, "background_image": null, "background_image_alt": "", "sub_category": [] } ] }, { "name": "Rice", "slug": "rice", "description": "", "parent": 20, "background_image": null, "background_image_alt": "", "sub_category": [] } ] Here the parent category Food has a child category Rice which is fine, but the problem is the child category Rice repeating at the root level, how can i stop this. -
django webpack assets too big
I have a Django project which doesn't use anything "fancy" like React or Vue (yet). It just uses the native Django templating system. Until now, I've been using gulp to generate the assets for it but I thought I'd experiment with webpack, as it seems like a good idea for various reasons. However, when I use webpack, it stuffs everything I need for my entire site into a small number of files, which I have to link to on every page of the site. For instance, there is an image I use just for the front page which is managed by webpack. So it goes into the main css file and makes that file very large, considering that image is only needed on one page. There are also a variety of 3rd party JS scripts that get pulled in because they are just here and there, so the main JS file is vast too. I've looked into code splitting a bit and that does give me an extra file for the vendors' stuff but it's still massive and obviously contains tons of stuff that is not used on every page. Am I doing the wrong thing by trying to make … -
Is There a way of returning a queryset of the first instance of a specific field from a django model
Say i have a model called Workout, and its populated as such I want to return a queryset of the first instance of each new date filterd by the current user. In this case, if the current logged in user is user_id = 1, the queryset would contain the workout objects with id 1,4 and 5. Is there a way of achieving this using a Workout.objects... method? Cheers. -
Neither set() nor add() django add to database entry
I have the following problem: I have a manytomanyfield (in model Toppings) and I can't populate it. I first tried using a list and set() and then I tried using just one object and add() in views.py but neither will return anything else than none. I have been looking at documentation and other forum questions but I just can't figure it out. Any help is greatly appreciated! views.py from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.core import serializers from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.urls import reverse from orders.models import Meal, Topping, Order def order(request): # Request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # Get IDs of meal, topping(s) and user idmeal = request.POST["idmeal"] idmeal = Meal.objects.get(pk = idmeal) # Topping[] is a list of numbers representing IDs for Topping database topping = request.POST.getlist('topping[]') for i in range(0, len(topping)): topping[i] = int(topping[i]) user = request.user userID = User.objects.get(username=user.username) topping = Topping.objects.filter(pk__in=topping) print(topping) # Create object in Order table order = Order.objects.create(customerID = userID, mealID = idmeal, price = 12, status = "pending") # Add values to ManyToManyField order.toppingsID.set(topping) print(order.toppingsID) return JsonResponse({"success": ""}, status=200) … -
Django + Jinja. Can't choose an element of dictinary
There is a dictinary of lists which I can render in Jinja template with that: {{ data.production_report.main_info }} So the Jinja template shows it: {"product_list":[{"name":"Mushroom soup","amount_got":"10"}],"decreasing_product_list":[{"name":"Chicken meat","amount_used":"6","amount_got":"3","loss_ratio":"50%"}]} The problem is that Jinja template can't render next things: {{ data.production_report.main_info.product_list }} {{ data.production_report.main_info.decreasing_product_list }} -
DRF: Best way to supply a dynamic default field value?
Our SAAS site utilizes a DRF backend with a Vue frontend. We have fields that do not require a value from the user, but do require a value in the database. I'd like to know where's the best place to supply such dynamic defaults. I've read in other posts that "save() is not always called" - though I don't yet know the circumstances where it would not be called. So, consider the following model: class Tenant(models.Model): name = models.CharField(max_length=100) subdomain = models.CharField(max_length=100, blank=True, null=True) schema_name = models.CharField(max_length=63, unique=True) In this case, only "name" is required (from the user); "schema_name", if left blank in the frontend form, can be derived from "name" (converting it to lowercase). Likewise, "subdomain" can be derived from "schema_name". "subdomain" can be blank/null because the "public" schema doesn't reference a subdomain, but its value will be required for all tenants other than "public".) So where should I put the code that populates those fields if they are blank when it comes time to create or update a Tenant?