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 ....
Try this:
data = request.POST.copy()
data['company_id'] = r_user.company.id
data['uploaded_by_id'] = r_user.id
data['bucket_id'] = r_user.company.s3_bucket_id
form = UploadForm(data, request.FILES)
if form.is_valid():
form_object = form.save()
This way you are setting the data before creating the form.
The assignments are late. In the __init__() of ModelForm, or in your code: the form = UploadForm(request.POST, request.FILES) line, an instance has been created and populated to initial of the form. Later modification upon the instance will not affect the value of form.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=True or exclude them from the form then follow the suggested way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With