Reputation: 575
I have a simple snippet using Django Wagtail. I would like to be able to update the logo from a "CreateView" but when it renders in my view it's expecting a foreign key. I would imagine it would be easy to create a from to do this but it's not.
@register_snippet
class MerchantSnippet(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, unique=True)
logo = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
panels =[
FieldPanel('name'),
ImageChooserPanel('logo'),
]
edit_handler = TabbedInterface([
ObjectList(panels, heading='Content'),
])
class ProductCreateView(CreateView):
model = ProductSnippet
fields = ['name','logo']
class ProductUpdateView(UpdateView):
model = ProductSnippet
fields = ['name','logo']
When I use the default example in the template I ended up just getting a drop down.
{% render_field field class+="form-control" %}
How would I be able to see an image preview in the event I am updating the snippet and the ability to upload a different one . In the event I am creating a new item the ability to select an upload an image.
Upvotes: 0
Views: 445
Reputation: 11228
The logo
field is a foreign key and points to Wagtail Image. Therefore it is a select. If you change the logo
field to a ImageField you probably have the behaviour you desire. However, uploaded logos will not appear in the Wagtail Images. That ain't a bad thing. Whenever you want to display a logo, you'd just use the Merchant snippet.
If storing the logo as a Wagtail Image is a must, there are two alternatives:
Alternative 1: Custom form
CreateView
and UpdateView
are Django generic views and inherit the FormMixin. This means you can specify a custom form_class
. Create a custom form with a logo = ImageField(...)
and on submit, handle the image data, create a Wagtail Image, and store the Wagtail Image pk on the snippet.
Alternative 2: Multiple forms
Django can handle multiple forms inside a single form tag with a prefix to avoid field name collisions. So you can present both the snippet and the Wagtail image within the same view.
Note: @register_snippet
is needed for Wagtail to display CRUD views and enable the snippet chooser in the Wagtail admin interface. But a snippet is a regular Django model. Wagtail Image is a regular Django model too. Forms and generic views are also pure Django concepts. If you dive into this some more, leave Wagtail out of your search queries.
Upvotes: 1