5

Ho due modelli in Django: Utente (predefinito da Django) e UserProfile. I due sono collegati tramite una chiave esterna.Come creare una vista che salva gli oggetti Utente e Profilo utente in 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) 

sto usando UserCreationForm (pre-definito da Django) per il modello d'uso, e ha creato un'altra forma per ProfiloUtente in forms.py

#UserCreationForm for User Model 

class UserProfileForm(ModelForm): 
    class Meta: 
    model = UserProfile 
    exclude = ("user",) 

I caricare entrambi questi moduli in un modello, registration.html, in modo che il cliente del sito Web possa immettere dati relativi ai campi contenuti in entrambi i modelli (ad es .: "first_name", "last_name" nel modello utente, "posizione" nel modello UserProfile).

Per la vita di me, non riesco a capire come creare una vista per questo modulo di registrazione. Quello che ho provato fino ad ora creerà l'oggetto User, ma non assocerà altre informazioni come la posizione nell'oggetto UserProfile corrispondente. Qualcuno mi può aiutare? Questo è quello che ho attualmente:

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) 
+0

http://stackoverflow.com/questions/569468/django-multiple-models-in-one-template-using-forms –

risposta

3

Ci siamo quasi :)

def register(request): 
    if request.method == 'POST': 
     form1 = UserCreationForm(request.POST) 
     form2 = UserProfileForm(request.POST) 
     if form1.is_valid() and form2.is_valid(): 
      user = form1.save() # save user to db 
      userprofile = form2.save(commit=False) # create profile but don't save to db 
      userprofile.user = user 
      userprofile.location = get_the_location_somehow() 
      userprofile.save() # save profile to db 

    else: 
     form1 = UserCreationForm() 
     form2 = UserProfileForm() 
    c = { 
     'form1':form1, 
     'form2':form2, 
    } 
    c.update(csrf(request)) 
    return render_to_response("registration/register.html", c) 

Per chiarire un po ', form.save() crea un'istanza del modello e lo salva al db. form.save(commit=False) Crea semplicemente un'istanza, ma non salva nulla in db.

Problemi correlati