How to request existing files from a form in django

i’m trying to add a feature for users to update thier profile, but i want to be able to get thier existing informations so they don’t have to fill all the form again. I have tried request.POST on the form but it doesn’t work, it does not update the form with the existing user informations.

views.py

def profile_update(request):
    info = Announcements.objects.all()
    categories = Category.objects.all()

    Profile.objects.get_or_create(user=request.user)
    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'Acount Updated Successfully!')
            return redirect('userauths:profile')
    else:
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form,
        'info': info,
        'categories': categories
    }

    return render(request, 'userauths/profile_update.html', context)





# profile update function
def profile_update(request):
    info = Announcements.objects.all()
    categories = Category.objects.all()

    Profile.objects.get_or_create(user=request.user)
    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'Acount Updated Successfully!')
            return redirect('userauths:profile')
    else:
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
    
    context = {
        'u_form': u_form,
        'p_form': p_form,
        'info': info,
        'categories': categories
    }

    return render(request, 'userauths/profile_update.html', context)

profile_update.html

{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}

<main>

<section class="pt-0">
    <!-- Main banner background image -->
    <div class="container-fluid px-0">
        <div class="bg-blue h-100px h-md-200px rounded-0" style="background:url(assets/images/pattern/04.png) no-repeat center center; background-size:cover;">
        </div>
    </div>
    <div class="container mt-n4">
        <div class="row">
            <!-- Profile banner START -->
            <div class="col-12">
                <div class="card bg-transparent card-body p-0">
                    <div class="row d-flex justify-content-between">
                        <!-- Avatar -->
                        <div class="col-auto mt-4 mt-md-0">
                            <div class="avatar avatar-xxl mt-n3">
                                <img class="avatar-img rounded-circle border border-white border-3 shadow" src="{% static 'assets/images/avatar/def.png' %}" alt="">
                            </div>
                        </div>
                        <!-- Profile info -->
                        <div class="col d-md-flex justify-content-between align-items-center mt-4">
                            <div>
                                <h1 class="my-1 fs-4">No Name Yet <i class="bi bi-patch-check-fill text-info small"></i></h1>
                            </div>
                            <!-- Button -->
                            
                        </div>
                    </div>
                </div>
                
            </div>
        </div>
    </div>
</section>
<!-- =======================
Page Banner END -->

