Shobi
Shobi

Reputation: 11461

Django CreateView Not Working as expected

I have the following CreateView

class CreateEmailTemplateView(CreateView):

   template_name = 'frontend/emailtemplates/create.html'
   model = Templates
   fields = '__all__'

   def form_valid(self, form):
      form.instance.user = self.request.user
      return super(CreateEmailTemplateView, self).form_valid(form)

And the Templates model looks like this

class Templates(models.Model):
    name = models.CharField(max_length=128)
    template = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

But when I submit the form it doesn't persist it in the database nor I see any error messages, it simply redirects to the same page, The form method is POST

What am I missing? How can I show some error/success message after the form submission ?

Upvotes: 1

Views: 1642

Answers (1)

Bendeberia
Bendeberia

Reputation: 116

form_valid is called when valid form data has been POSTed. Could you please check if your data is valid? You can also add logging into your form_valid method to make sure you reach it:

import logging


logger = logging.getLogger(__name__)


class CreateEmailTemplateView(CreateView):

    template_name = 'frontend/emailtemplates/create.html'
    model = Templates
    fields = '__all__'

    def form_valid(self, form):
        logger.info('form_valid called')
        form.instance.user = self.request.user
        return super(CreateEmailTemplateView, self).form_valid(form)

Upvotes: 1

Related Questions