Created
March 13, 2024 01:43
-
-
Save suspiciousRaccoon/aef7a52844c650f385491c0f86cbf2e0 to your computer and use it in GitHub Desktop.
Mixins for passing the request to a form in django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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