Django: Can class-based views accept two forms at a time?

前端 未结 7 2269
说谎
说谎 2020-11-29 17:50

If I have two forms:

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

class SocialForm(forms         


        
相关标签:
7条回答
  • 2020-11-29 18:43

    Resembles @james answer (I had a similar starting point), but it doesn't need to receive a form name via POST data. Instead, it uses autogenerated prefixes to determine which form(s) received POST data, assign the data, validate these forms, and finally send them to the appropriate form_valid method. If there is only 1 bound form it sends that single form, else it sends a {"name": bound_form_instance} dictionary.

    It is compatible with forms.Form or other "form behaving" classes that can be assigned a prefix (ex. django formsets), but haven't made a ModelForm variant yet, tho you could use a model form with this View (see edit below). It can handle forms in different tags, multiple forms in one tag, or a combination of both.

    The code is hosted on github (https://github.com/AlexECX/django_MultiFormView). There are some usage guidelines and a little demo covering some use cases. The goal was to have a class that feels as close as possible like the FormView.

    Here is an example with a simple use case:

    views.py

        class MultipleFormsDemoView(MultiFormView):
            template_name = "app_name/demo.html"
    
            initials = {
                "contactform": {"message": "some initial data"}
            }
    
            form_classes = [
                ContactForm,
                ("better_name", SubscriptionForm),
            ]
    
            # The order is important! and you need to provide an
            # url for every form_class.
            success_urls = [
                reverse_lazy("app_name:contact_view"),
                reverse_lazy("app_name:subcribe_view"),
            ]
            # Or, if it is the same url:
            #success_url = reverse_lazy("app_name:some_view")
    
            def get_contactform_initial(self, form_name):
                initial = super().get_initial(form_name)
                # Some logic here? I just wanted to show it could be done,
                # initial data is assigned automatically from self.initials anyway
                return initial
    
            def contactform_form_valid(self, form):
                title = form.cleaned_data.get('title')
                print(title)
                return super().form_valid(form) 
    
            def better_name_form_valid(self, form):
                email = form.cleaned_data.get('email')
                print(email)
                if "Somebody once told me the world" is "gonna roll me":
                    return super().form_valid(form)
                else:
                    return HttpResponse("Somebody once told me the world is gonna roll me")
    

    template.html

    {% extends "base.html" %}
    
    {% block content %}
    
    <form method="post">
        {% csrf_token %}
        {{ forms.better_name }}
        <input type="submit" value="Subscribe">
    </form>
    
    <form method="post">
        {% csrf_token %}
        {{ forms.contactform }}
        <input type="submit" value="Send">
    </form>
    
    {% endblock content %}
    

    EDIT - about ModelForms

    Welp, after looking into ModelFormView I realised it wouldn't be that easy to create a MultiModelFormView, I would probably need to rewrite SingleObjectMixin as well. In the mean time, you can use a ModelForm as long as you add an 'instance' keyword argument with a model instance.

    def get_bookform_form_kwargs(self, form_name):
        kwargs = super().get_form_kwargs(form_name)
        kwargs['instance'] = Book.objects.get(title="I'm Batman")
        return kwargs
    
    0 讨论(0)
提交回复
热议问题