更新个人资料图片

时间:2018-10-02 14:21:55

标签: python django

所以我正在开发一个小型django应用程序,用户可以在其中查看和修改个人资料,但是我不知道如何在个人资料图片下提供一个按钮,允许用户选择一个新按钮以及何时选择它将他重定向到与新个人资料图片相同的页面,任何帮助或想法都将非常有用!
这是我尝试过的:

forms.py

def profile(request):
if request.method == 'POST':
    form = picture_form(request.POST, request.FILES)
    if form.is_valid():
        profile = Profile.objects.get(user=request.user)
        profile.image = form.cleaned_data['image']
        profile.save()
        return redirect(reverse('profile'))



else:
 for usr in User.objects.all():
    if request.user.get_full_name() == usr.get_full_name():
        prf = Profile.objects.filter(user=usr)
        form = picture_form()
        return render(request, 'store/profile.html', {'profile': prf, 'form': form})

views.py

   {% if prf.image %}

            <div class="profile-img">
                <img src="{{ prf.image.url }}" id="prf_img" alt=""/>

            </div>
            {% else %}
            <div class="profile-img">
                <img src="{% static 'img/empty-profile-picture.png' %}" id="prf_img" alt=""/>

            </div>
            {% endif %}

            <!--<a href="{% url 'upload_picture' %}">  <div class="file btn btn-lg " >
                Change Photo
                   <input type="file" name="file"/>
               </div></a> -->
            <form method="post" action="{% url 'profile' %}" enctype="multipart/form-data">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" class="btn btn-outline-success" value="upload">

            </form>
        </div>

模板

navigationOptions

1 个答案:

答案 0 :(得分:0)

Django有一个很棒的通用编辑视图,称为UpdateView。您可以执行以下操作:

models.py

class Profile(models.Model):
    image = models.ImageField()

views.py

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView

@method_decorator(login_required, name='dispatch')
class UpdateProfileView(UpdateView):
    model = Profile
    fields = ['image']
    template_name_suffix = '_update_form'
    success_url = ''

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

profile_update_form.html

<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update">
</form>

urls.py

from . import views
path('<int:pk>/update/', views.UpdateProfileView.as_view(), name='profile-update')