장고 : User (Django에서 미리 정의 됨) 및 UserProfile의 두 가지 모델이 있습니다. 두 개는 외래 키를 통해 연결됩니다.Django에서 User 및 UserProfile 객체를 저장하는보기를 만드는 방법
models.py : 나는 UserCreationForm을 사용하고
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, related_name="connect")
location = models.CharField(max_length=20, blank=True, null=True)
은 사용자 모델 (장고에 의해 미리 정의 된) 및 forms.py
#UserCreationForm for User Model
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ("user",)
I에서 사용자 프로필에 대한 또 다른 형태를 만들어 두 양식을 모두 registration.html 템플리트에로드하여 웹 사이트 고객이 두 모델 (예 : 사용자 모델의 "first_name", "last_name", UserProfile 모델의 "location")에 포함 된 필드에 대한 데이터를 입력 할 수 있습니다.
저의 삶에 대해이 등록 양식에 대한보기를 만드는 방법을 알아낼 수 없습니다. 지금까지 시도한 것은 User 객체를 만들지 만 해당 UserProfile 객체의 위치와 같은 다른 정보는 연결하지 않습니다. 누구든지 나를 도울 수 있습니까? form.save()
는 모델의 인스턴스를 생성하고 dB로 저장합니다, 거의 다
def register(request):
if request.method == 'POST':
form1 = UserCreationForm(request.POST)
form2 = UserProfileForm(request.POST)
if form1.is_valid():
#create initial entry for User object
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
# What to do here to save "location" field in a UserProfile
# object that corresponds with the new_user User object that
# we just created in the previous lines
else:
form1 = UserCreationForm()
form2 = UserProfileForm()
c = {
'form1':UserCreationForm,
'form2':form2,
}
c.update(csrf(request))
return render_to_response("registration/register.html", c)
http://stackoverflow.com/questions/569468/django-multiple-models-in-one-template-using-forms –