Debian Codegraph @

docs/views.rst

raw
1 .. _views:
2
3 Class Based Views
4 =================
5
6 While :pypi:`django-polymorphic` provides full admin integration, you might want to build front-end
7 views that allow users to create polymorphic objects. Since a single URL cannot easily handle
8 different form fields for different models, the best approach is a two-step process:
9
10 1. **Step 1:** Let the user choose the desired type.
11 2. **Step 2:** Display the form for that specific type.
12
13 .. tip::
14
15 The code for this example can be found `here
16 <https://github.com/jazzband/django-polymorphic/tree/HEAD/src/polymorphic/tests/examples/views>`_.
17
18 This example uses model labels (e.g., ``app.ModelName``) to identify the selected type. Assume we
19 have the following models:
20
21 .. literalinclude:: ../src/polymorphic/tests/examples/views/models.py
22 :language: python
23 :linenos:
24
25 Step 1: Selecting the Type
26 --------------------------
27
28 Create a form that allows users select the desired model type. You can use a simple choice field
29 for this.
30
31 .. literalinclude:: ../src/polymorphic/tests/examples/views/views.py
32 :language: python
33 :lines: 1-45
34 :linenos:
35
36 Your template ``project_type_select.html``, might look like this:
37
38 .. literalinclude:: ../src/polymorphic/tests/examples/views/templates/project_type_select.html
39 :language: html
40
41 Step 2: Displaying the Form
42 ---------------------------
43
44 The creation view needs to dynamically select the correct form class based on the chosen model
45 label.
46
47 .. literalinclude:: ../src/polymorphic/tests/examples/views/views.py
48 :language: python
49 :lines: 47-
50 :linenos:
51
52
53 In your template ``project_form.html``, make sure to preserve the ``model`` parameter:
54
55 .. literalinclude:: ../src/polymorphic/tests/examples/views/templates/project_form.html
56 :language: html
57
58
59 And our urls might look like this:
60
61 .. literalinclude:: ../src/polymorphic/tests/examples/views/urls.py
62 :linenos:
63
64 Using ``extra_views``
65 ---------------------
66
67 If you are using :pypi:`django-extra-views`, :pypi:`django-polymorphic` provides mixins to help with
68 formsets. See :mod:`polymorphic.contrib.extra_views` for more details.