How to create a UserProfile form in Django with first_name, last_name modifications?

前端 未结 7 1294
挽巷
挽巷 2020-11-29 19:55

If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it.

However, I could not find any he

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 20:33

    I stumbled across this today and after some googling I found a solution that is a bit cleaner in my opinion:

    #in forms.py
    class UserForm(forms.ModelForm):
        class Meta:
            model = User
            fields = ["username", "email"]
    
    class UserProfileForm(forms.ModelForm):
        class Meta:
            model = UserProfile
    
    #in views.py
    def add_user(request):
        ...
        if request.method == "POST":
            uform = UserForm(data = request.POST)
            pform = UserProfileForm(data = request.POST)
            if uform.is_valid() and pform.is_valid():
                user = uform.save()
                profile = pform.save(commit = False)
                profile.user = user
                profile.save()
                ....
        ...
    
    #in template
    
    {{ uform.as_p }} {{ pform.as_p }}

    Source

提交回复
热议问题