我看过所有类似的问题,但似乎都没有帮助。
这是POST
class ProfileEditView(generic.DetailView):
方法
def post(self, request, *args, **kwargs):
profile_id = kwargs.get('pk')
user_detail = User.objects.get(id=profile_id)
form = EditProfileForm(request.POST, request.FILES, instance=user_detail)
if form.is_valid():
updated = form.save(commit=False)
updated.phone = form.cleaned_data["phone"]
updated.address = form.cleaned_data["address"]
updated.gender = form.cleaned_data["gender"]
updated.save()
messages.success(request, "Profile details updated.")
return redirect("profileview", profile_id)
else:
context = {}
context["form"] = form
context["profile_id"] = kwargs["pk"]
return render(request, self.template_name, context)
模板:
<form enctype="multipart/form-data" method="POST" action="{% url 'profile_edit_view' profile_id %}">
{% csrf_token %}
{{form|crispy}}
<input type="submit" value="Save">
</form>
Models.py
class UserDetail(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
profile_picture = models.FileField(upload_to=profile_image_upload, null=True, blank=True)
phone = models.CharField(max_length=10)
address = models.CharField(max_length=1000)
gender = models.CharField(max_length = 10, choices=gender_choices)
答案 0 :(得分:1)
如果EditProfileForm
正在修改UserDetail
,那么instance
应该是UserDetail
个实例。您目前正在通过user
。尝试将其更改为:
def post(self, request, *args, **kwargs):
user_id = kwargs.get('pk')
user_detail = User.objects.get(id=user_id)
user_detail = user.userdetail
form = EditProfileForm(request.POST, request.FILES, instance=user_detail)