<!-- =======================
Page content START -->
<section class="pt-0">
    <div class="container">
        <div class="row">

            
            <!-- Right sidebar END -->

            <!-- Main content START -->
            <div class="col-xl-9">
                <!-- Edit profile START -->
                <div class="card bg-transparent border rounded-3">
                    <!-- Card header -->
                    <div class="card-header bg-transparent border-bottom">
                        <h3 class="card-header-title mb-0">Hey {{ request.user|title }}, Let's fix your profile</h3>
                    </div>
                    <!-- Card body START -->
                    <div class="card-body">
                        <!-- Form -->
                        <form class="row g-4" method="POST" enctype="multipart/form-data">
                            {% csrf_token %}
                            <!-- Profile picture -->
                            <div class="col-12 justify-content-center align-items-center">
                                <label class="form-label">Profile picture</label>
                                <div class="d-flex align-items-center">
                                    <label class="position-relative me-4" for="uploadfile-1" title="Replace this pic">
                                        <!-- Avatar place holder -->
                                        <span class="avatar avatar-xl">
                                            <img id="uploadfile-1-preview" class="avatar-img rounded-circle border border-white border-3 shadow" src="{% static 'assets/images/avatar/def.png' %}" alt="">
                                        </span>
                                        <!-- Remove btn -->
                                        <!-- <button type="button" class="uploadremove"><i class="bi bi-x text-white"></i></button> -->
                                    </label>
                                    <!-- Upload button -->
                                    <label class="btn btn-primary-soft mb-0" for="uploadfile-1">{{p_form.image}}</label>
                                    <input id="uploadfile-1" class="form-control d-none" type="file">
                                </div>
                            </div>

                            <!-- Full name -->
                            <div class="col-12">
                                <!-- <label class="form-label">Full name</label> -->
                                <div class="input-group">
                                    <!-- {{p_form|crispy}} -->
                                    <!-- {{u_form|crispy}} -->
                                    {{p_form.first_name.label}} <br>
                                    {{p_form.first_name}} 
                                    
                                    {{p_form.last_name.label}} <br>
                                    {{p_form.last_name}}
                                </div>
                            </div>

                            <!-- Username -->
                            <div class="col-md-6">
                                <label class="form-label">Username</label>
                                <div class="input-group">
                                    {{u_form.username}}
                                </div>
                            </div>

                            <!-- Email id -->
                            <div class="col-md-6">
                                <label class="form-label">Email id</label>
                                {{p_form.email}}
                            </div>

                            <!-- Phone number -->
                            <div class="col-md-6">
                                <label class="form-label">Phone number</label>
                                {{p_form.phone}}
                            </div>

                            <!-- Location -->
                            <div class="col-md-6">
                                <label class="form-label">Location</label>
                                {{p_form.country}}
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Bio</label>
                                {{p_form.bio}}
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Website</label>
                                {{p_form.website}}
                            </div>
                            
                            <!-- About me -->
                            <div class="col-12">
                                <label class="form-label">About me</label>
                                {{p_form.aboutme}}
                                <div class="form-text">Brief description for your profile.</div> 
                            </div>

                            <!-- Education -->
                            <div class="col-12">
                                <label class="form-label">Education</label> <br><br>


                                <label class="form-label">School Name - 1</label>
                                {{p_form.school_name1}}
                                <label class="form-label">School Details and Major - 1</label>
                                {{p_form.school_desc1}} <br>

                                <label class="form-label">School Name - 2</label>
                                {{p_form.school_name2}}
                                <label class="form-label">School Details and Major - 2</label>
                                {{p_form.school_desc2}} <br>

                                <label class="form-label">School Name - 3</label>
                                {{p_form.school_name3}}
                                <label class="form-label">School Details and Major - 3</label>
                                {{p_form.school_desc3}}
                            </div>

                            
                            <div class="row g-4 mt-3">
                                <!-- Linked account START -->
                                <div class="col-lg-12">
                                    <div class="card bg-transparent border rounded-3">
                                        <!-- Card header -->
                                        <div class="card-header bg-transparent border-bottom">
                                            <h5 class="card-header-title mb-0">Skills</h5>
                                        </div>
                                        <!-- Card body START -->
                                        <div class="card-body pb-0">
                                            <div class="card-body">
                                                <!-- Facebook username -->
                                                <div class="mb-3">
                                                    <label class="form-label"><i class="fas fa-star  me-2"></i>Enter Skills</label>
                                                    {{p_form.skill1}} <br>
                                                    {{p_form.skill2}} <br>
                                                    {{p_form.skill3}} <br>
                                                    {{p_form.skill4}} <br>
                                                    {{p_form.skill5}} <br>
                                                </div>
       
                                            </div>
                                            
                                        </div>
                                        <!-- Card body END -->
                                    </div>
                                </div>

                            </div>

                            <div class="row g-4 mt-3">
                                <!-- Linked account START -->
                                <div class="col-lg-12">
                                    <div class="card bg-transparent border rounded-3">
                                        <!-- Card header -->
                                        <div class="card-header bg-transparent border-bottom">
                                            <h5 class="card-header-title mb-0">Social Media Accounts</h5>
                                        </div>
                                        <!-- Card body START -->
                                        <div class="card-body pb-0">
                                            <div class="card-body">
                                                <!-- Facebook username -->
                                                <div class="mb-3">
                                                    <label class="form-label">Enter Links to Social Media</label> <br>
                                                    <i class="fab fa-facebook-square me-2"></i>  {{p_form.facebook}} <br>
                                                    <i class="fab fa-twitter me-2"></i>  {{p_form.twitter}} <br>
                                                    <i class="fab fa-instagram me-2"></i>  {{p_form.instagram}} <br>
                                                    <i class="fab fa-linkedin"></i> {{p_form.linkedin}} <br>
                                                    
                                                </div>
       
                                            </div>
                                            
                                        </div>
                                        <!-- Card body END -->
                                    </div>
                                </div>

                            </div>
                            <!-- Save button -->
                            <div class="d-sm-flex justify-content-end">
                                <button type="submit" class="btn btn-primary mb-0">Save changes</button>
                            </div>
                        </form>
                    </div>
                </div>


        {% endblock content %}

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    first_name = models.CharField(max_length=1000, null=True, blank=True)
    last_name = models.CharField(max_length=1000, null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    phone = models.IntegerField(null=True, blank=True)
    bio = models.CharField(max_length=1000, null=True, blank=True)
    aboutme = models.TextField(null=True, blank=True, verbose_name="About Me")
    country = models.CharField(max_length=1000, null=True, blank=True)
    cover_photo = models.ImageField(default='default.jpg', upload_to="profile_pic")
    image = models.ImageField(default='default.jpg', upload_to="profile_pic")
    joined = models.DateTimeField(auto_now_add=True, null=True)
    creator = models.BooleanField(default=False)
    normal_user = models.BooleanField(default=True)
    facebook = models.URLField(max_length=10000, null=True, blank=True)
    twitter = models.URLField(max_length=10000, null=True, blank=True)
    instagram = models.URLField(max_length=10000, null=True, blank=True)
    linkedin = models.URLField(max_length=10000, null=True, blank=True)
    website = models.URLField(max_length=10000, null=True, blank=True)
    school_name1 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Name (1)")
    school_desc1 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Description (1)")
    school_name2 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Name (2)")
    school_desc2 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Description (2)")
    school_name3 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Name (3)")
    school_desc3 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="School Description (3)")
    skill1 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="First Skill")
    skill2 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Second Skill")
    skill3 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Third Skill")
    skill4 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Fourth Skill")
    skill5 = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Fifth Skill")
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

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

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        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)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

class ProfileUpdateForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'email', 'bio', 'country', 'image', 'aboutme', 'website', 'phone', 'facebook',  'twitter', 'instagram', 'linkedin', 'website', 'school_name1', 'school_desc1', 'school_name2', 'school_desc2', 'school_name3', 'school_desc3', 'skill1', 'skill2', 'skill3', 'skill4', 'skill5']

Are you using the standard User object or a custom user? If a custom user, please post your User object.

Please post your Profile object and both your UserUpdateForm and your ProfileUpdateForm.

Also, in the else clause of your if request.method == "POST" condition, you have:

u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)

It does not help to supply either request.POST or request.FILES at this location. This part of the code is reached on a “GET” not a “POST”, so there’s never going to be anything in request.POST.

1 Like

okay thanks for your response, let me update my question with the relevant files, and it not a Custom User

I’m not seeing anything specifically wrong here. What is happening that you’re not expecting to see happen, or what isn’t happening that you’re expecting to see? I need a better understanding of exactly what’s happening.

One thing that I don’t see is any error handling on the form. If either form.is_valid is false, then it’s just going to redisplay the form with the original data. But since you’re not rendering errors on the form, you won’t see what the problems are.

See Working with forms | Django documentation | Django for more information.

what i want to see - when i click the update profile button i want to see the instance of the informations the user already have then i can just update the old one which is already filled in the form to a new one.

what i don’t want to see - When i click the update profile button, all the forms stil renders blank and that is not what i want

Just wanting to be clear here - you’re saying that both the User form and the Profile form show no data when you initially render them?

I noticed in your template you’ve got:

Can you try this with using this complete form-rendering rather than all the individual fields? It’ll help narrow down where the problem is occurring, and if there is an error in the forms, this will render the error messages.

Also, I’m not sure that you can specify a default for a FileField using just a name.
The other thing you can try is to change your definitions of cover_photo and image to remove the default attribute. (Or, you could just temporarily remove those definitions from your model to determine whether they are causing the problem.)

[Late edit]
There is one more potential issue I see. You do have an overlap of field names in your forms - you have an email field in both your UserUpdateForm and ProfileUpdateForm. When you have two fields with the same name in two forms on the same page, you must use the prefix attribute on at least one of the forms.

Also, when you do submit the form, do you get any error messages on the console where you’re running the server?

[Late edit #2]
Also realized you don’t show usage of the login_required decorator on your view. Are you sure you’re logged in when you’re trying this?

thanks for your comment, yes i’m logged in when trying that
let me user this now {{p_form|crispy}} {{u_form|crispy}} and see if i get any error message as you’ve said