On May 5, 9:30 pm, Paul <pwar...@gmail.com> wrote:
> I have the following model (stripped of comments and __unicode__ for
> brevity) which defines  a comment in my Django app (I'm not using the
> comment module provided with Django for various reasons):
>
> class Comment(models.Model):
>   comment = models.TextField()
>   added_by = models.ForeignKey(User)
>   added_date = models.DateTimeField(auto_now_add = True)
>   approved = models.BooleanField()
>
> class CommentForm(ModelForm):
>   class Meta:
>     model = Comment
>     fields = ['comment']
>
> I also have a simple template which just displays the CommentForm
> (i.e. a textarea within a form element) and the action of the form is
> set to the following view:
>
> def add_comment(request):
>   if request.method == 'POST' and request.user.is_authenticated():
>     comment = Comment()
>     comment.added_by = request.user
>     comment.approved = False
>
>     comment_form = CommentForm(request.POST, instance = comment)
>
>     if comment_form.is_valid():
>       comment.save()
>       return HttpResponseRedirect('/')
>
> However, when I submit the form I get the following error:
>
> (1048, "Column 'added_by_id' cannot be null")
>
> I'm sure request.user must be set, because it is being accessed
> earlier in the code (request.user.is_authenticated), so I'm not sure
> why this error is appearing. Am I doing something obviously wrong? I'm
> new to both Django and Python so I am picking things up as I go along.
>
> Thanks in advance for any pointers.

What's probably happening is that because you're instantiating the
object first, then passing it to the form, the form is overwriting all
the attributes. There are two ways of fixing this: either exclude the
added_by field in the form Meta class:
  exclude = ('added_by',)
or, and this is probably better, set the added_by and approved fields
when you come to save:
    if comment_form.is_valid():
      comment.save(commit=False)
      comment.added_by = request.user
      comment.approved = False
      comment.save()
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to