Form Mixins
- synopsis:
Form mixin class in django-boost
MatchedObjectGetMixin
Mixin to add a method to get the queryset and object of the condition that matches the form input content.
from django import forms
from django_boost.forms.mixins import MatchedObjectGetMixin
from .models import Customer
class CustomerForm(MatchedObjectGetMixin, forms.ModelForm):
field_lookup = {'name': 'name__startswith'} # filter lookup kwargs
class Meta:
model = Customer
fields = ('name', )
Set field_lookup to set detailed search conditions.
from django.views.generic import FormView
from .forms import CustomerForm
class CustomerSearchView(FormView):
template_name = "form.html"
form_class = CustomerForm
def form_valid(self,form):
object = form.get_object() # get matched model object
object_list = form.get_list() # get matched models objects queryset
MatchedObjectGetMixin provides get_object and get_list methods, each of which returns a model object or queryset that matches the form input content.
FormUserKwargsMixin
Mixin that pulls a user keyword argument into self.user.
Pair it with django_boost.views.mixins.ViewUserKwargsMixin, which adds
the current request’s user to the form kwargs, so the form can access it
without the view passing it explicitly to form_valid/form_invalid.
from django import forms
from django_boost.forms.mixins import FormUserKwargsMixin
from django_boost.views.mixins import ViewUserKwargsMixin
from django.views.generic import FormView
class MyForm(FormUserKwargsMixin, forms.Form):
def clean(self):
cleaned_data = super().clean()
cleaned_data['owner'] = self.user
return cleaned_data
class MyFormView(ViewUserKwargsMixin, FormView):
form_class = MyForm