我最近尝试过这个问题并且完全混淆了。我在models.py中
扩展了默认用户模型class Biography(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
biography = models.TextField(max_length=500, blank=True,default='Details')
我已将其包含在forms.py中:
class EditProfileForm(forms.Form):
first_name = forms.CharField(label='First Name')
last_name = forms.CharField(label='Last Name')
biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5}))
我想要编辑个人资料,并希望添加"传记"对它,但绝对没有线索从哪里开始。以下是观点:
def edit_profile(request):
user = request.user
products = Product.objects.filter(user=user)
form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.save()
return render(request, 'profile.html', {'user':user, 'products':products})
context = {"form": form}
return render(request, "edit_profile.html", context)
我试图复制已有的内容:
def edit_profile(request):
user = request.user
products = Product.objects.filter(user=user)
biography = Biography(user=user)
form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.biography = request.POST['biography']
user.save()
return render(request, 'profile.html', {'user':user, 'products':products})
context = {"form": form}
return render(request, "edit_profile.html", context)
我绝对错过了这一点。我最后一次问这个问题时,因为不知道如何解决这个问题而受到严厉批评。说实话,我对Django来说真是太新了,我很惊讶我已经走到了这一步,但是我被困住了。我认为'我需要创建一个实例但不确定如何。
答案 0 :(得分:1)
你应该做些什么:
Biography
实例(如果它不存在,或从db。cleaned_data
作为输入验证是表单的主要目的之一User
和Biography
个实例products
。如果只是你不打算以某种方式更新它们。例如:
def edit_profile(request):
user = request.user
biography, created = Biography.objects.get_or_create(user=user)
form = EditProfileForm(initial={
'first_name': user.first_name,
'last_name': user.last_name,
'biography': biography.biography
})
if request.method == 'POST':
form = EditProfileForm(data=request.POST)
if form.is_valid():
user.first_name = form.cleaned_data['first_name'] # use cleaned_data
user.last_name = form.cleaned_data['last_name']
biography.biography = form.cleaned_data['biography']
biography.save() # save Biography object
user.save() # save User object
return redirect(biography) # always redirect after successful POST. In this case Biography must have get_absolute_url() method
context = {'form': form}
return render(request, 'edit_profile.html', context)
在documentation中阅读更多内容。
答案 1 :(得分:0)
user.biography
是Biography
模型的一个实例,所以你应该在这里做的是获取该实例并编辑其属性,如下所示:
bio = user.biography
bio.biography = request.POST['biography']
bio.save()