Reputation: 1324
I have built a form for posting using Ajax, however, when I click on the submit button i get the error:
django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id
I do not know what this is as before I had a separate html for creating posts but after using Ajax I am getting this error.
This is my Post Model:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(validators=[MaxLengthValidator(250)])
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
date_posted = models.DateTimeField(auto_now_add=True)
last_edited= models.DateTimeField(auto_now=True)
likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes')
This is my post form:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title','content',)
This is my create_post view:
@login_required
def post_create(request):
data = dict()
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
data['form_is_valid'] = True
posts = Post.objects.all()
data['posts'] = render_to_string('home/homepage/home.html',{'posts':posts})
else:
data['form_is_valid'] = False
else:
form = PostForm
context = {
'form':form
}
data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request)
return JsonResponse(data)
This is my Ajax Javascript code:
$(document).ready(function(){
var ShowForm = function(){
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType:'json',
beforeSend: function(){
$('#modal-post').modal('show');
},
success: function(data){
$('#modal-post .modal-content').html(data.html_form);
}
});
};
var SaveForm = function(){
var form = $(this);
$.ajax({
url: form.attr('data-url'),
data: form.serialize(),
type: form.attr('method'),
dataType: 'json',
success: function(data){
if(data.form_is_valid){
$('#post-list div').html(data.posts);
$('#modal-post').modal('hide');
} else {
$('#modal-post .modal-content').html(data.html_form)
}
}
})
return false;
}
//create
$('.create-post-btn').click(ShowForm);
$('#modal-post').on("submit",".post-create-form",SaveForm)
//update
$('#post-list').on("click",".show-form-update",ShowForm);
$('#modal-post').on("submit",".update-form",SaveForm)
//delete
$('#post-list').on("click",".show-form-delete",ShowForm);
$('#modal-post').on("submit",".delete-form",SaveForm)
});
I do not know what is causing this error as everything seems right to me.
Upvotes: 0
Views: 1239
Reputation: 412
In the model of Post, the author is not null. But in the view, you didn't set the author before saving the form.
You can add an existed author id to post in the view.
post = form.save(False)
post.author = author_id
post.save()
Upvotes: 1