Cannot set a field value of a Django form in views

Viewed 301

I am making a todo website in which different users can sign in and have their separate todo lists, but when a user signs in and adds a task to the list that task does not get assigned to any user, so despite being present on the database it does not show up on the user's list.

I am trying to assign the form object(task_form) a user after the form submission, I think that is the issue but I have no idea what else to try.

views.py

@login_required(login_url='todo:login')
def task_add(request):
    if(request.method == "POST"):
        task_form = AddTask(request.POST)
        if(task_form.is_valid()):

            task_form.cleaned_data['user'] = request.user #trying to assign a user after all the data has been populated

            task_form.save()
            return redirect('todo:index')
    return render(request,'todo/task_add.html')

template(task_add.html)

{% block body %}
    <form method="POST">
        {% csrf_token %}
        <p><label for="title">Title</label>
        <input type="text" name="title"></p>
        <p><label for="desc">Description</label>
        <input type="text" name="desc"></p>
        <p><label for="start_time">Time</label>
        <input type="datetime-local" name="start_time"></p>
        <p><label for="completed">Complete</label>
        <input type="radio" name="completed"></p>
        <input type="submit" value="Add" name="submit" class="btn btn-success">
    </form>
{% endblock %}

models.py

class Task(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True)
    title = models.CharField(max_length=50)
    desc = models.CharField(max_length=100,null=True,blank=True)
    start_time = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

forms.py

class AddTask(forms.ModelForm):
    class Meta:
        model = Task
        fields = '__all__'
1 Answers

You can set the .user attribute of the .instance wrapped in the form:

@login_required(login_url='todo:login')
def task_add(request):
    if request.method == 'POST':
        task_form = AddTask(request.POST)
        if task_form.is_valid():
            task_form.instance.user = request.user
            task_form.save()
            return redirect('todo:index')
    return render(request,'todo/task_add.html')
Related