sFishman
sFishman

Reputation: 133

Adding a value to a database field that is in your model but is not in your form

I have a model with a property called authID that looks like this: authID = models.CharField(max_length=400) In my view, all of the fields that are in my form get put into the database as follows:

if request.method == 'POST':
  form = PersonalDetailsModelForm(request.POST)
  if form.is_valid():
     form.save()

What I want to know how to do is that when they submit the form, I want to also put the value of authID into my database. However, authID is not a field in my form. I don't want to make it a hidden field either for security reasons. How do you add a value to a database field that is in your model, but is not in your form?

Upvotes: 0

Views: 32

Answers (2)

JPG
JPG

Reputation: 88499

Call the save() method of Django Form with commit=False

#views.py
if request.method == 'POST':
    form = PersonalDetailsModelForm(request.POST)
    if form.is_valid():
        model_instance = form.save(commit=False) # 'commit=False' plays key role here
        model_instance.authID = 'your auth id'
        model_instance.save()
        ...

Reference

  1. Django model form save() method

Upvotes: 1

solarissmoke
solarissmoke

Reputation: 31404

You can override the save() method on PersonalDetailsModelForm to set this value before saving the instance:

def save(self, commit=True):
    self.instance.authID = 'some_value'   # Set the auth ID
    return super().save(commit=commit)

If the authID is coming from your view, then you can pass that as a keyword argument to your overridden save() method.

Upvotes: 1

Related Questions