Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to get the latest X related-object by criteria, and keep other fields?
I have a case of Authors followed by a User, that I want to sort by their latest published Book, as well as display the book's title and release_date. Authors also have books with a release_date in the future, which I want to keep out of the result-set. I need to return JSON since Django is being used only for backend. After some research the best I've gotten is this: relevant_books = Book.objects.filter(author=OuterRef("pk"), release_date__range=[back_delta, startdate], author__id__in=user_follows).order_by("-release_date") user_authors_with_books = Author.objects.filter(id__in=user_follows) \ .annotate(latest_release_date=Subquery(relevant_books.values("release_date")[:1])) \ .annotate(latest_release_title=Subquery(relevant_books.values("title")[:1])) \ .filter(latest_release_date__isnull=False) \ .order_by(F("latest_release_date").desc(nulls_last=True), "id") \ .values(*fields_to_return, "latest_release_date", "latest_release_title") I'm not a big fan of annotating twice, and have a feeling there's a better way to write this Django ORM code for a quicker/more-efficient (PostgreSQL) query. Am I right? -
Django migration not picking up all the model fields
I created a new Django project on Windows 10, with the latest python and Django. After creating the model with a number of tables/models on one model it skipped some fields. After retrying it would not create a new migration script. I looked at the initial 0001_initial.py and the fields were missing in that file. I later added a single new field and that field migrated property but not the missing fields. All other models were successfully updated in the initial migration. This happens to be a SQLite DB. The model that is missing fields: class articles(models.Model): """ articles""" title = models.CharField (max_length=500) teaser = models.CharField (max_length=500) summary = models.CharField (max_length=1500) byline = models.CharField (max_length=250) category = models.SmallIntegerField articlenote = models.CharField (max_length=1000) author = models.CharField publishedDate = models.DateTimeField articleStatus = models.CharField(max_length=4) articleText = models.TextField last_update= models.DateTimeField def str(self): return self.name The missing fields are : category, author, publishedDate, articleText Interesting after trying to rerun the migration I was getting Missing Defaults errors on a new table I was creating. Since this is a brand new project I can just blow away the database and the migration scripts and try again. I would like to knwo what is potentially causing this … -
"django.core.exceptions.ValidationError: ['“post_id” is not a valid UUID.']" with seemingly valid UUID
This is a simple blog app I am creating. I have a model that creates an article and generates a UUID for each article created. This functions as expected. I am now attempting to create a view variable that contains the "post_id" object from my model "Post" so that I can later insert this variable into my html template. The confusing thing is I know the Post model generates a valid UUID (at least my understand of UUIDs) as I have seen it generated so I am unclear where to start looking to resolve this issue. Other similar issues online do not seem to be related to my issue. myapp/views.py from django.shortcuts import render from django.utils import timezone from .models import Post def blog_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') post_uid = Post.objects.get(pk="post_id") context = { "post_uid": post_uid, "posts": posts } return render(request, 'blog/blog_list.html', context) def article(request, post_id): current_article = Post.objects.get(pk=post_id) return render(request, 'blog/article.html', {'current_article':current_article}) myapp/model.py from django.db import models from django.conf import settings from django.utils import timezone import uuid class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return … -
How to add a line chart for the table visualization and add a drop down in a Django Project?
I have a Django project and I have a model that contains data. Now I want to make a visualization for the data of that model(table) with "line chart"(or other). I also want to add a 'drop down' option so that I can select different options from it and change the line chart automatically. -
Binding specific foreign key to ModelForm
My ModelForm is working but the problem is it currently gives acct_no a dropdown of all customers in the database. this is the workflow currently. So I select a customer profile and add a new job from that profile page. But when the form populates, it is not bound to that customer. I do not want to give them the option to select from a list of customers. Is there a way to automatically bind the form with that specific customer? I'm fairly new to Django and have tried looking at the form docs but I think I'm missing something. models.py class Customers(models.Model): acct_no = models.AutoField(db_column='ACCT_NO', primary_key=True) type = models.CharField(db_column='Type', max_length=45) first_name = models.CharField(db_column='FIRST_NAME', max_length=45, blank=True, null=True) last_name = models.CharField(db_column='LAST_NAME', max_length=45, blank=True, null=True) address = models.CharField(db_column='ADDRESS', max_length=100, blank=True, null=True) class Jobs(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) job_type = models.CharField(db_column='JOB_TYPE', max_length=45, blank=True, null=True) estimatedate = models.CharField(db_column='EstimateDate', max_length=45, blank=True, null=True) estimatetime = models.CharField(db_column='EstimateTime', max_length=45, blank=True, null=True) comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True) forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'comments'] widgets = { 'job_type' : forms.Select(choices = JOBS, attrs={'class' : 'form-control form-select'}), 'estimatedate' : widgets.DateInput(attrs={'type' : 'date', 'class' : 'form-control'}), 'estimatetime' : widgets.TimeInput(attrs={'type' : 'time', 'class' … -
Django signal only works when debug=True, DJANGO 3.2.4
I've been lookin everywhere and i coulnd't find any refference about this, my Django model signal only works when the debug=True, but it doesn't work if debug=False, this occur both on localhost and production server. my settings looks like this: settings.py from pathlib import Path import os import environ env = environ.Env() environ.Env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent #production STATIC_ROOT = 'https://d1u356tnw52tcs.cloudfront.net/' SECRET_KEY = env("SECRET_KEY_PROD") DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.postgres', 'sellrapp', 'stock_management', 'corsheaders', 'drf_yasg', 'optimized_image', 'csvexport', 'kronos', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = '****.urls' WSGI_APPLICATION = '****.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("NAME_PROD"), 'USER': env("USER_PROD"), 'PASSWORD': env("PASSWORD_PROD"), 'HOST': env("HOST_PROD"), 'PORT': env("PORT_PROD"), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Singapore' USE_I18N = True USE_L10N = True USE_TZ = True WEB_BASE_URL = 'https://****.com/' BASE_URL_LIVE_CAMPAIGN = WEB_BASE_URL + "product/" if set to debug=False, the signal wouldn't triggered, and there's no any error trown. signals.py from django.dispatch import receiver from django.db.models.signals import pre_save, post_save, pre_delete from .models import ManualWithdrawals @receiver(pre_delete, sender=ManualWithdrawals) def manual_wd(sender, instance, **kwargs): order = ManualWithdrawals.objects.get(id=instance.id) consumer_order = order.order_id_list.all() sample_order … -
Django - Bypass loading code in the apps.ready function when making migrations or migrating to the database
For starters, I have searched for this before with no luck to find something around this. Background: I have created an inventory application for work to help my team be able to quickly see stats around our IT infrastructure. I have threads kicked off when the application loads to kick off some scraping functions. That code works great, but it happens whenever I create and apply database migrations (manage.py makemigrations & manage.py migrate). Goal: I'd like to only kick off the scraping code when I'm issuing the runserver command (manage.py runserver). This way, I don't have resources competing between the migration activities and the scraping activities. It also often generates lots of errors because sometimes not all of the database models/fields exist in the database yet. Ideas: Modify the code in the django repository to introduce a flag that I can then check against before I have the scraping code run. Not recommended This will get overwritten when I update django, and it won't persist between my dev server and prod server. Find a way to check which command is being run with the manage.py, and introduce a check to only start scraping if that command is run. Recommended This … -
Where to put a background task and how to be able to still debug
I have an almost model-less django app running, that collects infos from some API calls and displays them on a frontend via DRF. At some point I need to start calling this other API after django started and in debugging I face the problem of an unresponsive console, as soon as I activate the server via runserver command. My service so to say vastly looks like this: class APISERVICE(object): def __init__(self): self.time_now = datetime.datetime.now() self.sDATA = ServerAPI("https", settings.API_URL, settings.API_USR, settings.API_PWD) threading.Thread(target = self.worker, kwargs = {"interval": 10, "function": self.pollAPI}).start() def worker(self, interval, function): while True: function() time.sleep(interval) def pollAPI(self): try: self.time_since_last_run = (self.time_now - self.time_old).seconds except Exception as E: self.time_since_last_run = 20 if self.time_since_last_run >= 20: self.time_old = datetime.datetime.now() data = self.sDATA ... Two Questions arise: the serivce should run "forever" and therefore I thought about just calling it from inside the views.py or the apps urls.py. Why is that good/bad? When instantiated the console can not stop the execution any more in debug mode via CTRL + C - I suspect this is due to the sleep command. How can I avoid this without installing something like celary or django-background-tasks? -
JS music player error : "TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context"
I have a music player inside a Django app, written in JQuery, the user track files get uploaded into a AWS S3 bucket, I'm then trying to fetch the data from a REST API to get the mp3 link into the music.js code, when the app runs locally it works fine when loading tracks but after deployed to Heroku the tracks don't load, the music player just seems to be stuck on loading. I'm also getting an error in the Array prototype - construction function() in the console : "TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context". here is the jquery code for the music player notice the top fetch async function populates the trackUrl array with the mp3 link, it also fetches the track name and artist name, How can I fix this?: music.js $(function () { async function getUserTracks() { try { await fetch("https://sound-city.herokuapp.com/music/music_all/?format=json") .then(res => res.json()) .then(data => { for (item of data) trackNames.push(item['title']), trackUrl.push(item['track']), albums.push(item['artist_name']) console.log(trackNames, trackUrl, albums) }) } catch(error) { console.error(error) } } getUserTracks(); function createAlbumId() { setTimeout(function () { let number = 0; for (let i = 0; i < trackUrl.length; i++) { number++; albumArtworks.push(`_${number}`); // console.log(albumArtworks); } }, 100) … -
How to uninstall django-rest-swagger?
Is there a simple or elegant way to uninstall django-rest-swagger on Windows 10? I've recently started developing API's and creating documentation. I found a tutorial that used the django-rest-swagger app. After installing the app and doing more reading, I discovered that it was deprecated, and the developer's GitHub page recommends using drf-yasg. I tried using "pip uninstall django-rest-swagger," and that echoed back that the app was uninstalled. But, when I went into the virtual environment folder of the project, all the package folders were still there. I also tried "pipenv uninstall django-rest-swagger", but it returned "pipenv is not recognized..." I spent a few hours reading the app docs, and googling "how to remove/ uninstall django-rest-swagger." However, I didn't find anything useful. Eventually, I gave up, and decided to do it the hard way. I manually deleted all the installed files. Fortunately, I hadn't updated my requirements.txt, so, I knew what was originally installed. While this solution worked, it was somewhat time consuming. Does django-rest-swagger have an internal uninstall command? And does anyone know why "pip uninstall" didn't remove the app folders? Thanks -
Django - Pass multiple parameters from in a form action
I want to pass 3 values from my Template which are id, size & request.user template.html <form action='{{ id }}/{{ size }}/{{ request.user }}' method='GET'> . . <form> urls.py path("<id>/<size>/<user_name>", views.add_to_cart) That is what I have in mind which does not work for sure, so I wonder if there is a way to call a specific URL and then pass in some parameters which I can then use in my views.py file to query a specific object using the id from the database and edit something, I guess something like the following might explain what I mean: ./cart?id=00003,size='M',user=admin So is there a way to do this in Django, my bad if the question is dummie its first time I study back-end. -
How to use try and except in django?
I wanted to use try and except in djagno template is there is any way to use it. I want to check either attendance table has any data of not. and if not it has to show error text {% try %} {% for attendances in attendance %} .... {% endfor %} {% except %} <h1>Error Attendance table has no data.</h1> -
How can I use if inside if in django template
Hello Guys I want to create a card where if an authenticated user is equal to a certain post. So to show authenticated users these are his post in blue I want to add noteActive class. so anyone knows how to use if inside if in Django template?? index.html {% extends 'base.html' %} {% block title %} OctoNotes - Home {% endblock title %} {% block content %} <div class="noteDisplay"> {% if notes %} {% for note in notes %} {% if request.user == note.user %} <div class="noteCard noteActive"> {% else %} <div class="noteCard"> {% end if %} <div class="noteUser"> <p class="noteUserUsername">{{note.user}}</p> <div class="info"> <p class="noteUserPubDate">{{note.pub_date}}</p> {% if request.user == note.user %} <div class="info-btn"> <div></div> <div></div> <div></div> </div> <div class="noteDropDown"> <a href="#">Edit</a> <a href="{% url 'notes:deleteNote' note.id %}">Delete</a> </div> {% endif %} </div> </div> <div class="noteContent"> <h2>{{note.title}}</h2> <p>{{note.content}}</p> </div> </div> {% endfor %} {% else %} <p> No Notes, Create Your First Note.... </p> {% endif %} </div> {% endblock content %} -
Django file explorer
I need to create a Django file explorer. It needs to perform a similar function to the Simplehttpserver that comes with python. The main purpose is rendering static html files and making certain directories available for TEST users or ITOPS users etc. Need some advice how to do this. -
why column blog_post.category_id does not exist in django after hosting with heroku
I'm making a web application with django and I can run this application on localserver without any error.But when I host it gets a error like column blog_post.category_id does not exist LINE 1: ...d_on", "blog_post"."status", "blog_post"."image", "blog_post... By the way I run migrations for this application with heroku server.And also when I list tables in heroku using heroku pg:psql this command.After that I can see all the tables are created in heroku server.Do you have any suggestion. -
gunicorn: error: argument --error-logfile/--log-file: expected one argument - Procfile
When I run heroku open, it says that there is an application error. I run heroku logs --tails, this comes up: gunicorn: error: argument --error-logfile/--log-file: expected one argument I assume it's a problem with my Procfile, because my Procfile has something to do with --log-file. Heres my Procfile: web: gunicorn pages_project.wsgi --log-file - Please help me! -
How to render a table in Django from a class with manytomanyfield for all fields selected for an instance?
I am struggling to render a table view in Django 3.2 that will display data from instance of a class: class SalesPlan(models.Model): customer = models.OneToOneField(Customer, null=True, on_delete=RESTRICT) period = models.DateField() product = models.OneToOneField(Product, null=True, on_delete=RESTRICT) qty = models.DecimalField(max_digits=10, decimal_places=2, null=True) classes for customer and product: class Customer(models.Model): customer_code = models.CharField(max_length=6, primary_key=True, unique=True) customer_name = models.CharField(max_length=100) belongs_to_sales_channel = models.ForeignKey(SalesChannel, on_delete=RESTRICT) customer_portfolio = models.ManyToManyField(Product) date_created = models.DateTimeField(auto_now_add=True, null=True) class Product(models.Model): product_group = models.ForeignKey(ProductGroup, on_delete=RESTRICT) product_subgroup = models.ForeignKey(ProductSubGroup, on_delete=RESTRICT) item_code = models.CharField(max_length=5, primary_key=True) item_name = models.CharField(max_length=100) unit_of_measure = models.CharField(max_length=10) product_weight = models.DecimalField(max_digits=5, decimal_places=3) product_weight_text = models.CharField(max_length=10) I have tried a function based view and class based view. A class based view gives me one line for one product, since SalesPlan class is set like that. Is there a way to render rows for each product in Customer.customer_portfolio.all() with all data already set and only with quantity for a user to input? I have searched for similar examples, all I found is what I already have: class based view can display a form, for one instance (only one row). I failed using formset, I am currently researching if it's possible using a formset. -
Splitting settings.py in prod and dev causing a ModuleNotFoundError, why?
I am new to django and trying to deploy my app. I would like to split my settings in two (dev and prod). When I did python manage.py runserver with just one settings.py file, it worked perfectly. I have now the following folder structure: apps core pycache settings pycache init.py base.py dev.py prod.py init.py asgi.py urls.py utils.py wsgi.py media etc. base.py from pathlib import Path import os import sys from django.contrib.messages import constants as messages # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent sys.path.insert(0, os.path.join(BASE_DIR, "apps")) # 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 = "my_secret_key" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "account.apps.AccountConfig", "address.apps.AddressConfig", "basket.apps.BasketConfig", "contact.apps.ContactConfig", "discount.apps.DiscountConfig", "home_page.apps.HomePageConfig", "la_marque.apps.LaMarqueConfig", "orders.apps.OrdersConfig", "payment.apps.PaymentConfig", "shipping.apps.ShippingConfig", "store.apps.StoreConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django_extensions", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "basket.context_processors.basket", ], }, }, ] AUTH_USER_MODEL = … -
Failing to access Nginx server (Django + Docker + Postgres)
After following this excellent tutorial https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/, I was able to create my own docker with Django + Postgres. However when I try to access my Nginx server (locally) I receive "This site can’t be reached" page: Which is weird because when I build my docker-compose.prod.yml and run it, everything seems to be working fine: Do you guys have any idea what might be causing this issue? Here is my code repo: https://github.com/MarioSilvaPrada/portfolio_v2 Dockerfile.prod: https://github.com/MarioSilvaPrada/portfolio_v2/blob/master/Dockerfile.prod docker-compose.prod.yml: https://github.com/MarioSilvaPrada/portfolio_v2/blob/master/docker-compose.prod.yml Thank you in advance! -
Javascripts not working after Django update
I updated my Django 1.9 application to Django 3.1 following the changes mentioned in the releases. The application is running, but the javascripts are not showing the same bevhavior. <a href="{% url field.label_tag|cut:field.label|striptags prj_pk=ProjectId %}" class="add-another" id="add_{{field.auto_id}}" onclick="return showAddAnotherPopup(this);"></a> This line previously showed + button to open a new form but now the + button is not seen on the webpage. What has changed with respect to Javascripts in Django 3.1? -
Is django.views.generic.edit.UpdateView same as CreateView
I am making a view that will create and update an object. I was looking at which view to inherit from, but it appears that CreateView and UpdateView are identical in principal. Any reason to choose one over the other? Create View: class BaseCreateView(ModelFormMixin, ProcessFormView): """ Base view for creating a new object instance. Using this base class requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = None return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None return super().post(request, *args, **kwargs) class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView): """ View for creating a new object, with a response rendered by a template. """ template_name_suffix = '_form' And Update View: class BaseUpdateView(ModelFormMixin, ProcessFormView): """ Base view for updating an existing object. Using this base class requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView): """View for updating an object, with a response rendered by a template.""" template_name_suffix = '_form' -
Django custom authentication backend - "is_valid" calls authenticate
I am doing my custom auth backend for the first time, and it generally works, but i fail to understand a thing or two and there is some unwanted behaviour in my view. Basically i just wanted to add an additional mandatory field - domain name which would have to be filled in (or choosen) on login. So i have my custom DomainUser (AbstractUser) which defines additional "domainname" field class DomainUser(AbstractUser): domainname = models.CharField(max_length=50) REQUIRED_FIELDS = ['domainname', ] def __str__(self): return self.username @property def domainusername(self): return ''.join([self.domainname, '\\', self.username]) then there is the view: def domain_login(request): if request.method == 'POST': login_form = DomainLoginForm(data=request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') domainname = login_form.cleaned_data.get('domainname') raw_password = login_form.cleaned_data.get('password') user = authenticate(username=username, domainname=domainname, password=raw_password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('admin:index')) else: pass # should return invalid logon page else: login_form = DomainLoginForm() context = { 'login_form': login_form, } return render(request, 'domain_auth/login.html', context) And the auth: class DomainLDAPBackend(BaseBackend): def authenticate(self, request, username=None, domainname=None, password=None): #return DomainUser.objects.get(username__iexact=username, domainname__iexact=domainname) return DomainUser.objects.get(username__iexact=username) def get_user(self, user_id): try: return DomainUser.objects.get(pk=user_id) except DomainUser.DoesNotExists: return None Auth is a complete placeholder for now (it doesn't really authenticates the use with domain, but that's just temporary), it's just for test purpose … -
How to order django rest framework search results by the query written?
I want to order my django search results (DRF) in the order it was written. For example when I search https://mywebsite.com/api/title=one,two,five,nine so the first result from the API should be Post One, Post Two, Post Five, and Nine and so on. Thanks in advance. -
django __date return None in MySQL
Simple question: Why Model.objects.values('some_datetime_field',) returns the datetimes while Model.objects.values('some_datetime_field__date',) returns Nones? -
Django - alter objects from different apps
I am working with several different django apps, which provides some data for another one: class WordpressSnapshot(models.Model): configuration = models.ForeignKey(WordpressServerConfiguration, on_delete=models.CASCADE, related_name='snapshots') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % self.created_at class Post(models.Model): class Meta: unique_together = (('snapshot', 'slug'),) snapshot = models.ForeignKey(WordpressSnapshot, on_delete=models.CASCADE, related_name='posts') date = models.DateTimeField() excerpt = models.CharField(max_length=255) slug = models.CharField(max_length=255) title = models.CharField(max_length=255) content = models.TextField() author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, related_name='posts') media = models.URLField() def __str__(self): return '%s %s' % (self.slug, self.author) class WebSite(models.Model): name = models.CharField(max_length=255) .... posts = models.ForeignKey( "wordpress.WordpressSnapshot", on_delete=models.SET_NULL, null=True, blank=True ) pages = models.ManyToManyField(Page, null=True, blank=True) def __str__(self): return self.name Currently I'm creating a new WordpressSnapshot (which gets all posts from our blog), updating the posts field in WebSite, updating several other fields in the same fashion and after that - I am creating a new frontend object, which relies on data from WebSite. What is the best/the most django approach to hide all of that stuff behind a single click? Do I have to create a new model "BuildingSiteFacade" just to perform all this operations during creation of BuildingSiteFacade object?