/ accounts / addtimesheet / TimeSheet中的RelatedObjectDoesNotExist没有项目

时间:2018-03-23 21:28:08

标签: django django-models django-views

我正在尝试将对象(Project)添加到另一个对象TimeSheet。当我试图这样做时,我收到一个错误说

" / accounts / addtimesheet /中的RelatedObjectDoesNotExist - TimeSheet没有项目。"

虽然我在TimeSheet中将项目作为项目模型的ForeignKey。

我认为在创建项目模型时,我在models.py文件中遗漏了一些内容。有人可以帮助我,我错过了什么。

model.py

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  emp_name = models.CharField(max_length=500)
  gender = models.CharField(max_length=10)
  job_position = models.CharField(max_length=20)
  salary = models.IntegerField()

def __str__(self):
    return self.emp_name

class Project(models.Model):
  project_name = models.CharField(max_length=200)
  employees = models.ManyToManyField(Profile)

  def __str__(self):
    return self.project_name

class TimeSheet(models.Model):
  employees = models.ManyToManyField(Profile)
  emp_name = models.CharField(max_length=100, default='emp_name')
  date  = models.DateField()
  start_time = models.TimeField()
  end_time = models.TimeField()
  project = models.ForeignKey(Project, on_delete=models.CASCADE)

  def __str__(self):
    return self.emp_name + ' ' + self.project.project_name +' '+ str(self.date)    

views.py

def add_timesheet(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        timesheet = TimeSheet()
        print(request.user)
        timesheet.employees.set(request.user)
        timesheet.save()
        timesheet.date = request.POST['date']
        timesheet.start_time = request.POST['from']
        timesheet.end_time = request.POST['to']
        timesheet.project_set.add(Project.objects.filter(id=request.POST.get('project_id'))[0])
        #timesheet.project = project_name
        timesheet.save()
        id = request.user.id
        emp_profile = Profile.objects.filter(user=id)[0] # get the profile object of the logged in user
        projects = emp_profile.project_set.all()         # use the profile object to get his projects
        return render(request, 'accounts/project.html', {'projects':projects})
    else:
        project_name = request.GET.get('project_name')
        return render(request, 'accounts/add_timesheet.html', {'project_name':project_name})
else:
    return render(request, 'accounts/login.html', {'error': 'Login to access the page'})

完全追溯:

Internal Server Error: /accounts/addtimesheet/
Traceback (most recent call last):
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\computer\Desktop\django\TMS_1\TMS_1\TMS\accounts\views.py", line 49, in add_timesheet
    timesheet.employees.set(request.user)
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 498, in __get__
    return self.related_manager_cls(instance)
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 795, in __init__
(instance, self.pk_field_names[self.source_field_name]))
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 513, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
  File "C:\Users\computer\Desktop\django\TMS_1\TMS_1\TMS\accounts\models.py", line 32, in __str__
    return self.emp_name + ' ' + self.project.project_name +' '+ str(self.date)
  File "C:\Users\computer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 175, in __get__
    "%s has no %s." % (self.field.model.__name__, self.field.name)
django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: TimeSheet has no project.
[23/Mar/2018 15:46:12] "POST /accounts/addtimesheet/ HTTP/1.1" 500 87076

2 个答案:

答案 0 :(得分:0)

尝试此操作而不是设置用户

timesheet.employees = Profile.objects.get(user = request.user)

答案 1 :(得分:0)

timestampproject之间没有Revere FK关系。所以它应该是这样的,
timestamp.project = some_project_instance

此外,您应该知道the difference between filter and get in django。在您的view.py中

尝试此操作
def add_timesheet(request):


    if request.user.is_authenticated:
        if request.method == 'POST':
            timesheet = TimeSheet()
            print(request.user)
            timesheet.employees.set(request.user)
            timesheet.save()
            timesheet.date = request.POST['date']
            timesheet.start_time = request.POST['from']
            timesheet.end_time = request.POST['to']
            # Changes
            timesheet.project = Project.objects.get(id=request.POST.get('project_id'))
            timesheet.save()
            emp_profile = Profile.objects.get(user=request.user)
            projects = emp_profile.project_set.all()  # use the profile object to get his projects

            return render(request, 'accounts/project.html', {'projects': projects})
        else:
            project_name = request.GET.get('project_name')
            return render(request, 'accounts/add_timesheet.html', {'project_name': project_name})
    else:
        return render(request, 'accounts/login.html', {'error': 'Login to access the page'})