Home > Enterprise >  How can I save a django Model Form in views for the logged in user
How can I save a django Model Form in views for the logged in user

Time:05-04

I am working on a project in Django where I have an Education(models.Model) with a OneToOneField to User Model as shown below:

class Education(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
qualification = models.CharField(max_length=60, choices=INSTITUTE, blank=True, null=True)
institution = models.CharField(max_length=40, null=True)
reasons = models.CharField(max_length=100, null=True) 
matnumber = models.CharField(max_length=255, null=True)

And a forms.ModelForm as shown below:

class AddEducationForm(forms.ModelForm):

class Meta:
    model = Education
    fields = ['qualification','instition', 'matnumber', 'reasons','refphone']

In my views.py file I want to save this AddEducationForm for the logged in user. Below is what I have tried but it is not saving but showing success message of save.

def AddEducation(request):
if request.method == 'POST':
    form = AddEducationForm(request.POST, instance=request.user)
    if form.is_valid():
        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)

The system is displaying the success message that the form has been saved for the logged in user but in reality it is not (when checked using Django Admin Login). Someone should kindly help out with the solution to this problem. Remember each logged in user would save only one Education Form record. Thank in anticipation.

CodePudding user response:

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.

  • Related