С изображением Django не связано ни одного файла, хотя у меня пустое значение - PullRequest
0 голосов
/ 25 мая 2019

Когда пользователь регистрировался, я использовал его, чтобы изображение было применено к этой учетной записи пользователя. Но из-за расположения файлов у меня больше не может быть такого, поэтому я пытаюсь сделать так, чтобы, когда пользователь регистрируется, поле изображения оставалось пустым, чтобы я мог отобразить поддельное изображение по умолчанию в шаблоне. Но когда пользователь регистрируется или просматривает свой профиль или входит в систему, выдает ошибку The 'image' attribute has no file associated with it.. Я думал, что смогу обойти это, имея blank=True и null=True, но по какой-то причине он продолжает выдавать эту ошибку.

Модель:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(verbose_name='Profile Picture', upload_to='profile_pictures', blank=True, null=True)

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self, force_insert=False, force_update=False, using=None):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

Просмотров: 1009 * *

def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    review = Post.objects.filter(live=False, author=request.user)
    post = Post.objects.filter(live=True, author=request.user)

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

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

HTML:

{% if user.profile.image.url %}
                <div class="profile-image">
                    <img class="rounded-circle account-img" src="{{ user.profile.image.url }}" alt="{{ user.profile.image }}">
                </div>
                {% elif user.profile.image.url == None %}
                <div class="profile-image">
                    <img class="rounded-circle account-img" src="{% static '/public/images/default.jpg' %}" alt="{{ user.profile.image }}">
                </div>
                {% endif %}

Было бы замечательно, если бы у кого-нибудь было какое-либо решение.

1 Ответ

0 голосов
/ 25 мая 2019

Я думаю, вам следует добавить проверку в методе профиля save.

def save(self, force_insert=False, force_update=False, using=None):
    super().save()

    if self.image:
        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

Кроме того, вы должны проверить объект image в шаблоне и затем получить доступ кurl атрибут и сделать предварительный просмотр.Вот как.

{% if user.profile.image %}
    <div class="profile-image">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}" alt="{{ user.profile.image }}">
    </div>
{% else %}
    <div class="profile-image">
        <img class="rounded-circle account-img" src="{% static '/public/images/default.jpg' %}" alt="{{ user.profile.image }}">
    </div>
{% endif %}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...