Created
June 2, 2022 21:31
-
-
Save hazho/1d0e503249fad39f7110314fe05c9f86 to your computer and use it in GitHub Desktop.
Testing the upgrading to wagtail version 3
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 HHFormBuilder(FormBuilder): | |
def create_image_field(self, field, options): | |
return WagtailImageField(**options) | |
class HHFormSubmission(AbstractFormSubmission): | |
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True) | |
def get_data(self): | |
form_data=super().get_data() | |
print(form_data) | |
return form_data | |
def __str__(self): return f'{self.form_data}' | |
class HHSubmissionsListView(SubmissionsListView): | |
def get_context_data(self, **kwargs): | |
context=super().get_context_data(**kwargs) | |
if not self.is_export: | |
field_types=['submission_date'] + ['user'] + [field.field_type for field in self.form_page.get_form_fields()] | |
data_rows=context['data_rows'] | |
ImageModel=get_image_model() | |
for data_row in data_rows: | |
fields=data_row['fields'] | |
for idx, (value, field_type) in enumerate(zip(fields, field_types)): | |
if field_type == 'image' and value: | |
image=ImageModel.objects.get(pk=value) | |
rendition=image.get_rendition('fill-60x37|jpegquality-30') | |
preview_url=rendition.url | |
url=reverse('wagtailimages:edit', args=(image.id,)) | |
# build up a link to the image, using the image title & id | |
fields[idx]=format_html( | |
"<a href='{}'><img alt='Uploaded image - {}' src='{}' /><br>{}... ({})</a>", | |
url,image.title,preview_url,image.title[:7],value | |
) | |
return context | |
class FormPage(AbstractEmailForm): | |
subpage_types=[] | |
is_creatable=True | |
nav_title=models.CharField(max_length=45, verbose_name="Custom title for main nav-bar menu", null=True, blank=True, help_text="if not used, the page's title will be used in the nav-bar menu") | |
no_se_index=models.BooleanField(verbose_name="No SE Indexing", null=True, blank=True, help_text="Use this to control on indexing this page or not (in search engines, like: bing, google or ... any other one)") | |
custom_metadata=models.TextField(blank=True, null=True, help_text="add as much elements as you need ") | |
form_builder=HHFormBuilder | |
submissions_list_view_class=HHSubmissionsListView | |
uploaded_image_collection=models.ForeignKey('wagtailcore.Collection',null=True,blank=True,on_delete=models.SET_NULL,help_text=_('collection for uploaded image (if that field had been used), Default: Root') ,) | |
thank_you_text=models.CharField(max_length=200, blank=True) | |
more_submissions=models.BooleanField(verbose_name="Can a User Submit more than Once?",default=True, null=True, blank=True, help_text="uncheck this if you want to prevent a user from submitting more than once (Users should be registered))") | |
content_panels=Page.content_panels + [ | |
FieldPanel('more_submissions', classname="col4"), | |
FieldPanel('subject', classname="full"), | |
FieldRowPanel([FieldPanel('from_address', classname="col6"),FieldPanel('to_address', classname="col6"),]), | |
FieldPanel('thank_you_text', classname="full"), | |
] | |
form_fields_panels = [ | |
MultiFieldPanel([InlinePanel('form_fields', label="Field", classname="collapsible" ),FieldPanel('uploaded_image_collection', classname="col6"),],heading="Fields", classname=""), | |
] | |
promote_panels = [ | |
MultiFieldPanel([ | |
FieldPanel('slug'), | |
FieldPanel('seo_title'), | |
FieldPanel('search_description'), | |
FieldPanel('custom_metadata') | |
], _('For search engines and other METAs'), classname="collapsible"), | |
] | |
edit_handler = TabbedInterface( | |
[ | |
ObjectList(content_panels, heading='Main Section'), | |
ObjectList(form_fields_panels, heading="Form Fields Section"), | |
ObjectList(promote_panels, heading='SEO'), | |
ObjectList(Page.settings_panels, heading='Other Settings'), | |
] | |
) | |
def get_admin_display_title(self): return f"{self.title} ({self.slug}) Form" | |
def get_uploaded_image_collection(self): | |
""" Returns a Wagtail Collection, using this form's saved value if present, | |
otherwise returns the 'Root' Collection. | |
""" | |
collection=self.uploaded_image_collection | |
return collection or Collection.get_first_root_node() | |
@staticmethod | |
def get_image_title(filename): | |
return filename | |
def get_submission_class(self): | |
return HHFormSubmission | |
def process_form_submission(self, form): | |
""" Customized Processes the form submission """ | |
from django.contrib.auth import get_user_model | |
user = get_user_model() | |
cleaned_data=form.cleaned_data | |
for name, field in form.fields.items(): | |
if isinstance(field, WagtailImageField): | |
image_file_data=cleaned_data[name] | |
if image_file_data: | |
ImageModel=get_image_model() | |
kwargs={ | |
'file': cleaned_data[name], | |
'title': self.get_image_title(cleaned_data[name].name), | |
'collection': self.get_uploaded_image_collection(), | |
} | |
if form.user and not form.user.is_anonymous: | |
kwargs['uploaded_by_user']=form.user | |
else: | |
kwargs['uploaded_by_user']=user.objects.get(id=8) | |
image=ImageModel(**kwargs) | |
image.save() | |
cleaned_data.update({name: image.pk}) | |
else: | |
del cleaned_data[name] | |
submission=self.get_submission_class().objects.create(form_data=cleaned_data,page=self) | |
if self.to_address: | |
self.send_mail(form) | |
return submission | |
def get_form_fields(self): | |
fields = list(super().get_form_fields()) | |
fields.insert(1000, FormField(label='I am not a Human',field_type='singleline',required=False,help_text="Only fill this field if you are not a human")) | |
return fields | |
class Meta: | |
verbose_name="Form" | |
# verbose_name_plurer="Forms" | |
class FormField(AbstractFormField): | |
field_type=models.CharField(verbose_name='field type',max_length=16,choices=list(FORM_FIELD_CHOICES) + [('image', 'Upload Image'), ] ) # todo ('user', 'submited by'), | |
page=ParentalKey('base.FormPage', related_name='form_fields', on_delete=models.CASCADE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment