Last active
June 15, 2024 18:07
-
-
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
This file contains 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 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}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about if the form is invalid