Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Form Instance Django before Save

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:

  • company
  • This field is required.
  • bucket
  • This field is required.
  • uploaded_by
  • This field is required.
  • 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 ....

    like image 212
    abisson Avatar asked May 02 '26 12:05

    abisson


    2 Answers

    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.

    like image 66
    Darwin Avatar answered May 05 '26 08:05

    Darwin


    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.

    like image 25
    okm Avatar answered May 05 '26 09:05

    okm



    Donate For Us

    If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!