在我的应用程序中用户可以通过为其命名来创建项目。
这是我的模特:
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
def __str__(self):
return self.name
这是我的观点:
class ProjectCreate(CreateView):
model = Project
fields = ['name']
template_name = 'project_form.html'
如何设置用户使用其ID创建项目project_hr_admin = models.ForeignKey(MyUser,blank = True,null = True)并将其保存在DB中?
你好
答案 0 :(得分:0)
希望这有帮助。
class ProjectCreate(CreateView):
model = Project
fields = ['name']
template_name = 'project_form.html'
def form_valid(self, form):
form.instance.project_hr_admin = self.request.user
return super(ProjectCreate, self).form_valid(form)
或者您也可以将form_valid
函数重写为
def form_valid(self, form):
obj = form.save(commit=False)
obj.project_hr_admin = self.request.user
obj.save()
return HttpResponseRedirect('YOUR_SUCCESS_URL')