我有两个模型,User
和Freelancer
:
#models.py
class User(AbstractBaseUser):
class Freelancer(models.Model):
user = models.ForeignKey(User)
我有两种形式:
#forms.py
class UserUpdateForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
class FreelanceUpdateForm(forms.ModelForm):
class Meta:
model = Freelancer
fields = ('first_name', 'surname', 'university', 'biography', 'skills')
我想在同一页面上显示两者,所以我创建了一个视图来执行此操作:
def profile(request, pk):
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
freelancer_form = FreelanceUpdateForm(request. POST, instance=request.user.id)
if all([user_form.is_valid(), freelancer_form.is_valid()]):
user = user_form.save()
freelancer_form = freelancer_form.save()
return redirect(user)
else:
user_form = UserUpdateForm(instance=request.user)
freelancer_form = FreelanceUpdateForm(instance=request.user.id)
return render(request, 'freelancestudent/profile.html',{
'user_form': user_form,
'freelancer_form': freelancer_form,
})
问题是我无法获得freelancer_form
freelancer_form = FreelanceUpdateForm(instance=request.user.id)
我已经尝试freelancer_form = FreelanceUpdateForm(instance=Freelancer(user_id=request.user.id))
填充表格,但它不会将其保存为有效,因为它没有绑定。
如何获得相关的自由职业者?
答案 0 :(得分:-1)
为此,您需要在related_name
中指定Freelancer.user
以反向访问它:
class Freelancer(models.Model):
user = models.ForeignKey(User, related_name='freelancer')
现在,您可以使用简单Freelancer
从User
模型访问User.freelancer
,因此您可以像这样创建表单:
freelancer_form = FreelanceUpdateForm(request. POST, instance=request.user.freelancer)