我有一个名为profile
的模型,它与User
模型具有一对一的关系。 profile
包含有关用户的不必要信息,例如个人简介,性别,国家/地区等。因此,当用户注册时,他们还没有个人资料。当用户进入设置并开始输入详细信息时,他们将拥有一个配置文件。
话虽如此,我如何在Django中创建一个视图,该视图既可以创建有关用户的个人资料详细信息,也可以更新现有信息。
表格
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['avatar', 'bio', 'gender', 'dob', 'country']
查看
class SettingsView(FormView):
template_name = 'oauth/settings.html'
form_class = ProfileForm
success_url = reverse_lazy('oauth:settings')
redirect_field_name = "next"
答案 0 :(得分:1)
尝试一下:
from django.views import View
from .forms import ProfileForm
from .models import Profile
class Settings(View):
form_class = ProfileForm
template_name = 'oauth/settings.html'
def post(self, request):
form = self.form_class(request.POST)
data = {'error':''}
if form.is_valid():
user = request.user
bio = form.cleaned_data['bio']
# more fields here
try:
profile = user.profile
# update user profile
profile.bio = bio
# add more fields here
profile.save()
data['response'] = 'profile updated!'
except:
profile = Profile(user=user,bio=bio) #add more fields
profile.save()
data['response'] = 'profile created!'
else:
data['error'] = 'Invalid form!'
return render(request, self.template_name,{'data':data})
编辑:
或者我们可以按照OP的建议使用update_or_create()
。
通过将try
和except
块替换为:
updated_values = {'bio':bio} # add more fields
obj, created = Profile.objects.update_or_create(user=user,bio=bio, defaults=updated_values) # add more fields
if created:
data['response'] = 'profile created!'
else:
data['response'] = 'profile updated!'