Home > Net >  Saving logged in user info in django model
Saving logged in user info in django model

Time:07-08

I am trying to update planTable model with the current logged in user automatically. In my planForm form, I have excluded "user" field.

These are my code snippets.

views.py

def createPlan(request):
    
    form = planForm
    
    if request.method == "POST":
        form = planForm(request.POST)
        
        if form.is_valid():
            
            form.save()
            
            return redirect('index')
    
    
    context = {'form':form}
    return render(request, 'workoutapp/create_plan.html', context)

@login_required(login_url='/register_user/')
def myPlan(request):
        
    my_plan = planTable.objects.filter(user=request.user)
    print('user : ', request.user)
    #print('data : ', my_plan)
    context = {'my_plan':my_plan}
    return render(request, 'workoutapp/my_plan.html', context)

models.py

class planTable(models.Model):
    
    DAYS = (
        ("sunday", "sunday"),
        ("monday", "monday"),
        ("tuesday", "tuesday"),
    )
    
    day = models.CharField(null=True, max_length=10, choices=DAYS)
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    category = models.ForeignKey(workoutTable, null=True, on_delete=models.CASCADE)
    exercise = models.ForeignKey(itemTable, null=True, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.day

forms.py

class planForm(ModelForm):
    
    class Meta:
        model = planTable 
        fields = 'day', 'category', 'exercise'

create_plan.html

<form action="" method="POST">

    {% csrf_token %}

    {{form}}



    <input type="submit" name="submit">
</form>

My requirement is that when the logged in user clicks on submit button, the fields in planTable should get populated with the values. But after logged in user click on submit button, only day, category and exercise gets populated, the user field stays blank. Is there any way for the user field to get populated depending on the logged in user?

CodePudding user response:

validate the form without a user then set it:

def createPlan(request):
    
    form = planForm
    
    if request.method == "POST":
        form = planForm(request.POST)
        
        if form.is_valid():
            plan = form.save(commit=False)
            plan.user = request.user
            plan.save()
            return redirect('index')
    
    context = {'form':form}
    return render(request, 'workoutapp/create_plan.html', context)   
  • Related