(Django)无法为用户头像上传图像

时间:2018-03-06 07:55:55

标签: python django django-models django-forms django-views

所以我试图让用户通过允许他们上传他们的图像来更新他们的头像/个人资料图像+我想实现一个图像裁剪器,以便他们可以将图像裁剪为1比1的比例。我认为首先要做的就是上传。

我试图让它成为可能,但我想我几乎到处都是。

我正在使用的图像字段就像是User表的扩展名我基本上称之为扩展用户,其中包含所有额外信息。

媒体设置2我可以从管理面板上传文件,它们会正常显示。

Views.py

@login_required
def useravatar(request, user_pk):
    if request.method == 'POST':
        form = UpdateProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.extendeduser.avatar = form.cleaned_data('avatar')
            user.save()
            messages.success(request, 'Your avatar was successfully Uploaded!')
            return redirect('useravatar', user_pk=request.user.pk)
    logged_in_user = get_object_or_404(User, pk=request.user.pk)
    requested_user = get_object_or_404(User, pk=user_pk)
    driverslicence = DriversLicenceCategories.objects.all()
    feedback = FeedbackSupportForm()
    password = PasswordChangeForm(request.user)
    avatar = UpdateProfileForm(instance=request.user)
    context = {
        'avatar'        : avatar,
        'logged_in_user': logged_in_user,
        'requested_user': requested_user,
        'feedback'      : feedback,
        'password'      : password,
    }
    return render(request, 'user/avatar.html', context)

Models.py

class ExtendedUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nickname = models.CharField(max_length=20)
    birthdate = models.DateField(null=True, blank=True)
    postal_code = models.CharField(max_length=10)
    phone_number_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+4570131415'. Up to 15 digits allowed.")
    phone_number = models.CharField(max_length=16, validators=[phone_number_regex], blank=True)
    phone_number_show = models.BooleanField(default=False)
    emergency_number = models.CharField(max_length=16, validators=[phone_number_regex], blank=True)
    drivers_licence = models.ManyToManyField(DriversLicenceCategories, blank=True)
    avatar = models.ImageField(upload_to='users/avatars', default='static/img/userpreload.png')
    background = models.ImageField(upload_to='users/backgrounds', default='static/img/userpreload.png')

forms.py

class UpdateProfileForm(forms.ModelForm):
    postal_code = forms.CharField(max_length=10, required=True)
    phone_number = forms.CharField(max_length=16, required=True)
    phone_number_show = forms.BooleanField(required=False)
    avatar = forms.ImageField()
    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'postal_code', 'phone_number', 'phone_number_show', 'avatar')

然后当然有html文件,格式为

<form action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="custompanel no-m-bottom">
                        <h3>Avatar</h3>
                        <hr style="border-color:rgba(0, 0, 0, 1);">
                        <div class="form-group">
                            <div class="setting-user-avatar">
                                <img class="user-avatar" src="{{ logged_in_user.extendeduser.avatar.url }}">
                            </div>
                            <label for="id_avatar">Change profile image.</label>
                            <input id="id_avatar" style="color: #000;" class="victext-input vic-block full-width" type="file" name="avatar"></input>
                            <small id="id_avatarHelpBlock" class="form-text text-muted">
                                 Current: <a href="{{ logged_in_user.extendeduser.avatar.url }}">{{ logged_in_user.extendeduser.avatar.url }}</a>
                            </small>
                        </div>
                    </div>
                    <button type="submit" class="vicbtn vicbtn-green w-100">Save</button>
                </form>

我希望有人会帮助我让这个工作,因为我基本上完全破碎了

2 个答案:

答案 0 :(得分:2)

试试这个: 从您的视图更新此行:

user.extendeduser.avatar = request.FILES['avatar']

答案 1 :(得分:1)

尝试使用此功能,我认为,即使将图像添加到扩展模型的头像列之前,您也在保存配置文件

from .models import ExtendedUser

def useravatar(request, user_pk):
    if request.method == 'POST':
        form = UpdateProfileForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            user = form.save()
            av = ExtendedUser.objects.get(user_id=user_pk)
            av.avatar = request.FILES['avatar']
            // other columns if you want to save, same as above line, except request.FILES will be request.POST['input_name']
            av.save()
            messages.success(request, 'Your avatar was successfully Uploaded!')
            return redirect('useravatar', user_pk=request.user.pk)

并更改您的HTML

<form action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="custompanel no-m-bottom">
                        <h3>Avatar</h3>
                        <hr style="border-color:rgba(0, 0, 0, 1);">
                        <div class="form-group">
                            <div class="setting-user-avatar">
                                <img class="user-avatar" src="{{ logged_in_user.extendeduser.avatar.url }}">
                            </div>
                            <label for="id_avatar">Change profile image.</label>
                            {{ avatar.as_p }}
                            <small id="id_avatarHelpBlock" class="form-text text-muted">
                                 Current: <a href="{{ logged_in_user.extendeduser.avatar.url }}">{{ logged_in_user.extendeduser.avatar.url }}</a>
                            </small>
                        </div>
                    </div>
                    <button type="submit" class="vicbtn vicbtn-green w-100">Save</button>
                </form>