get_user_model doesn't return a value

a 夏天 提交于 2021-01-29 17:56:10

问题


as my first project in Django I am creating a todo app, that lets people log in and see their own tasks that they created. For that, I need to save author info in single task data.

From what I learned reading the documentation and doing lots of google-searching, the current approach is to use the get_user_model function from django.contrib.auth.

The problem is, that whenever I try to use it in my model, it seems to not get the username from the currently logged in user. While printing the form.errors to my console, the output is:

<ul class="errorlist"><li>added_by<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

Seems like the get_user_model is not returning any value. Can anyone recommend a better approach for me to do that? Or is there something obvious that I missed?

Here are the code snippets:

models.py

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


class Task(models.Model):
    title = models.CharField(max_length=35)
    completed = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now_add=True)
    added_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    def __str__(self):
        return self.title

forms.py

from django import forms
from .models import *


class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = '__all__'
        widgets = {
            'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}),
        }

views.py

@login_required
def list_homepage(request):
    tasks = Task.objects.all()

    form = TaskForm()
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            print(form.cleaned_data)
        else:
            print(form.errors)
        return redirect('/list/home')

    context = {
        'page_title': 'Todo list',
        'tasks': tasks,
        'form': form,
    }
    return render(request, 'tasks/list.html', context)

form in template:

    <form method="POST", action="#"> {% csrf_token %}
        {{ form.title }}
        <input class="submit" type="submit", value="Create task">
    </form>

Thank you in advance for any help!


回答1:


Your form template only includes the title field, you either need to add the added_by field to this form, or add it in the view handling

{{ form.added_by }}

or

if request.method == 'POST':
    form = TaskForm({**request.POST, **{"added_by": request.user}})


来源:https://stackoverflow.com/questions/60759961/get-user-model-doesnt-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!