現在、Djangoにて
Userモデルと一対一対応させたProfileモデルを用いて
テンプレート画面から値を入力して、Profileモデルのフィールド値をアップデートしようと
しています。
しかし、POSTで送信するとcould not be changed because the data didn't validate.
というエラーが出ており、デバッグすると問題があるのはuserモデルではなく、Profileモデル
でした。ちなみに、profileform.errorを表示するとuserという文字が表示されています。
この原因について分かりかねているので
分かる方がいらっしゃいましたら教えて頂きたいです。
models.py
models.py
1class Profile(models.Model): 2 GENDER_CHOICES = ( 3 ('1', '男性'), 4 ('2', '女性'), 5 ) 6 7 COUNTRY_CHOICES = ( 8 ('1','アメリカ'), ('2','日本'), ('3','中国'), ('4','台湾'), ('5','カナダ'), ('6','イギリス'), ('7','ドイツ'), ('8','イタリア'), ('9','オーストラリア'), 9 ) 10 11 YEAR_CHOICES = ( 12 (1940,1940), (1941,1941), 13 ) 14 15 MONTH_CHOICES = ( 16 (1,1),(2,2), 17 18 ) 19 20 DAY_CHOICES = ( 21 (1,1),(2,2) 22 ) 23 24 user = models.OneToOneField(User,on_delete=models.CASCADE) 25 name = models.CharField("名前",max_length = 255,blank = True) 26 gender = models.CharField("性別",max_length = 2,choices = GENDER_CHOICES, blank = True) 27 birth_year = models.IntegerField("年",choices = YEAR_CHOICES, blank = True,null = True) 28 birth_month = models.IntegerField("月",choices = MONTH_CHOICES, blank = True,null = True) 29 birth_day = models.IntegerField("日",choices = DAY_CHOICES, blank = True,null = True) 30 country = models.CharField("出身国",max_length = 2,choices = COUNTRY_CHOICES, blank = True) 31 32 def __str__(self): 33 return self.name 34 35@receiver(post_save, sender=User) 36def create_user_profile(sender, instance, created, **kwargs): 37 if created: 38 Profile.objects.create(user=instance) 39 40@receiver(post_save, sender=User) 41def save_user_profile(sender, instance, **kwargs): 42 instance.profile.save()
views.py
views.py
1def profile_edit(request): 2 userform = UserUpdateForm(request.POST or None, instance=request.user) 3 profileform = ProfileForm(request.POST or None, instance=request.user.profile) 4 5 if request.method == 'POST': 6 7 if profileform.is_valid() and userform.is_valid(): 8 #Userモデルの処理 9 userform.save() 10 11 #Profileモデルの処理 12 profile.user = request.user 13 profileform.save() 14 15 return redirect("profile") 16 else: 17 return HttpResponse(profileform.errors) 18 19 context = { 20 "userform": userform, 21 "profileform":profileform, 22 } 23 return render(request, 'profile_edit.html', context)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。