[Django]-Form save is not adding user to model

2👍

A form has no user, you should patch the .instance wrapped in the form, so:

@login_required
def index(request):
    '''deal with post method first'''
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('index')
    # …

You might want to use the auto_now_add=True parameter for the timestamp:

class Post(models.Model):
    body = models.TextField(max_length=140)
    timestamp = models.DateField(db_index=True, auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    # …

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment