ユーザーがフォームを送信したときに保存されない2つのモデルフィールド(趣味と言語)があります。彼らは、別々のモデルに接続された多くのフィールドから多くのフィールドです。しかし、私はそれらをモデルに保存する方法がわかりません。フォームを送信した後、2つのフィールドが保存されません。 Django
これはモデルである:
# this is model for user
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
hobbies = models.ManyToManyField(Hobby)
languages = models.ManyToManyField(Language)
profilepic = models.ImageField(upload_to='static/images/Profile Pictures', blank=True)
city = models.ForeignKey(City)
slug = models.SlugField(unique=True)
average_rating = models.IntegerField(default=0)
ratings_count = models.IntegerField(default=0)
def save(self, *args, **kwargs):
# Uncomment if you don't want the slug to change every time the name changes
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)
def __unicode__(self):
return self.user.username
これは趣味と言語モデルである:
# this is the model for hobbies - one to many relationship with User
class Hobby(models.Model):
hobby = models.CharField(max_length=128)
def save(self, *args, **kwargs):
# if self.id is None:
# self.slug = slugify(self.name)
self.slug = slugify(self.hobby)
super(Hobby, self).save(*args, **kwargs)
def __unicode__(self):
return self.hobby
# this is the model for languages - one to many relationship with User
class Language(models.Model):
language = models.CharField(max_length=128)
def save(self, *args, **kwargs):
# if self.id is None:
# self.slug = slugify(self.name)
self.slug = slugify(self.language)
super(Language, self).save(*args, **kwargs)
def __unicode__(self):
return self.language
これはデータベースにフォームデータを保存する図である。
def createprofile(request):
registered = False
if request.method == 'POST':
user = User.objects.get(username = request.user.username)
user_form = UserForm(data=request.POST, instance = user)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profilepic' in request.FILES:
profile.profilepic = request.FILES['profilepic']
profile.save()
registered = True
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request,
'createprofile.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered})