Python 插入数据库Django时出错

Python 插入数据库Django时出错,python,django,Python,Django,我有一个新的问题,当我在数据库中插入新闻时,它添加了但没有区域。如何插入具有正确区域的注释 以下是我的看法: def index_region(request,region): try: actuCommentaire = Actu.objects.get(region=region) except ObjectDoesNotExist: actuTempo = Actu(region=region) actuCommentaire

我有一个新的问题,当我在数据库中插入新闻时,它添加了但没有区域。如何插入具有正确区域的注释

以下是我的看法:

def index_region(request,region):
    try:
        actuCommentaire = Actu.objects.get(region=region)
    except ObjectDoesNotExist:
        actuTempo = Actu(region=region)
        actuCommentaire = actuTempo.commentaire

    form = UpdateActu(request.POST or None, instance=actuCommentaire)

    if form.is_valid():
        form.save()
        return redirect('index.html')
这是我的模型“Actu”:

这是我的表格:

class UpdateActu(forms.ModelForm):
    class Meta:
        model = models.Actu
        fields = ['commentaire']
        widgets = {
            'commentaire': forms.Textarea(attrs={'class': 'form-control', 'id': 'exampleTextarea', 'rows': '2'})
        }
以下是插入数据库时的结果:


我找到了解决这个问题的方法

以下是我的新观点:

try:
    actuCommentaire = Actu.objects.get(region=region)
except ObjectDoesNotExist:
    actuTempo = Actu(region=region)
    actuCommentaire = actuTempo.commentaire

form = UpdateActu(request.POST or None, instance=actuCommentaire)

if form.is_valid():
    if Actu.objects.filter(region=region).count() == 0:
        formActu = Actu(commentaire=request.POST['commentaire'], region=region)
        formActu.save()
    else:
        form.save()
    return redirect('index.html')

您的
区域
是字符串吗?通常我会说,我们用一个
区域
模型来建模。你能解释一下你是如何在这里插入值的吗?有一点很奇怪。在区域上执行
.get(..)
。但这意味着您的视图假设
区域
s是唯一的​​使用仅包含“注释”字段的表单。我想要写“评论”的人,以及何时使用函数中的参数验证“评论”的插入和“评论”的区域。是的,但现在我们无法访问该表单,等等。因此,共享表单和您提出的POST请求可能是件好事。
try:
    actuCommentaire = Actu.objects.get(region=region)
except ObjectDoesNotExist:
    actuTempo = Actu(region=region)
    actuCommentaire = actuTempo.commentaire

form = UpdateActu(request.POST or None, instance=actuCommentaire)

if form.is_valid():
    if Actu.objects.filter(region=region).count() == 0:
        formActu = Actu(commentaire=request.POST['commentaire'], region=region)
        formActu.save()
    else:
        form.save()
    return redirect('index.html')