में उपयोगकर्ता और उपयोगकर्ता प्रोफाइल ऑब्जेक्ट्स को सहेजने वाला दृश्य कैसे बनाएं, मेरे पास Django में दो मॉडल हैं: उपयोगकर्ता (Django द्वारा पूर्व परिभाषित) और UserProfile। दोनों विदेशी कुंजी के माध्यम से जुड़े हुए हैं।Django
models.py:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, related_name="connect")
location = models.CharField(max_length=20, blank=True, null=True)
मैं UserCreationForm उपयोग कर रहा हूँ उपयोगकर्ता मॉडल के लिए (Django द्वारा पूर्व निर्धारित), और forms.py
#UserCreationForm for User Model
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ("user",)
मैं में UserProfile के लिए एक और रूप बनाया इन दोनों रूपों को एक टेम्पलेट, register.html में लोड करें, इसलिए वेबसाइट ग्राहक दोनों मॉडलों में मौजूद फ़ील्ड के बारे में डेटा दर्ज कर सकता है (उदा: उपयोगकर्ता मॉडल में "first_name", "last_name", 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 –