Custom validation in Django admin

假装没事ソ 提交于 2020-08-21 01:55:09

问题


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 ??


回答1:


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.




回答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.




回答3:


def clean(self): 
   if self.database_name != '111':
      raise ValidationError("You can use only letters ,numbers and 
      underscores.")

This clean method works perfect for me in django admin



来源:https://stackoverflow.com/questions/24802244/custom-validation-in-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!