Django ModelForm没有保存到数据库

时间:2018-01-29 00:55:47

标签: python django database model

我是Django的新手。我正在尝试将表单保存到数据库。它不会显示任何错误,但不会将其保存到数据库中。任何帮助将不胜感激!

这是我的代码:

models.py

class Estate(models.Model):
    type = models.CharField(max_length=100)
    net_area = models.CharField(max_length=10)
    total_area = models.CharField(max_length=10)
    price = models.CharField(max_length=10)
    cep = models.CharField(max_length=8)
    state = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    neighborhood = models.CharField(max_length=30)
    street = models.CharField(max_length=250)
    number = models.CharField(max_length=10)
    complement = models.CharField(max_length=100)
    rooms = models.CharField(max_length=3)
    suits = models.CharField(max_length=3)
    parking_spots = models.CharField(max_length=3)
    bathrooms = models.CharField(max_length=3)
    description = models.CharField(max_length=1000)
    logo = models.FileField()

    def get_absolute_url(self):
        return reverse('register:create2')

    def __str__(self):
        return self.type + ' ' + self.neighborhood

views.py

class CreateView1 (TemplateView):
    template_name = 'register/estate_form1.html'

    def get(self, request):
        form1 = AddForm()
        return render(request, self.template_name, {'form1': form1})
    def post(self, request):
        form1 = AddForm(request.POST)
        text = None
        if form1.is_valid():
            text = form1.cleaned_data()
            form1.save()
        args = {'form1': form1, 'text':text}
        return render(request, self.template_name, args)

forms.py

class AddForm(forms.ModelForm):

    class Meta:
    model = Estate
    fields = ('type','net_area','total_area','price','cep','state','city','neighborhood','street','number','complement','rooms','suits','parking_spots','bathrooms','description','logo')

1 个答案:

答案 0 :(得分:1)

if form1.is_valid():
        text = form1.cleaned_data()
        form1.save()

将其更改为:

if form1.is_valid():
         instance = form1.save(commit=False)
         text = form1.cleaned_data()
         instance.save()

要保存对象,您需要保存实例对象,而不是表单。

我也看到你有文件字段。文件位于request.FILES而不是request.POST

form1 = AddForm(request.POST)更改为form1 = AddForm(request.POST, request.FILES)