Изменить картинку профиля на django - PullRequest
0 голосов
/ 20 февраля 2020

Я пытаюсь создать модуль редактирования профиля, но ему тоже нужно изменить изображение профиля. Я уже пробовал код, но картинка не меняется, когда я нажимаю кнопку отправки

Вот мнения .py для update_profile

def update_profile(request):
    if request.method == 'POST':
        user_form = UserInfoForm(request.POST, instance=request.user )
        profile_form = UserProfileInfoForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():            
            user = user_form.save()            
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user 
            if 'profile_pic' in request.FILES:                
                profile.profile_pic = request.FILES['profile_pic']           
            profile.save()         
            return redirect('/profile/')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserInfoForm(instance=request.user)
        profile_form = UserProfileInfoForm(instance=request.user.profile)
    return render(request, 'profile.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

вот форма

<form role="form" class="form-horizontal" method="post">                          

                          {% load staticfiles %}
                          {% block body_block %}

                                {% if registered %}
                                  <h1>Update Profile Success!</h1>
                                {% else %}    
                                  <form class="cmxform form-horizontal style-form" id="commentForm" enctype="multipart/form-data" method="POST" action="">
                                    {% csrf_token %}        
                                    {{ user_form.as_p }}
                                    {{ profile_form.as_p }}

                                    <input type="submit" name="" value="Update">                          
                                  </form>

                                {% endif %}

                          {% endblock %}                             

                        </form>

urls.py (уже добавлено + static []) от чьего-то предложения и до сих пор не работает

app_name = 'polls'
urlpatterns = [
    path('profile/', views.update_profile, name='profile'),        
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Надеюсь, что кто-то может решить проблему, спасибо.

Ответы [ 2 ]

1 голос
/ 20 февраля 2020

Вы не передаете файл в свою форму, поэтому добавьте request.FILES в качестве второго параметра в форму, содержащую изображение в вашем представлении, например

profile_form = UserProfileInfoForm(request.POST, request.FILES, instance=request.user.profile
1 голос
/ 20 февраля 2020

Добавьте enctype в форму HTML.

<form role="form" class="form-horizontal" method="post" <b>enctype="multipart/form-data"</b>>
    <!-- Your html elements -->
</form>

также укажите request.FILES в форме.

profile_form = UserProfileInfoForm(request.POST, <b>request.FILES,</b> instance=request.user.profile)

удалите эти строки :

if 'profile_pic' in request.FILES:                
    profile.profile_pic = request.FILES['profile_pic']

Если вы передаете request.FILES в UserProfileInfoForm, вам не нужно напрямую назначать его профилю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...