表单不保存 - form.is_valid()返回false

时间:2017-11-16 12:52:47

标签: django django-forms

以下是我的所有型号。基本上这是一个拍卖网站

class Item(models.Model):

    name = models.CharField(max_length = 30)
    description = models.TextField()
    image = models.ImageField(upload_to='media/')
    category = models.CharField(max_length=100)
    ask = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)
    closes = models.DateTimeField()

class Bid(models.Model):
    item = models.ForeignKey(Item)
    user = models.ForeignKey(User)
    price = models.DecimalField(default=0, max_digits=6, decimal_places=2)
    created_at = models.DateTimeField(default=datetime.now, blank=True)

这是表格:

class itemform(ModelForm):
    class Meta:
        model = Item
        fields =['name','description','image','category','ask','closes']

保存表单的视图:

def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return redirect('/items') 
    else:    
        form = itemform()
        return render(request, 'app/create.html', {'form':form})

create.html上

{% extends 'app/layout.html' %}
{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p}}
        <button type ="submit">Save</button>
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

您应该稍微更改视图,以便仅在表单有效时重定向。当表单无效时,您应该重新呈现表单。

def createitem(request):
    if request.method == "POST":
        form= itemform(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/items') 
    else:    
        form = itemform()
    return render(request, 'app/create.html', {'form':form})

这样,您将看到表单的错误消息,这可以帮助您找出问题所在。