Skip to content

Instantly share code, notes, and snippets.

@suspiciousRaccoon
Created March 13, 2024 01:43
Show Gist options
  • Save suspiciousRaccoon/aef7a52844c650f385491c0f86cbf2e0 to your computer and use it in GitHub Desktop.
Save suspiciousRaccoon/aef7a52844c650f385491c0f86cbf2e0 to your computer and use it in GitHub Desktop.
Mixins for passing the request to a form in django
class BlogForm(GetRequestFromFormMixin, forms.ModelForm):
class Meta:
model = Blog
fields = ("name, description",)
def clean(self):
print(self.request) # we can now access the request!
return super().clean()
class AddRequestToFormMixin:
"""
Modifies `get_form_kwargs` to add the request object to the form kwargs.
"""
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs(*args, **kwargs)
kwargs["request"] = self.request
return kwargs
class GetRequestFromFormMixin:
"""
Modifies __init__ from a form to add the request. Must be accompanied by `AddRequestToFormMixin` in the view.
"""
def __init__(self, *args, **kwargs) -> None:
self.request = kwargs.pop("request")
super().__init__(*args, **kwargs)
class BlogCreateView(AddRequestToFormMixin, CreateView):
model = Blog
form_class = BlogForm
template_name = "app/blog_create.html"
success_url = reverse_lazy("blog-index")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment