# How to automatically save values in the database

**URL:** <https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573>\
**Category:** Using Django\
**Created:** [January 14, 2022, 6:26am UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573 "2022-01-14T06:26:36Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![ggggg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ggggg/32/6969_2.png) [@ggggg](https://forum.djangoproject.com/u/ggggg)\
**Post date:** [January 14, 2022, 6:26am UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/1 "2022-01-14T06:26:36Z")

</div>

```auto
class resu_DB_Add(forms.ModelForm):
    class Meta:
        model = models.resu_DB
        fields = ["users","code",'masseg','creat_times',"updete_times"]

```

Currently I only know how to save what was sent from the form without processing.

```auto
The only step I know
1 render(request,'aaa.html', ｛'form': resu_DB_Add()｝)
2 <form action="{% url ' __________' %}" method="post">
3 form = resu_DB_Add(request.POST)
4 form.save()

```

However, when saving, the user cannot change it, and I want it to be set automatically.  
{users, code} These two are decided by your own system  
{‘creat\_times’, “updete\_times”} These two are timezone.now functions because they mark the time.  
I don’t know how to save the value decided by my system in resu\_DB\_Add

What I tried

```auto
    if (request.method == 'POST'):
        form = resu_DB_Add(request.POST)
        form.code=sled_num
        form.creat_times=timezone.now
        form.updete_times=timezone.now
        form.users="userrrrrr"
        if form.is_valid():
            form.save()

```

I specified everything as above, but form.is\_valid () does not become true

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 14, 2022, 2:14pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/2 "2022-01-14T14:14:55Z")

</div>

