yogeshiitm
yogeshiitm

Reputation: 309

In Django, how to add username to a Model automatically, when the Form is submitted by a logged in user

In my Django app, I have defined a Many-to-one relationship using ForeignKey. Now what I want is that when a logged-in user submits the ListForm then his username should automatically add to the owner field of the ListModel. Currently when a user submits the form, None is being shown in the owner field, how can I add the username to the database along with the form?

my models.py:

from django.db import models
from django.contrib.auth.models import User

class ListModel(models.Model):
    owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
    task = models.CharField(max_length=255)
    completed = models.BooleanField(default=False)

my forms.py:

from django.forms import ModelForm
from .models import ListModel
from django import forms


class ListForm(ModelForm):
    class Meta:
        model = ListModel
        fields = ['owner','task', 'completed']

Upvotes: 2

Views: 2757

Answers (2)

yogeshiitm
yogeshiitm

Reputation: 309

Finally got it working (my solution reference)

First, we need to exclude the owner field from the ModelForm in forms.py:

class ListForm(ModelForm):
    class Meta:
        model = ListModel
        fields = ['task', 'completed']
        # instead of above line we can simply write: exclude = ['owner']

and in the views.py:

form = ListForm(request.POST)
if form.is_valid():
    task_list = form.save(commit=False)
    task_list.owner = request.user
    task_list.save()
    return redirect('/')

where instead of task_list we can use any variable & also note that after task_list.save() no need to do form.save() because it's already included in task_list = form.save(commit=False)

Upvotes: 3

Pritesh Suvagiya
Pritesh Suvagiya

Reputation: 166

You have to override the form_valid() method of the View and attach the current logged in user as an Owner.

    def form_valid(self, form):
        form.instance.owner = self.request.user   <------ This line will do the trick.
        return super().form_valid(form)

Upvotes: 2

Related Questions