What Django is
Asked in interviews
AskedWhat is Django and what are its key features?INSTALLED_APPS.MIDDLEWARE list, and the response walks back up.|safe, @csrf_exempt or SQL built by string formatting.Asked in interviews
AskedWhat is Django and what are its key features?django-admin startproject mysitepython manage.py startapp blogpython manage.py runserverTipGive each app one purpose. A blog app shouldn't also handle billing.
Asked in interviews
AskedWhat are Django apps and how do they differ from projects?render(request, 'a.html', ctx)Every view must return an HttpResponse.request.user comes fromSession and authentication middleware set it.404 page.TrapThe template is MVC's view. A Django view holds the logic.
path('a/<int:id>/', view)re_path(r'^(?P<y>[0-9]{4})/$', view)str, int, slug, uuid and path. Only path matches slashes.include('blog.urls') {% url 'list' %}reverse('list')Tipurls.py picks the view, and views.py holds the code.
TrapDjango uses the first match, so order matters. Matching ignores the domain and the query string.
if request.method == 'POST':def post(self, request):ArticleView.as_view() return redirect('done')TipUse a function for one-off logic and a class for a common pattern or shared code.
TrapA function that branches only on GET and POST returns nothing for other verbs. Add a branch or @require_.
ListViewpaginate_by = 10DetailViewCreateViewUpdateViewDeleteView@login_requiredLoginRequiredMixin TipUse generic views for standard CRUD, not unusual logic.
TrapThe top decorator runs first, so put @login_required above the method check.
CharField(max_length=200) BooleanField()EmailField()DateTimeField(auto_now_add=True) TextField(blank=True) Make a text field optionalDateField(null=True, blank=True)Make a date or number optionalTrapOn a text field, null=True gives two values for no data, NULL and the empty string.
models.ForeignKey models.OneToOneField models.ManyToManyField models.CASCADEmodels.PROTECTmodels.RESTRICTSET_NULL needs null=Truemodels.SET_NULLmodels.SET_DEFAULT models.DB_CASCADE TrapDB_CASCADE is faster because Django fetches no related rows, but it sends no delete signals.
models.Managerdef get_queryset(self): TrapThe first manager you define becomes the default. Declare a plain objects first so it hides no rows.
Asked in interviews
AskedWhat are Django model managers and how do you create custom managers?abstract = TrueShare fields such as timestampsclass Restaurant(Place):Query every child through its parentproxy = TrueChange only ordering, manager or methodsTrapMulti-table inheritance links two tables with a OneToOneField, so loading a child reads both.
Asked in interviews
AskedWhat are the model inheritance styles in Django?python manage.py makemigrationspython manage.py migratepython manage.py migrate blog 0006python manage.py sqlmigrate blog 0007TrapA rollback works only if the migrations you undo are reversible.
Asked in interviews
AskedExplain Django migrations and their purpose.Add a required column in steps. Old and new code overlap during a deploy, so it stays nullable until the backfill ends.
atomic = FalseAddIndexConcurrently TrapMySQL can't roll back a failed schema change, so you fix it by hand.
Asked in interviews
AskedHow do you run Django migrations safely in production?Article.objects.all() .filter(live=True) .get(pk=1)None or a 404.filter(pk=1).first() get_object_or_404(Article, pk=1)TipThe ORM gives one API across databases, parameters that block SQL injection, and migrations.
Trapget() raises DoesNotExist or Multiple, so use it on unique fields.
for a in qs:list(qs)bool(qs)qs.count()qs.exists()TrapChaining another .filter() builds a new QuerySet, and that one queries again.
Asked in interviews
AskedExplain Django QuerySets and lazy evaluation.Q(a=1) | Q(b=2)~Q(title='')filter(stock__lt=F('min')) update(stock=F('stock') - 1)aggregate(Avg('price'))annotate(n=Count('book')) filter(n__gt=5)TipIn one filter() call, Q arguments must come before keyword arguments.
TrapSeveral Count() calls across relations multiply rows and give wrong totals. Pass distinct=True.
TipN+1 means one query for the list, then one more per item that touches a related object.
Trapauthor. in the loop ignores the prefetch and queries again.
Asked in interviews
AskedExplainselect_related() and prefetch_related() in Django ORM.with transaction.atomic(): select_for_update() transaction.on_commit(fn) TipATOMIC_REQUESTS puts every view in a transaction, but it adds overhead.
TrapCatch database errors around an atomic block, not inside it, or Django may miss the broken transaction.
Asked in interviews
AskedHow do you manage database transactions in Django?{{ article.title }}{{ text|lower }}{% for a in qs %}< into <, which blocks most cross-site scripting.{% block content %}{% extends 'base.html' %}{{ block.super }}Trap{% extends %} must be the child's first template tag.
@register.filter @register.simple_tag @register.inclusion_tag TipLoad the module in a template with {% load custom_tags %}.
Traptemplatetags needs an __init__.py, and the dev server needs a restart.
Asked in interviews
AskedHow do you create and use custom template tags and filters?forms.Formforms.ModelFormform.is_valid()form.cleaned_data def clean_title(self): def clean(self):Tipis_valid() runs field checks, then clean_<field>(), then clean().
TrapList fields explicitly, or users can set fields they shouldn't.
ValidationErrorvalidators=[is_even] TrapValidators don't run on save(). A ModelForm or full_clean() runs them.
None if they failauthenticate(request, **creds)login(request, user)logout(request)AbstractUserAbstractBaseUser USERNAME_FIELD = 'email'TipIn other code, use get_, never User.
TrapSet AUTH_USER_MODEL before the first migration. Changing it later is complex.
('publish', 'Can publish')Put it in Meta.permissions .user.has_perm('blog.publish') @permission_required PermissionRequiredMixin group.permissions.add(perm) user.groups.add(group) TipPermissions are model-level. Per-object rules need a custom backend or a package.
TrapCheck permissions, not group names. has_perm() keeps working when you rename a role.
request.session['cart'] = cartpython manage.py clearsessionsTipBy default the database keeps the data, and the cookie holds only a session ID. Cookie-based sessions put the data in the cookie, where the client can read it.
TrapDjango saves only when you assign or delete a key. Assign a changed list back.
Asked in interviews
AskedHow do sessions work in Django?get_response.process_response() MiddlewareMixinTipAdd the class's dotted path to MIDDLEWARE.
TrapOnly a middleware listed below Authentication can read request.user.
@receiver(post_save, sender=User)TipConnect receivers in App. They run one at a time before send() returns.
TrapQueryset update() and bulk_create() send no save signals.
Asked in interviews
AskedWhat are Django signals and when should you use them?python manage.py createsuperuserModelAdmin with columns, filters and searchlist_displaylist_filtersearch_fields@admin.actionactions = ['publish']Trapqueryset. in an action skips each save() and the save signals.
JsonResponse(items, safe=False)viewsets.ModelViewSet ModelSerializerSerializerdjango-ratelimit, which gives 403@ratelimit(key='ip', rate='5/m')AnonRateThrottle UserRateThrottle TipPlain Django suits a few simple endpoints. Django REST Framework (DRF) suits many, or outside clients.
TrapThe local-memory cache keeps one counter per process. Use a shared cache such as Redis.
python manage.py testSimpleTestCaseTestCaseTransactionTestCase fixtures = ['blog.json']factory_boyfactory.django.DjangoModelFactory TrapFixtures go stale when models change, and a test can depend on a pk=1 hidden in a file.
qs.explain()db_index=Trueonly('title')defer('body')'CONN_MAX_AGE': 600'OPTIONS': {'pool': True}TipMeasure first. Django Debug Toolbar shows each page's queries and their time.
TrapCONN_MAX_AGE must stay 0 when the built-in pool is on.
UpdateCacheMiddleware FetchFromCacheMiddleware @cache_page(60 * 15){% cache 500 sidebar %}cache.set('k', v, 30)cache.get('k')TrapPages that differ per user need the right Vary headers, or users may get each other's pages.
Asked in interviews
AskedExplain Django's caching framework.from django.tasks import taskIt only enqueues. Production needs a real worker.TipPass IDs, not model objects, and enqueue from on_commit().
TrapA retry can run a task again, so make tasks idempotent, meaning safe to run twice.
Asked in interviews
AskedHow do you run background tasks in Django?{% csrf_token %}X-CSRFToken403.Article.objects.raw(sql, [value])TrapDjango skips the CSRF check on safe methods such as GET, so a GET view must never change data.
DEBUG = FalseALLOWED_HOSTS = ['example.com']os.environ['SECRET_KEY'] SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = Truepython manage.py check --deployTrapStart SECURE_ small. A wrong setting can break the site for as long as that value lasts.
Asked in interviews
AskedWhat are important Django settings for production deployment?STATIC_ROOTpython manage.py collectstaticSTORAGESIt replaced DEFAULT_FILE_STORAGE , removed in 5.1.TipThe web server or a CDN serves these files, never Django.
TrapUploads are untrusted. Limit their size, never execute them and serve them from a separate domain.
Asked in interviews
AskedHow do you handle static files and media files in Django production?gunicorn mysite.wsgi:application uvicorn mysite.asgi:application TrapAsync views under WSGI each get a one-off event loop and lose the benefit for long requests.
Asked in interviews
AskedExplain Django's deployment with WSGI and ASGI.Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in