Django ModelForm一些字段未保存

时间:2019-07-20 00:25:10

标签: django forms model

我在Django中使用ModelForm,但是某些字段未保存到数据库中...

models.py文件


from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.forms import ModelForm

# Create your models here.
class Bill(models.Model):
    image_name = models.CharField(max_length=150)
    upload_date = models.DateTimeField(default=timezone.now)
    image = models.ImageField()
    description = models.TextField(blank=True)
    result = models.CharField(max_length=1000)
    uploaded_by = models.OneToOneField(User, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return  str(self.result + self.description)

forms.py文件


from django import forms
from django.db import models
from django.forms import ModelForm
from .models import Bill

class BillForm(ModelForm):
    class Meta:
        model = Bill
        fields = ['image', 'description']
        exclude = ['result', 'image_name', 'upload_date', 'uploaded_by']

views.py文件

def upload(request):
    if request.method == 'POST':
        form = BillForm(request.POST, request.FILES)

        if form.is_valid():
            form.image_name = request.FILES['image']
            form.upload_date = datetime.now()
            form.uploaded_by = request.user
            form.result  = "something"
            form.save()
            return redirect('cism-home')
    else:
        form = BillForm()
    return render(request, 'auth/upload.html', {'form': form})

因此,将保存图像和说明字段,但未保存其他字段。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

您的表单不包括某些字段,因此您不能使用以下方式“访问”这些字段: 例如form.upload_date,因为它们不存在。

您可以做的是:

if form.is_valid():
    bill = form.save(commit=False)
    bill.image_name = request.FILES['image']
    bill.upload_date = datetime.now()
    bill.uploaded_by = request.user
    bill.result  = "something"
    bill.save()

如果您想快速了解“ commit = False”的操作,可以检查:

Django ModelForm: What is save(commit=False) used for?