Django, updating a user profile with a ModelForm

后端 未结 2 1186
孤城傲影
孤城傲影 2021-01-02 18:39

I\'m trying to display a simple ModelForm for a user\'s profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful

相关标签:
2条回答
  • 2021-01-02 19:08

    You could also use a generic view:

    from django.views.generic.create_update import update_object
    
    @login_required
    def user_profile(request):
        return update_object(request,
                            form_class=UserProfileForm,
                            object_id=request.user.get_profile().id,
                            template_name='profile/index.html')
    
    0 讨论(0)
  • 2021-01-02 19:17

    Try this:

    @login_required
    def user_profile(request):
        success = False
        user = User.objects.get(pk=request.user.id)
        if request.method == 'POST':
            upform = UserProfileForm(request.POST, instance=user.get_profile())
            if upform.is_valid():
                up = upform.save(commit=False)
                up.user = request.user
                up.save()
                success = True
        else:
            upform = UserProfileForm(instance=user.get_profile())       
    
        return render_to_response('profile/index.html',
            locals(), context_instance=RequestContext(request))
    
    0 讨论(0)
提交回复
热议问题