[Answered ]-How can I save a django Model Form in views for the logged in user

1👍

You add it to the instance of the form, so:

from django.contrib.auth.decorators import login_required

@login_required
def add_education(request):
    if request.method == 'POST':
        form = AddEducationForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.applicant = request.user
            form.save()
            messages.success(request, 'Education Added Successfully')
            return redirect('user-bank')
    else:
        form = AddEducationForm()
    context = {
        'form':form,
    }
    return render(request, 'user/add_education.html', context)

Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].


Note: Functions are normally written in snake_case, not PascalCase, therefore it is
advisable to rename your function to add_education, not addEducation.


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