7 Forms, user data, static files, and uploads

 

This chapter covers

  • Writing views that handle form submissions
  • Using the Form class to write web forms
  • Cross-site request forgery (CSRF) protection
  • Using the ModelForm to create forms based on Model classes
  • Writing views that handle file uploads
  • Providing access to both uploaded and static files

This chapter covers content handled by your website over and above a simple view. It starts out by showing you how to receive user input data through web forms, and then it moves on to dealing with files. Files can be uploaded by your users, and if they are, those same files can be downloaded or shown on a page. There are also files you include in your site that aren’t served by Django: CSS, images, JavaScript, and more. This chapter covers how to deal with user data and all kinds of file input and output as well as how to do it to manage it all securely.

7.1 Web forms

In the previous chapter, you took the first steps toward having self-serve user features in RiffMates. And although it wasn’t explicitly called out, you started using web forms. The login page is a web form with two fields: Username and Password. Submitting this form gets handled by a built-in Django view, which adds data to the user’s session, indicating they are authenticated. The mechanisms the login view uses are built on top of the tools available to you as a programmer. With them, you can build your own forms and have users submit data to your site.

7.1.1 Handling GET and POST in views

7.1.2 CSRF

7.1.3 Beautifying web forms

7.1.4 New in Django 5: Reusable field group templates

7.2 Django ModelForm

7.2.1 Validating fields in a model

7.2.2 A ModelAdmin for SeekingAd using Truncate

7.2.3 Writing a ModelForm

7.2.4 Using SeekingAdForm in a view

7.2.5 Editing existing data with forms

7.3 Serving static files

7.4 Uploads

7.4.1 Configuring your project for uploads

7.4.2 Storing and referencing uploaded files

7.4.3 File upload forms and views

7.4.4 Restricted file downloads