Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davemerwin/37f1a4838a64759c3d2ed77ac1b5ff02 to your computer and use it in GitHub Desktop.
Save davemerwin/37f1a4838a64759c3d2ed77ac1b5ff02 to your computer and use it in GitHub Desktop.
An example of a Class Based View using django-htmx to determine what template to return
class AddImage(LoginRequiredMixin, CreateView):
"""
adds a image
"""
form_class = ImageForm
model = Image
def get_template_names(self):
if self.request.htmx:
return ["images/htmx-add.html"] # The response HTML to inject into a list
else:
return ["images/add.html"] # The actual form
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.owner = self.request.user
self.object.save()
messages.add_message(self.request, messages.SUCCESS,
'Your image has been added!')
if self.request.htmx:
context = {'image': self.object}
return render(self.request, 'images/htmx-add.html', context)
else:
return reverse('image_detail', kwargs={'pk': self.object.id})
@ubongpr7
Copy link

What about if the form is invalid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment