Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Django docs
Django
Getting Started with DjangoProject StructureCore ConceptsData and StateTestingDeployment
Discussions

Django guide · 4/6

Data and State

In Django you describe data with ORM models, apply them to the database with migrations, and read and write it through QuerySets. User input is validated with forms, and state that lasts across requests is handled by sessions and the authentication system.

Models and relationships

Each attribute on a model class becomes a column in its table. ForeignKey creates a many-to-one relationship, ManyToManyField a many-to-many one, and OneToOneField a one-to-one one.

# polls/models.py
from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["-pub_date"]

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices")
    choice_text = models.CharField(max_length=200)
    votes = models.PositiveIntegerField(default=0)

on_delete decides what happens when the referenced row is deleted: CASCADE deletes this one too, PROTECT blocks it, and SET_NULL clears the field (needs null=True). related_name sets the name for the reverse lookup, as in question.choices.all().

Migrations

After changing your models, apply the change to the database in two steps.

# Detect model changes and write a file into migrations/
python manage.py makemigrations polls

# Show the SQL that will run
python manage.py sqlmigrate polls 0001

# Apply it to the database
python manage.py migrate

# List migrations and whether they are applied
python manage.py showmigrations

Commit migration files with your code so teammates and servers get the same schema from migrate. The default database is SQLite; production deployments often use PostgreSQL, and switching is a matter of changing DATABASES.

Querying with QuerySets

Model.objects is a manager, and the QuerySets it returns are lazy. Chaining filters runs no queries; the database is hit once, when you iterate over the QuerySet or turn it into a list.

from datetime import timedelta

from django.db.models import Count, F, Q
from django.utils import timezone

from polls.models import Choice, Question

# Create and save
q = Question.objects.create(question_text="What is your favorite language?")
q.choices.create(choice_text="Python")

# Filter with field__lookup syntax
recent = Question.objects.filter(pub_date__gte=timezone.now() - timedelta(days=7))
python_q = Question.objects.filter(question_text__icontains="python")

# Follow relations and annotate with a count
popular = (
    Question.objects.annotate(total=Count("choices"))
    .filter(total__gt=1)
    .order_by("-total")
)

# OR conditions and an atomic increment
Question.objects.filter(Q(question_text__startswith="Why") | Q(question_text__startswith="How"))
Choice.objects.filter(pk=1).update(votes=F("votes") + 1)

# Avoid N+1 queries
for choice in Choice.objects.select_related("question"):
    print(choice.question.question_text)

select_related fetches foreign keys in the same query with a JOIN, while prefetch_related loads many-to-many and reverse relations with one extra query. Try queries in python manage.py shell, and wrap writes that must succeed or fail together in transaction.atomic().

Forms

A form takes input, validates it and hands back clean values in cleaned_data. When the fields match a model, ModelForm saves you most of the work.

# polls/forms.py
from django import forms

from .models import Question


class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = ["question_text"]

    def clean_question_text(self):
        text = self.cleaned_data["question_text"].strip()
        if not text.endswith("?"):
            raise forms.ValidationError("A question must end with a question mark.")
        return text
# polls/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from .forms import QuestionForm


@login_required
def create(request):
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save()
            return redirect("polls:detail", question_id=question.pk)
    else:
        form = QuestionForm()
    return render(request, "polls/create.html", {"form": form})

Every POST form needs {% csrf_token %} to pass the CSRF middleware. Redirecting after a save stops a refresh from resubmitting the data.

Sessions and authentication

Sessions keep per-visitor state on the server and store only a session ID cookie in the browser. In a view, request.session behaves like a dictionary.

def add_to_cart(request, item_id):
    cart = request.session.get("cart", [])
    cart.append(item_id)
    request.session["cart"] = cart
    return redirect("shop:cart")

The authentication system, django.contrib.auth, provides user, group and permission models plus views for login, logout and password changes. Adding path("accounts/", include("django.contrib.auth.urls")) gives you the standard auth URLs. In views, request.user is the current user, and @login_required or LoginRequiredMixin restricts access. For a new project, the official docs recommend creating a custom user model that subclasses AbstractUser and pointing AUTH_USER_MODEL at it from the start, because switching later is very hard.

Summary

  • Models map to tables, fields to columns, and ForeignKey and friends to relationships.
  • makemigrations records changes and migrate applies them.
  • QuerySets are lazy; select_related and prefetch_related cut down the number of queries.
  • Validate input with forms, and manage per-user state with sessions and django.contrib.auth.
Questions about this chapter?
Previous chapterCore ConceptsNext chapterTesting

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.