问题
I am building a BlogApp and I am stuck on an Error and I keep getting this error :-
The Post could not be created because the data didn't validate.
What i am trying to do
I made a feature that users cannot insert past date in DateTimeField
. AND If user enters the past date in field then a Validation Error
should be display. AND i was testing it and suddenly a new error is occured.
forms.py
class PostForm(forms.ModelForm):
date = forms.DateTimeField(initial=timezone.now)
def clean_date(self):
date = self.cleaned_data['date']
if date.date() < datetime.date.today():
raise forms.ValidationError("The date cannot be in the past!")
return date
views.py
def new__blog_post(request,user_id):
if request.method != 'POST':
form = PostForm()
else:
form = PostForm(request.POST,request.FILES)
new_post = form.save()
new_post.post_owner = request.user
new_post.save()
return redirect('mains:posts',user_id=user_id)
context = {'form':form,'posts':posts}
return render(request, 'new_blog_post.html', context)
models.py
class BlogPost(models.Model):
post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)
post_title = models.CharField(max_length=500,default='')
date_added = models.DateTimeField(null=True,default=timezone.now)
It is showing that the Error is in new_post = form.save()
line . It means that there's having problem in saving form.
The Problem
When i set the time of now
( as timezone.now as default ) in DateTimeField
then it is working fine , Post is saving fine. BUT when i change the present time (2021-02-18) into past time (2019-02-18
) then it is showing that error The Post could not be created because the data didn't validate
.
I don't know what am i doing wrong
Any help would be appreciated.
Thank You in Advance
回答1:
To validate data you need to call Form.is_valid()
. See Using forms to validate data.
So call first is_valid()
:
def new__blog_post(request,user_id):
if request.method == 'POST':
form = PostForm(request.POST,request.FILES)
if form.is_valid():
new_post = form.save()
new_post.post_owner = request.user
new_post.save()
return redirect('mains:posts',user_id=user_id)
else:
form = PostForm()
context = {'form':form}
return render(request, 'new_blog_post.html', context)
The name of clean method must be changed - forms.py:
from django.core.exceptions import ValidationError
import datetime
class PostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ["post_title","date_added"]
def clean_date_added(self):
date_added = self.cleaned_data['date_added']
if date_added.date() < datetime.added.today():
raise forms.ValidationError("The date cannot be in the past!")
return date_added
来源:https://stackoverflow.com/questions/66265246/the-post-could-not-be-created-because-the-data-didnt-validate-when-i-set-pa