Custom validation in Django admin












27















I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:



#models.py
from django.db import models

class Lecture(models.Model):
topic = models.CharField(max_length=100)
speaker = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField()


I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:



#admin.py
from models import Lecture
from django.contrib import admin
from django import forms


class LectureForm(forms.ModelForm):
class Meta:
model = Lecture

def clean(self):
start_date = self.cleaned_data.get('start_date')
end_date = self.cleaned_data.get('end_date')
if start_date > end_date:
raise forms.ValidationError("Dates are incorrect")
return self.cleaned_data


class LectureAdmin(admin.ModelAdmin):
form = LectureForm
list_display = ('topic', 'speaker', 'start_date', 'end_date')

admin.site.register(Lecture, LectureAdmin)


However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:enter image description here



What am I doing wrong ??










share|improve this question





























    27















    I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:



    #models.py
    from django.db import models

    class Lecture(models.Model):
    topic = models.CharField(max_length=100)
    speaker = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()


    I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:



    #admin.py
    from models import Lecture
    from django.contrib import admin
    from django import forms


    class LectureForm(forms.ModelForm):
    class Meta:
    model = Lecture

    def clean(self):
    start_date = self.cleaned_data.get('start_date')
    end_date = self.cleaned_data.get('end_date')
    if start_date > end_date:
    raise forms.ValidationError("Dates are incorrect")
    return self.cleaned_data


    class LectureAdmin(admin.ModelAdmin):
    form = LectureForm
    list_display = ('topic', 'speaker', 'start_date', 'end_date')

    admin.site.register(Lecture, LectureAdmin)


    However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:enter image description here



    What am I doing wrong ??










    share|improve this question



























      27












      27








      27


      6






      I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:



      #models.py
      from django.db import models

      class Lecture(models.Model):
      topic = models.CharField(max_length=100)
      speaker = models.CharField(max_length=100)
      start_date = models.DateField()
      end_date = models.DateField()


      I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:



      #admin.py
      from models import Lecture
      from django.contrib import admin
      from django import forms


      class LectureForm(forms.ModelForm):
      class Meta:
      model = Lecture

      def clean(self):
      start_date = self.cleaned_data.get('start_date')
      end_date = self.cleaned_data.get('end_date')
      if start_date > end_date:
      raise forms.ValidationError("Dates are incorrect")
      return self.cleaned_data


      class LectureAdmin(admin.ModelAdmin):
      form = LectureForm
      list_display = ('topic', 'speaker', 'start_date', 'end_date')

      admin.site.register(Lecture, LectureAdmin)


      However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:enter image description here



      What am I doing wrong ??










      share|improve this question
















      I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:



      #models.py
      from django.db import models

      class Lecture(models.Model):
      topic = models.CharField(max_length=100)
      speaker = models.CharField(max_length=100)
      start_date = models.DateField()
      end_date = models.DateField()


      I need to ensure that nobody enters the start date after the end date in the admin forms,so I read the django docs for custom validation in the admin and implemented the following in my admin.py:



      #admin.py
      from models import Lecture
      from django.contrib import admin
      from django import forms


      class LectureForm(forms.ModelForm):
      class Meta:
      model = Lecture

      def clean(self):
      start_date = self.cleaned_data.get('start_date')
      end_date = self.cleaned_data.get('end_date')
      if start_date > end_date:
      raise forms.ValidationError("Dates are incorrect")
      return self.cleaned_data


      class LectureAdmin(admin.ModelAdmin):
      form = LectureForm
      list_display = ('topic', 'speaker', 'start_date', 'end_date')

      admin.site.register(Lecture, LectureAdmin)


      However,this has no effect whatsoever on my admin and I am able to save lectures where start_date is after end_date as seen in the image:enter image description here



      What am I doing wrong ??







      python django django-forms django-admin django-validation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 12 '17 at 18:29









      rynmrtn

      1,89632136




      1,89632136










      asked Jul 17 '14 at 11:25









      AmistadAmistad

      2,74472639




      2,74472639
























          2 Answers
          2






          active

          oldest

          votes


















          20














          You have an indentation issue. Your clean method is indented within the form's Meta class. Move it back one level. Also, ensure that the return statement is indented within the method.






          share|improve this answer
























          • that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

            – Amistad
            Jul 17 '14 at 11:36






          • 1





            @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

            – bruno desthuilliers
            Jul 17 '14 at 11:48











          • hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

            – Amistad
            Jul 17 '14 at 11:54






          • 1





            You can define the get_changelist_form method to return a custom form to use there.

            – Daniel Roseman
            Jul 17 '14 at 12:37






          • 1





            Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

            – jobima
            Jun 30 '16 at 11:28



















          2














          Usually you just want to define a clean() method on the model itself.



          https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects



          from django.core.exceptions import ValidationError

          class Lecture(models.Model):
          topic = models.CharField(max_length=100)
          speaker = models.CharField(max_length=100)
          start_date = models.DateField()
          end_date = models.DateField()

          def clean(self):
          if self.start_date > self.end_date::
          raise ValidationError("Dates are incorrect")


          Something like that will work in the django admin without any need to create a form class.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24802244%2fcustom-validation-in-django-admin%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            20














            You have an indentation issue. Your clean method is indented within the form's Meta class. Move it back one level. Also, ensure that the return statement is indented within the method.






            share|improve this answer
























            • that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

              – Amistad
              Jul 17 '14 at 11:36






            • 1





              @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

              – bruno desthuilliers
              Jul 17 '14 at 11:48











            • hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

              – Amistad
              Jul 17 '14 at 11:54






            • 1





              You can define the get_changelist_form method to return a custom form to use there.

              – Daniel Roseman
              Jul 17 '14 at 12:37






            • 1





              Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

              – jobima
              Jun 30 '16 at 11:28
















            20














            You have an indentation issue. Your clean method is indented within the form's Meta class. Move it back one level. Also, ensure that the return statement is indented within the method.






            share|improve this answer
























            • that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

              – Amistad
              Jul 17 '14 at 11:36






            • 1





              @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

              – bruno desthuilliers
              Jul 17 '14 at 11:48











            • hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

              – Amistad
              Jul 17 '14 at 11:54






            • 1





              You can define the get_changelist_form method to return a custom form to use there.

              – Daniel Roseman
              Jul 17 '14 at 12:37






            • 1





              Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

              – jobima
              Jun 30 '16 at 11:28














            20












            20








            20







            You have an indentation issue. Your clean method is indented within the form's Meta class. Move it back one level. Also, ensure that the return statement is indented within the method.






            share|improve this answer













            You have an indentation issue. Your clean method is indented within the form's Meta class. Move it back one level. Also, ensure that the return statement is indented within the method.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 17 '14 at 11:27









            Daniel RosemanDaniel Roseman

            456k41591648




            456k41591648













            • that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

              – Amistad
              Jul 17 '14 at 11:36






            • 1





              @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

              – bruno desthuilliers
              Jul 17 '14 at 11:48











            • hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

              – Amistad
              Jul 17 '14 at 11:54






            • 1





              You can define the get_changelist_form method to return a custom form to use there.

              – Daniel Roseman
              Jul 17 '14 at 12:37






            • 1





              Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

              – jobima
              Jun 30 '16 at 11:28



















            • that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

              – Amistad
              Jul 17 '14 at 11:36






            • 1





              @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

              – bruno desthuilliers
              Jul 17 '14 at 11:48











            • hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

              – Amistad
              Jul 17 '14 at 11:54






            • 1





              You can define the get_changelist_form method to return a custom form to use there.

              – Daniel Roseman
              Jul 17 '14 at 12:37






            • 1





              Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

              – jobima
              Jun 30 '16 at 11:28

















            that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

            – Amistad
            Jul 17 '14 at 11:36





            that worked !!..and I almost spent 2 hours re reading the docs to get a fix for it !!..I had one more doubt..the validation error was thrown up only when i created a new entry.For the existing ones,they continued to be there..I am assuming that the clean() method is called only when a model is saved.How do i ensure that it is called every time the page loads ?

            – Amistad
            Jul 17 '14 at 11:36




            1




            1





            @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

            – bruno desthuilliers
            Jul 17 '14 at 11:48





            @Amistad The clean method is called only when the form is submitted, not "when the model is saved" (if that's what you want you're looking for model's validation: docs.djangoproject.com/en/1.7/ref/models/instances/…)... Which will still not validate your model instances "every time the page loads", but why would you want such a "feature" anyway ?

            – bruno desthuilliers
            Jul 17 '14 at 11:48













            hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

            – Amistad
            Jul 17 '14 at 11:54





            hmm..now that I think of it,all my changes to the model happen only via the admin through the form..so a validation check there should suffice..thanks..

            – Amistad
            Jul 17 '14 at 11:54




            1




            1





            You can define the get_changelist_form method to return a custom form to use there.

            – Daniel Roseman
            Jul 17 '14 at 12:37





            You can define the get_changelist_form method to return a custom form to use there.

            – Daniel Roseman
            Jul 17 '14 at 12:37




            1




            1





            Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

            – jobima
            Jun 30 '16 at 11:28





            Just in case it can help other people: Note that it's important to import "from django.forms import ValidationError" NOT "from django.core.exceptions import ValidationError"

            – jobima
            Jun 30 '16 at 11:28













            2














            Usually you just want to define a clean() method on the model itself.



            https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects



            from django.core.exceptions import ValidationError

            class Lecture(models.Model):
            topic = models.CharField(max_length=100)
            speaker = models.CharField(max_length=100)
            start_date = models.DateField()
            end_date = models.DateField()

            def clean(self):
            if self.start_date > self.end_date::
            raise ValidationError("Dates are incorrect")


            Something like that will work in the django admin without any need to create a form class.






            share|improve this answer




























              2














              Usually you just want to define a clean() method on the model itself.



              https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects



              from django.core.exceptions import ValidationError

              class Lecture(models.Model):
              topic = models.CharField(max_length=100)
              speaker = models.CharField(max_length=100)
              start_date = models.DateField()
              end_date = models.DateField()

              def clean(self):
              if self.start_date > self.end_date::
              raise ValidationError("Dates are incorrect")


              Something like that will work in the django admin without any need to create a form class.






              share|improve this answer


























                2












                2








                2







                Usually you just want to define a clean() method on the model itself.



                https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects



                from django.core.exceptions import ValidationError

                class Lecture(models.Model):
                topic = models.CharField(max_length=100)
                speaker = models.CharField(max_length=100)
                start_date = models.DateField()
                end_date = models.DateField()

                def clean(self):
                if self.start_date > self.end_date::
                raise ValidationError("Dates are incorrect")


                Something like that will work in the django admin without any need to create a form class.






                share|improve this answer













                Usually you just want to define a clean() method on the model itself.



                https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects



                from django.core.exceptions import ValidationError

                class Lecture(models.Model):
                topic = models.CharField(max_length=100)
                speaker = models.CharField(max_length=100)
                start_date = models.DateField()
                end_date = models.DateField()

                def clean(self):
                if self.start_date > self.end_date::
                raise ValidationError("Dates are incorrect")


                Something like that will work in the django admin without any need to create a form class.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 2 at 18:06









                arisaris

                10.9k11621




                10.9k11621






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24802244%2fcustom-validation-in-django-admin%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas

                    Can't read property showImagePicker of undefined in react native iOS