问题
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