无法分配“<simplelazyobject:<user:=”“admin =”“>&gt;”:“Project.manager”必须是“Profil”实例

时间:2018-05-26 17:21:13

标签: django django-models django-forms

您好我在开始保存表单时遇到此错误。

Cannot assign "<SimpleLazyObject: <User: admin>>": "Project.manager" must be a "Profil" instance.

我有两个应用程序帐户和项目

  

account.model.py

class Profil(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   photo_path = time.strftime('photo/%Y/%m/%d')
   photo = models.ImageField(upload_to=PathAndRename(photo_path), blank=True, null=True)
   antity = models.CharField(max_length=50, choices=ENTITY_TYPE, default=ENTITY_TYPE[0])
   biography = models.TextField(blank=True, max_length=500)
   location = models.CharField(max_length=30, blank=True, default='Congo-BZV')
   facebook_url = models.URLField(default='', blank=True)
   twitter_url = models.URLField(default='', blank=True)
   inscrit_newsletter = models.BooleanField(default=True)
   def __str__(self):
       return "Profil de {0}".format(self.user.username)
  

project.model.py

class Project( models.Model):

   manager = models.ForeignKey('accounts.Profil', related_name='project', on_delete=models.CASCADE)
   title = models.CharField(max_length = 100)
   slug = models.SlugField(unique=True)


   image_path = time.strftime('images/%Y/%m')
   main_image = models.ImageField(upload_to=PathAndRename(image_path), blank=True)


   slogan = models.CharField(max_length=300, blank=True)

   description = RichTextUploadingField(blank = True, null=True)
  

project.views.py

def project_new(request):
   if request.method == 'POST':
       form = ProjectForm(request.POST)
       if form.is_valid():
           project = form.save(commit = False)
           project.manager = request.user
           project.save()

   else:
       form = ProjectForm()


   return render(request, 'project/project_new.html', {'form': form})
  

project.forms.py

class ProjectForm(forms.ModelForm):

   title = forms.CharField(label='Titre')
   description = forms.CharField(widget=CKEditorUploadingWidget())
   category = forms.ModelChoiceField(queryset =  Category.objects.all(), label='Catégorie')

#description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))


   class Meta:
       model = Project
       fields = ('title', 'nb_days', 'slogan', 'category', 'description')

我希望每个用户或经理都能通过表单链接到他们发布的项目。 如何通过保存模型来链接这两个模型?

谢谢

1 个答案:

答案 0 :(得分:1)

insted of

project.manager = request.user

你应该使用:

project.manager = request.user.profil