1

I'm using a ModelForm in Django but some fields are not saved to the database...

models.py file


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 file


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 file

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})

So the image and description fields are saved but other fields are not. Any ideas why is that?

Saeed Alijani
  • 313
  • 2
  • 13

1 Answers1

0

Your form is excluding some fields, so you can't "access" those fields using: form.upload_date (for example), because they don't exists.

What you can do is:

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()

If you want a quick description about what "commit=False" do, you can check:

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

  • Thanks it works :D any ideas why I get Integrityerrorr with uploaded_by field? – iLoveMental Jul 20 '19 at 01:19
  • I think it's because you have "upload_by" with OneToOneField, this means that a User can upload only 1 bill. Maybe you want to change that to ForeignKey. You can check it here: https://stackoverflow.com/questions/5870537/whats-the-difference-between-django-onetoonefield-and-foreignkey Or provide me a better description of the error – Jean Duanner Marticorena Rios Jul 20 '19 at 01:24