How to automatically save values in the database

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.

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

    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

First, see the auto_now and auto_now_add parameters 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, particularly the examples in the green box a couple of paragraphs down.

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

        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()
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)

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)

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

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.

To clarify some items:

This is not correct. It’s quite possible.

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

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

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.

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)

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

Step by step:

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

  • Your line

is close, but not quite right.
When you call form.save(), 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 docs.