如何在Django中使用bootstrap模式上传头像

6ss1mwsb  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(109)

我正在做一个Web应用程序项目,用户可以更新个人资料图片和他们的名字,姓氏,生物,URL和用户名。我使用bootstrap 4模式在user_update.html中实现个人资料图片更新。
user_update.html

{% extends 'users/base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block maincss %}
<link rel="stylesheet" type="text/css" href="{% static 'users/stylesheet/main.css' %}">
{% endblock maincss %}
{% block updateprofilecontent %}
<main role="main" class="container">
  <div class="row">
    <div class="col-md-8">
      <div class="content-section">
        <div class="media">
          <a href="#" data-toggle="modal" data-target="#profilePicModal">
            <img class="rounded-circle account-img" src="{{ user.profile_picture.url }}">
          </a>
        </div>
        <form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Edit Profile</legend>
                {{ u_form|crispy }}
            </fieldset>
            <div class="form-group">
                <button class="btn btn-outline-info" type="submit">Update</button>
            </div>
        </form>
      </div>
    </div>
  </div>
</main>

<!-- Modal -->
<div class="modal fade" id="profilePicModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Choose Profile Picture</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        {{ p_form|crispy }}
      </div>
    </div>
  </div>
</div>
{% endblock updateprofilecontent %}

urls.py

from django.contrib import admin
from django.urls import path
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path("admin/", admin.site.urls),
    path('user/update/', user_views.userUpdate, name='user-update'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

用户/forms.py

class UserUpdateForm(forms.ModelForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'username'}), label='', required=False)
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'First Name'}), label='', required=False)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'Last Name'}), label='', required=False)
    bio = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'Bio'}), label='', required=False)
    url = forms.CharField(widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'URL'}), label='', required=False)

    class Meta:
        model = User 
        fields = ['username', 'first_name', 'last_name', 'bio', 'url']


class ProfilePicUpdateForm(forms.ModelForm):
    profile_picture = forms.ImageField(widget=forms.FileInput(attrs={}), label='', required=False)

    class Meta:
        model = User 
        fields = ['profile_picture']

views.py

def userUpdate(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfilePicUpdateForm(request.POST, request.FILES, instance=request.user)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            return redirect('timeline')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfilePicUpdateForm(instance=request.user)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }

    return render(request, 'users/user_update.html', context)

我可以从引导模式的“选择文件”选项中选择个人资料图片。其他用户个人资料信息,如用户名,生物,网址等正确更新。但个人资料图片不更新。它只能选择个人资料图片。我如何更新个人资料图片也与其他用户信息,如用户名,生物,网址等?

sq1bmfud

sq1bmfud1#

您可以在views.py中使用UpdateView。它只对您编辑的字段进行更改,其余的保持不变。

from django.views.generic import DetailView, UpdateView

class UpdateUserProfileView(UpdateView, DetailView):
    """Updating profile"""
    model = User
    template_name = 'users/user_update.html'
    form_class = ProfilePicUpdateForm
    context_object_name = 'get_car'

    def get_context_data(self, **kwargs):
        kwargs['some_data'] = SomeData.objects.all() #some data if you need in your template
        return super().get_context_data(**kwargs)

    def get_success_url(self):
        return reverse('detail_user_page', kwargs={'slug': self.user.slug})

    def form_valid(self, form):
        self.object = form.save(commit=False)
        # some doing if you need
        self.object.save()
        return super().form_valid(form)

相关问题