Created
May 22, 2016 23:26
-
-
Save maxmoriss/ba467ff80eab195baa5598aaa420d32f to your computer and use it in GitHub Desktop.
Example of FormView class based views of 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
| from django.views import generic | |
| class EmailPreferenceView(generic.FormView): | |
| form_class = EmailPreferenceForm | |
| def get(self, *args, **kwargs): | |
| # You can access url variables from kwargs | |
| # url: /email_preferences/geeknam > kwargs['username'] = 'geeknam' | |
| # Assign to self.subscriber to be used later | |
| self.subscriber = get_subscriber(kwargs['username']) | |
| def post(self, request, *args, **kwargs): | |
| # Process view when the form gets POSTed | |
| pass | |
| def get_initial(self): | |
| # Populate ticks in BooleanFields | |
| initial = {} | |
| for s in self.subscriber.events.all(): | |
| initial[s.value_id] = True | |
| return initial | |
| def get_form(self, form_class): | |
| # Initialize the form with initial values and the subscriber object | |
| # to be used in EmailPreferenceForm for populating fields | |
| return form_class( | |
| initial=self.get_initial(), | |
| subscriber=self.subscriber | |
| ) | |
| def get_success_url(self): | |
| # Redirect to previous url | |
| return self.request.META.get('HTTP_REFERER', None) | |
| def form_valid(self, form): | |
| messages.info( | |
| self.request, | |
| "You have successfully changed your email notifications" | |
| ) | |
| return super(EmailPreferenceView, self).form_valid(form) | |
| def form_invalid(self, form): | |
| messages.info( | |
| self.request, | |
| "Your submission has not been saved. Try again." | |
| ) | |
| return super(EmailPreferenceView, self).form_invalid(form) | |
| email_preferences = EmailPreferenceView.as_view() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment