Sobes.tech
Junior

What basic classes does Django provide?

sobes.tech AI

Answer from AI

Django provides the following basic classes for building web applications:

  • django.db.models.Model: The main class for defining data models that are mapped to database tables. All custom models inherit from it.

    # Example of a basic model definition
    from django.db import models
    
    class Article(models.Model):
        title = models.CharField(max_length=100)
        content = models.TextField()
    
  • django.views.View: The base class for creating views that handle web requests and generate responses. Supports methods for various HTTP verbs (GET, POST, PUT, DELETE, etc.).

    # Example of a basic CBV definition
    from django.views import View
    from django.http import HttpResponse
    
    class MyView(View):
        def get(self, request, *args, **kwargs):
            return HttpResponse("Hello, world!")
    
  • django.forms.Form: The base class for defining web forms used for collecting and validating user input. Defines form fields and validation rules.

    # Example of a basic form definition
    from django import forms
    
    class ContactForm(forms.Form):
        name = forms.CharField(max_length=100)
        email = forms.EmailField()
        message = forms.CharField(widget=forms.Textarea)
    
  • django.contrib.admin.ModelAdmin: The base class for configuring the Django admin interface for a specific model. Defines how the model is displayed and edited in the admin panel.

    # Indirect inheritance, used in admin.site.register()
    # from django.contrib import admin
    # from .models import Article
    #
    # @admin.register(Article)
    # class ArticleAdmin(admin.ModelAdmin):
    #     list_display = ('title',)
    
  • django.urls.URLResolver and django.urls.URLPattern: Although not directly used by developers as base classes in everyday practice, URLResolver and URLPattern are fundamental internal classes underlying the URL routing system (URLconf). URLResolver represents a nested set of URL patterns, and URLPattern matches a specific URL to a view.

    # Used for defining routes
    # from django.urls import path
    # from . import views
    #
    # urlpatterns = [
    #     path('my-view/', views.MyView.as_view()),
    # ]
    

These classes form the foundation of most components of a Django application, providing structure and functionality for data handling, request processing, form creation, and admin panel management.