Debian Codegraph @

src/polymorphic/tests/examples/views/views.py

raw
1 from django.apps import apps
2 from django.shortcuts import redirect
3 from django.urls import reverse
4 from django.views.generic import FormView, CreateView
5 from .models import Project, ArtProject, ResearchProject
6
7 from django import forms
8 from django.utils.translation import gettext_lazy as _
9
10
11 class ProjectTypeChoiceForm(forms.Form):
12 model_type = forms.ChoiceField(
13 label=_("Project Type"),
14 widget=forms.RadioSelect(attrs={"class": "radiolist"}),
15 )
16
17
18 class ProjectTypeSelectView(FormView):
19 form_class = ProjectTypeChoiceForm
20 template_name = "project_type_select.html"
21
22 def get_form_kwargs(self):
23 kwargs = super().get_form_kwargs()
24 # Build choices using model labels: [(model_label, verbose_name), ...]
25 choices = [
26 (model._meta.label, model._meta.verbose_name)
27 for model in [ArtProject, ResearchProject]
28 ]
29 kwargs["initial"] = {"model_type": choices[0][0] if choices else None}
30 return kwargs
31
32 def get_form(self, form_class=None):
33 form = super().get_form(form_class)
34 # Populate the choices for the form using model labels
35 choices = [
36 (model._meta.label, model._meta.verbose_name)
37 for model in [ArtProject, ResearchProject]
38 ]
39 form.fields["model_type"].choices = choices
40 return form
41
42 def form_valid(self, form):
43 model_label = form.cleaned_data["model_type"]
44 return redirect(f"{reverse('project-create')}?model={model_label}")
45
46
47 class ProjectCreateView(CreateView):
48 model = Project
49 template_name = "project_form.html"
50
51 def get_success_url(self):
52 return reverse("project-select")
53
54 def get_form_class(self):
55 # Get the requested model label from query parameter
56 model_label = self.request.GET.get("model")
57 if not model_label:
58 # Fallback or redirect to selection view
59 return super().get_form_class()
60
61 # Get the model class using the app registry
62 model_class = apps.get_model(model_label)
63
64 # Create a form for this model
65 # You can also use a factory or a dict mapping if you have custom forms
66 class SpecificForm(forms.ModelForm):
67 class Meta:
68 model = model_class
69 fields = "__all__" # Or specify fields
70
71 return SpecificForm
72
73 def get_context_data(self, **kwargs):
74 context = super().get_context_data(**kwargs)
75 # Pass the model label to the template so it can be preserved
76 # in the form action
77 context["model_label"] = self.request.GET.get("model")
78 return context