mercredi 15 février 2017

Django: Error when creating objects using from

I'v been trying to use form to insert comment. When user type comment it gets article number, username, and comment body and redirect to the previous paHowever It keeps display error message, and I couldn't find exactly which part I missed.

This is model.py

class Comment(models.Model):
article_no = models.IntegerField(default=1)
comment_no = models.AutoField(primary_key=True)
comment_writer = models.CharField(max_length=50)
comment_body = models.CharField(max_length=300)
comment_date = models.DateTimeField(editable=False, default=datetime.now())

forms.py

class CommentForm(forms.ModelForm):

class Meta:
    model = Comment
    fields = ['article_no', 'comment_body', 'comment_writer']

view.py

@login_required
def comment(request, article_no):
user = request.user
request.session['username'] = user.username
if 'username' is None:
    return render(request, 'blog/home.html')
else:

    if request.POST.has_key('comment_body') == False:
        return HttpResponse('comment is none')
    else:
        if len(request.POST['comment_body']) == 0:
            return HttpResponse('comment is none')
        else:
            comment_body = request.POST['comment_body']
            print(comment_body)

    if request.POST.has_key('comment_writer') == False:
        return HttpResponse('writer is none')
    else:
        if len(request.POST['comment_writer']) == 0:
            return HttpResponse('comment is none')
        else:
            comment_writer = request.POST['comment_writer']
            print(comment_writer)

    try:        

            instance = CommentForm(Comment_body=comment_body, Comment_writer=comment_writer, Article_no=article_no)
            instance.save()
            instance.Comment += 1
            instance.save()
            #return HttpResponse('comment added')
            item = get_object_or_404(Article, pk=article_no)

            return render(request, 'blog/detail.html', {'item': item})

    except:
        print("A")
        return HttpResponse('error')
    print("B")
return HttpResponse('error')

urls.py

url(r'^comment/(?P<article_no>[0-9]+)/$', views.comment, name='comment'),




Aucun commentaire:

Enregistrer un commentaire