I am trying to change a form’s instance before I save it. I need to set certain information within the view like this:
class UploadedFile(models.Model):
file = models.FileField(storage=s3store, upload_to=custom_upload_to)
slug = models.SlugField(max_length=50, blank=True)
bucket = models.ForeignKey(S3Bucket, blank=False)
uploaded_by = models.ForeignKey(User, related_name='uploaded_by', blank=False)
company = models.ForeignKey(Company, blank=False)
—
class UploadForm(ModelForm):
class Meta:
model = UploadedFile
—
form = UploadForm(request.POST, request.FILES)
form.instance.company_id = r_user.company.id
form.instance.uploaded_by_id = r_user.id
form.instance.bucket_id = r_user.company.s3_bucket_id
if form.is_valid():
form_object = form.save()
Now, I get that the form is not valid because company/uploaded/bucket are empty:
Errors Form:
But I did set them! Do I need to make them blank=True, then do a save(commit=false), change them, and then resave? If yes, why is so? I did change the form ….
The assignments are late. In the
__init__()ofModelForm, or in your code: theform = UploadForm(request.POST, request.FILES)line, an instance has been created and populated toinitialof the form. Later modification upon the instance will not affect the value ofform.initial.Also, if you want to fill in some fields automatically in backend, don’t render them to user.
Thus, yes, you could make them
blank=Trueor exclude them from the form then follow the suggested way.