First, see the [`auto_now` and `auto_now_add` parameters](https://docs.djangoproject.com/en/4.0/ref/models/fields/#datefield) for the DateField and DateTimeField model fields to see if that will do what you’re looking for here.

But to address your more general question:  
`form = resu_DB_Add(request.POST)`  
Yes, `form` here is a form, not an instance.

If you want to get the instance of the model being handled by the form, the common sequence is to save the form with `commit=False`, which returns an instance of the object. You can then alter that instance and save it.

Note that in the general case, if you have fields that you are setting programmatically, you do _not_ want to include them in the list of fields in the form.

See the docs at [Creating forms from models | Django documentation | Django](https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#selecting-the-fields-to-use), particularly the examples in the green box a couple of paragraphs down.

---

<div class="post-metadata">

**Author:** ![ggggg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ggggg/32/6969_2.png) [@ggggg](https://forum.djangoproject.com/u/ggggg)\
**Post date:** [January 15, 2022, 6:57am UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/3 "2022-01-15T06:57:39Z")

</div>

> [@KenWhitesell](#):
>
> will do what you’re looking f

No, I’m having a problem with putting a value in form.code instead of save () I can’t reach save () because forms.is\_valid () is false  
I’m having some problems with form.code = sled\_num

```auto
        form.code=sled_num
        form.creat_times=timezone.now
        form.updete_times=timezone.now
        form.users="userrrrrr"
        forms=form.save(commit=False)
        if forms.is_valid():
            _.save()

```

```auto
ValueError The resu_DB could not be created because the data didn't validate.

```

I suspect this error is due to “” or “None” because form.code = sled\_num is not working (I’m sorry if it’s different)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 15, 2022, 12:07pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/4 "2022-01-15T12:07:05Z")

</div>

You’re trying to make changes to the _form_ when you want to make changes to the _instance of the object_ being created by the form.

What you want to do is:

- Do _not_ include programmatically generated fields in the form.
- Perform the form validation test first.
  - After the “if POST” conditional.

- Update the instance of the model **after** the form.save(commit=False)

---

<div class="post-metadata">

**Author:** ![ggggg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ggggg/32/6969_2.png) [@ggggg](https://forum.djangoproject.com/u/ggggg)\
**Post date:** [January 15, 2022, 12:36pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/5 "2022-01-15T12:36:43Z")

</div>

It’s impossible  
Currently form.is\_valid () = flase and it doesn’t work after that.  
You must fill in the fields that do not use the form before validation.  
So you have to do something before verification  
And if I use form.save (commit = False) before validation I get an error

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 15, 2022, 12:37pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/6 "2022-01-15T12:37:56Z")

</div>

What does your current form look like?  
(Specifically, did you remove the fields from the form that you are going to be adding programmatically?)

Also, please post the complete view.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 15, 2022, 5:04pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/7 "2022-01-15T17:04:56Z")

</div>

To clarify some items:

> [@ggggg](#):
>
> It’s impossible

This is not correct. It’s quite possible.

> [@ggggg](#):
>
> Currently form.is\_valid () = flase and it doesn’t work after that.

This statement is correct, because you’re not creating your form correctly.

> [@ggggg](#):
>
> So you have to do something before verification

This is not correct. If your form is constructed properly, you do not need to do anything before verification.

> [@ggggg](#):
>
> And if I use form.save (commit = False) before validation I get an error

Again, this is caused by you not creating your form correctly.

Keep in mind that a ModelForm is a **form** , it is not a model nor is it a type of model.

What you’re trying to do is create is an instance of a model - something completely different from the form.

In creating this instance of a model, some of your data is coming from a form, and some of it is coming from your code. The data being added to that model by your code does not come from the form, therefore, those fields should not be in the form.

---

<div class="post-metadata">

**Author:** ![ggggg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ggggg/32/6969_2.png) [@ggggg](https://forum.djangoproject.com/u/ggggg)\
**Post date:** [January 16, 2022, 6:30am UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/8 "2022-01-16T06:30:11Z")

</div>

```auto
class resu_DB_Add(forms.ModelForm):
    class Meta:
        model = models.resu_DB
        fields = ["users","code",'masseg','creat_times',"updete_times"]

ef sled_page(request,sled_num):
    massege="メッセージ"
    if (request.method == 'POST'):
        form = resu_DB_Add(request.POST)
        if form.is_valid():
            #form=form.save(commit=False)
            form.code=sled_num
            form.creat_times=timezone.now
            form.updete_times=timezone.now
            form.users="userrrrrrrr"
            form.save()
            massege="投稿に成功しました"
        else:
            massege="投稿に失敗しました"
          #"sled_DB_Addから特定(sled_num)のレスを取り出す"
    #resues=models.resu_DB.objects.#.get(code=sled_num)
    resues=models.resu_DB.objects.filter(code=sled_num)#
    header = ['ID','本文',"時間",]
    my_dict = {
        "header":header,
        'resues':resues,
        "sled_DB":models.sled_DB.objects.get(code=sled_num),
        'form': resu_DB_Add(), # 追加
        "sled_num":sled_num,
        "massege":massege

    }
    return render(request,'sled_page.html', my_dict)

```

---

<div class="post-metadata">

**Author:** ![ggggg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ggggg/32/6969_2.png) [@ggggg](https://forum.djangoproject.com/u/ggggg)\
**Post date:** [January 16, 2022, 6:31am UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/9 "2022-01-16T06:31:25Z")

</div>

As I said at the beginning, it seems that the explanation was insufficient.  
I don’t know any function to save other than ModelForm  
If you shouldn’t use it please tell me its unknown function

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 16, 2022, 1:06pm UTC](https://forum.djangoproject.com/t/how-to-automatically-save-values-in-the-database/11573/10 "2022-01-16T13:06:21Z")

</div>

Step by step:

- Remove all fields from the form that are going to be set programmatically.

- Your line

> [@ggggg](#):
>
> `#form=form.save(commit=False)`

> is close, but not quite right.  
> When you call [`form.save()`](https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#the-save-method), the return value is **not** a **form** - it’s an instance of the model being saved. So it would be more accurate and less confusing to write:

> `resu_db = form.save(commit=False)`  
> (Notice the name change from `resu_DB` - which is the model class, to `resu_db`, which is a name I’m using to indicate that it is an instance of `resu_DB` and not a reference to the model class.

- Your various field updates are then changed to refer to this new instance of your model.  
e.g. `form.code = sled_num` should be `resu_db.code = sled_num`

- Then at the end, you want to save this new model instance.  
e.g. `form.save()` becomes `resu_db.save()`

- Finally, after you’re done processing this form, you’re likely going to want to issue a `redirect` to the next page to be viewed. See how the overall flow of a page works at [`the view` section of the Working with forms](https://docs.djangoproject.com/en/4.0/topics/forms/#the-view) docs.
