Form question ('user' field)

Hi. I’m building a simple Django app that allows to register, login and add (new, update, delete) records.
My problem is that in the video tutorial that I’m following everyone can see every records, and I need that user could see his/her records only. So I’m stuck. How do I add usernames to records, so I could filter them in view? Please help.

here is my model:

class Record(models.Model):

    user = models.CharField(max_length=150)
    creation_date = models.DateTimeField(auto_now_add=True)
    sis = models.IntegerField()
    dia = models.IntegerField()
    pulse = models.IntegerField()

    def __str__(self):
        return str(self.creation_date) + "   " + str(self.user) + "   " + str(self.sis) + "   " + str(self.dia) + "   " + str(self.pulse)

here is forms.py class:

class CreateRecordForm(forms.ModelForm):

    class Meta:

        model = Record
        fields = ['sis', 'dia', 'pulse']

here is view:

@login_required(login_url='my-login')
def create_record(request):

    form = CreateRecordForm()

    if request.method == "POST":

        form = CreateRecordForm(request.POST)
        
        if form.is_valid():
            form.save()

            return redirect("index")

    context = {'form':form}

    return render(request, 'core/create-record.html', context=context)

Ho do I add ‘current_user’ into ‘user’ field before form.save() ?
Thanks in advance.

See the docs and the examples for The save() method.

Thanks! It looks like this works!

            full_form = form.save(commit=False)
            full_form.user = request.user
            full_form.save()

Note: For clarity and accuracy, I always recommend that you name the variable holding the return value from the save method correctly.

The expression form.save(commit=False) does not return an instance of the form. It returns the instance of the model created by the form, in your case, Record.

So, to prevent confusion and potential misunderstandings in the future, I would recommend that instead of calling it full_form which is not accurate), you use a variable name like record or new_record - something like that.

Agree. new_record it is. Thanks! )