[Answered ]-The Post could not be created because the data didn't validate – ( When i set past time in form field )

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
πŸ‘€NKSM

Leave a comment