views.py
@login_required(login_url='/account/login/')
def TaskCreateView(request,pk,todo_id):
if not request.user.is_authenticated:
return redirect('accounts:index')
else:
instance = get_object_or_404(Level, pk=pk)
qs = instance.todo_set.get(id = todo_id)
#user = Task.objects.filter(student=request.user)
todo = Task.objects.filter(todo=qs, student=request.user)
if todo.exists():
messages.warning(request, 'You Already Completed This Task')
return HttpResponseRedirect(instance.get_absolute_url())
form = StudentTaskForm(request.POST or None,request.FILES or None)
if form.is_valid():
obj = form.save(commit=False)
obj.student = request.user
obj.todo = qs
obj.level = instance
obj.save()
return redirect('student:dashboard')
return render(request,'task_form.html',{'form':form,"qs":qs})
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
image = models.ImageField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField(auto_now_add=True, auto_now=False)
like = models.ManyToManyField(User,related_name='user_likes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs={'pk': self.pk})
objects = PostManager()
@property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
forms.py
class StudentTaskForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control',' type': "text",'placeholder':'Enter Title'}))
content = forms.CharField(widget=SummernoteWidget())
image = forms.ImageField()
class Meta:
model = Task
fields = [
'title',
'content',
'image',
]
widgets = {
'content': SummernoteWidget(),
}
我试图在表单保存后将字段保存到Task模型中。我在提交表单后遇到此错误。如果我再次刷新页面,则其工作正常。 ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp上写pppp
答案 0 :(得分:0)
您的代码不包含user
外键,因此不会出现有关user_id
为空的错误。
也许您将user
重命名为student
,却忘记了进行迁移和迁移。