Note that there are some explanatory texts on larger screens.

plurals
  1. POcan't override default admin model form django
    primarykey
    data
    text
    <p>I need to add extra validation to my DateField in Admin to make sure the date given is in the future. I have no experience in such a thing, so here's what I've done. 1) I've created custom form field and added validation to it:</p> <pre><code>class PastDateField(forms.DateField): def clean(self, value): """Validates if only date is in the past """ if not value: raise forms.ValidationError('Plase enter the date') if value &gt; datetime.now(): raise forms.ValidationError('The date should be in the past, not in future') return value </code></pre> <p>2) Then I've added custom model form:</p> <pre><code>class CustomNewsItemAdminForm(forms.ModelForm): title = forms.CharField(max_length=100) body = forms.CharField(widget=forms.Textarea) date = PastDateField() region = forms.ModelChoiceField(Region.objects) </code></pre> <p>3) And here's how I've registered admin:</p> <pre><code>class NewsItemAdmin(admin.ModelAdmin): form = CustomNewsItemAdminForm def queryset(self, request): return NewsItem.objects.all() admin.site.register(NewsItem, NewsItemAdmin) </code></pre> <p>The result of this is that my admin form 1) Shows field I haven't specified in custom admin form 2) Lacks JavaScript calendar for the datetime field</p> <p>It's pretty obvious to me that I'm doing something wrong, but I've found no examples relevant to my needs as I am a noob. What is the better way to add custom validation to datetime field without messing things up?</p> <p><strong>EDIT</strong>: Thanks a lot to Brian Luft and Daniel Roseman for correct answers! To make this post helpful for someone facing the same problem here is the resulting code:</p> <pre><code>class CustomNewsItemAdminForm(forms.ModelForm): class Meta: model = NewsItem def clean_date(self): """Validates if only date is in the past """ date = self.cleaned_data["date"] if date is None: raise forms.ValidationError('Plase enter the date') if date &gt; datetime.now().date(): raise forms.ValidationError('The date should be in the past, not in future') return self.cleaned_data["date"] class NewsItemAdmin(admin.ModelAdmin): form = CustomNewsItemAdminForm def queryset(self, request): return NewsItem.objects.all() admin.site.register(NewsItem, NewsItemAdmin) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload