M
M
Meekey2018-04-24 22:17:31
Django
Meekey, 2018-04-24 22:17:31

django photo not saving. What to fix?

I do not understand why the photo is not saved when the user adds it.
models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    location = models.CharField(max_length = 4, null=True, blank = True)
    phone = models.CharField(max_length = 11, null=True, blank = True)
    image = models.ImageField(blank=True, upload_to='user_images',
        default='user_images/default-user.png')

forms.py
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')


class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('phone', 'location', 'image')

views.py
@login_required
def edit_profile(request, username):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(
                request,
                "Информация профиля успешно отредактирована!"
            )
            return HttpResponseRedirect(reverse('profile', kwargs={'username': request.user.username}))
    else:
        user = User.objects.get(username=username)
        user_form = UserForm(instance=user)
        profile_form = ProfileForm(instance=user.profile)
    return render(request, 'account/profile_edit.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

@login_required
def view_profile(request, username):
    user = User.objects.get(username=username)
    return render(request, 'account/profile.html', {'user': user,})

profile.html
<div class="col s6">
        <h3>{{ user.last_name }} {{ user.first_name }}</h3>
        <p>Email: {{ user.email }}</p>
        <p>Телефон: {{ user.profile.phone }}</p>
        <p>Кабинет: {{ user.profile.location }}</p>
    </div>
    <div class="col s6">
    {% if user.profile.image %}
        <img height="350" width="300" src="{{ user.profile.image.url }}">
        {%else%}
        <p></p>
    {%endif%}
    </div>
    <a href="{% url 'edit_profile' username=request.user.username %}">Изменить профиль</a></li>
</div>

profile_edit.html
<form method="post">
  {% csrf_token %}
  {{ user_form.as_p }}
  {{ profile_form.as_p }}
  <button type="submit">Сохранить изменения</button>
</form>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-04-24
@Meekey

How to submit an image through a Django form?

V
Vadim kyklaed, 2018-04-24
@kyklaed

profile_form = ProfileForm(request.POST, request.FILES,instance=request.user.profile)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question