简体   繁体   中英

Django - AttributeError: 'NoneType' object has no attribute 'pk'

In short I'm making ToDo app where user can store his todos and projects. Projects consist of todos and can be shared with other users. I'm displaying all todos and projects belonging to a user but when I try to access user todo I get: AttributeError: 'NoneType' object has no attribute 'pk'

When accessing todo inside project and even todo inside someone else project everything works fine. Here's log:

 Traceback (most recent call last):
      File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
        response = get_response(request)
      File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
        return view_func(request, *args, **kwargs)
      File "C:\Users\dknapik\Documents\Software\Python\lic\todo-licencjat\task\views.py", line 126, in viewtask
        project = get_object_or_404(Project, pk=task.project_id.pk)

Exception Type: AttributeError at /task/4
Exception Value: 'NoneType' object has no attribute 'pk'

view:

def displayTask(request, task_pk, task):
    if request.method == 'GET':
        form = TaskForm(instance=task)
        return render(request, 'task/viewtask.html', {'task': task, 'form':form})
    else:
        try:
            form = TaskForm(request.POST, instance=task)
            form.save()
            return redirect('currenttasks')
        except ValueError:
            return render(request, 'task/viewtask.html', {'task': task, 'form':form, 'error': 'Something went wrong'})

@login_required
def viewtask(request, task_pk):
    task = get_object_or_404(Task, pk=task_pk)
    project = get_object_or_404(Project, pk=task.project_id.pk)
    if request.user == task.task_owner:
        return displayTask(request, task_pk, task)
    elif task.project_id and project.participant1 == request.user:
        return displayTask(request, task_pk, task)
    else:
        raise Http404

and model:

class Project(models.Model):
    title = models.CharField(max_length=100)
    project_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner")
    created = models.DateTimeField(auto_now_add=True)
    completed = models.DateTimeField(blank=True, null=True)
    participant1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="participant", blank=True, null=True)

class Task(models.Model):
    title = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)
    scheduled = models.DateTimeField(blank=True, null=True)
    completed = models.DateTimeField(blank=True, null=True)
    importance = models.BooleanField(default=False)
    task_owner = models.ForeignKey(User, on_delete=models.CASCADE)
    project_id = models.ForeignKey(Project, on_delete=models.CASCADE, blank=True, null=True)

I understand that I need to do something with project = get_object_or_404(Project, pk=task.project_id.pk) but I can't figure out condition that would be able to display all of these:

  • user own todos
  • user todos inside his projects
  • todos inside projects where user is a participant

I will appreciate any help with that, thanks.

I was able to figure it out, basically hasattr() did the trick:

if hasattr(task.project_id, 'pk'):
    project = get_object_or_404(Project, pk=task.project_id.pk)

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM