関数ベースビューを書く
レスポンスを返すビューを作成します
「関数ベースビューを書く」はCoddyKit上の無料Django Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはDjango Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Django Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
What a View Really Is
A Django view is just a Python function that takes a request and returns a response. That is the whole contract. 🙂
The First Argument: request
Every view's first parameter is the request object. Django hands it to you automatically when a URL matches your view.
Importing HttpResponse
To send something back, you return an HttpResponse. Import it from django.http before you use it.
from django.http import HttpResponseYour First View
Here is a complete, working view. It takes request and returns plain text in a response.
from django.http import HttpResponse
def home(request):
return HttpResponse('Hello, Django!')Where Views Live
By convention, views go in your app's views.py file. Keeping them there makes them easy to find and wire up later.
You Must Return Something
A view that returns None raises an error. Django expects an HttpResponse every single time, with no exceptions.
Returning HTML
The response body is just a string, so you can put HTML inside it. The browser renders it like any page.
def home(request):
return HttpResponse('<h1>Welcome</h1>')Views Are Plain Functions
A view is normal Python, so you can run logic inside it: build a message, check a condition, then return your response.
def greet(request):
name = 'friend'
return HttpResponse('Hi ' + name)Naming Your View
Name views after what they do, like home or about. Clear names make your URL file readable when you connect them.
Function-Based vs Class-Based
This style is a function-based view, the simplest kind. Class-based views come later; functions are perfect to start with.
Nothing Runs Until It Is Mapped
A view does nothing on its own. It only runs when a URL points to it, which is the very next step you will learn.
Quick Check
Let's confirm the core contract of a Django view.
Recap: You Wrote a View
A view is a function that takes request and returns an HttpResponse. You import it, write your logic, and live in views.py. 🎉
よくある質問
「関数ベースビューを書く」レッスンは無料ですか?
はい。「関数ベースビューを書く」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Django Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Django Academyコースには全4レッスンが含まれています。
「関数ベースビューを書く」で何を学びますか?
レスポンスを返すビューを作成します ブラウザで直接実行するハンズオンコードでDjango Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Django Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのDjango Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「関数ベースビューを書く」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このDjango Academyレッスンでコードを書いて実行できますか?
はい。すべてのDjango Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。