开发者

Why won't foreign key save on ModelForm(1048, "Column 'post_id' cannot be null")

开发者 https://www.devze.com 2023-02-18 05:40 出处:网络
This should be a simple problem, but it\'s been weighing me down for a while now. I want to save a modelform but I keep getting the above error.

This should be a simple problem, but it's been weighing me down for a while now.

I want to save a modelform but I keep getting the above error.

class Favorite(models.Model):
    post=models.ForeignKey(Post)
      user=models.ForeignKey(User)  
    note=models.TextField(max_length=1000, blank=True)


def listing(request, pid):
    post=get_object_or_404(Post,pk=pid)
    favform=F开发者_如何学JAVAavoriteForm()
     try:
        ratings=post.post_rating_set.all()
        score=ratings.aggregate(mark=Avg('rating'))
         score=int(score.get('mark',0))-1 
    except AttributeError:
            ratings=''
            score=1000 
    if request.method=="POST" and request.POST.get('save_it',''):
        user=User.objects.get(pk=request.user.id)
        favorite=FavoriteForm(request.POST)
        if favorite.is_valid:

            favorite.save(commit=False)
            favorite.user=user
            favorite.post=post

            favorite.save()

My form validates, I've tested both user and post and they both contain the intended querysets. I tried not saving the favorite form first but that failed as well. m2m isn't appropriate here.

Is this a mysql set up error?


You are using commit=False incorrectly. save() returns an instance, and you are just calling save on a form twice.

Do this instead:

        favorite = favorite.save(commit=False) 
        # now, favorite is an instance returned by save.
        favorite.user=user
        favorite.post=post
        favorite.save()

I'd personally name the form favoriteform to distinguish between instance and form as well.


You can put the decorator before the method declaration.

@transaction.commit_on_success
def listing(request, pid):
    post=get_object_or_404(Post,pk=pid)
    ...

and remove this line:

favorite.save(commit=False)
0

精彩评论

暂无评论...
验证码 换一张
取 消