I intend to make a user profile model with profile picture in django.
Everything works fine but I can't update the profile picture of the user.
The form is being displayed on the website but on clicking submit, no changes are visible in the database and the image is also not getting uploaded.
Below is my code for the form in HTML.
<form method="POST" action="{% url 'profile' %}" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<br><br>
<div class="mb-3"><button class="btn btn-primary btn-sm" name="_picture" type="submit">Change Photo</button></div>
</form>
Below is the code models.py, for creating user profile model.
class UserProfileInfo(models.Model):
# Create relationship (don't inherit from User!)
user = models.OneToOneField(User, on_delete=models.CASCADE)
isInstructor = models.BooleanField(default=False)
department = models.ForeignKey(Department,on_delete=models.CASCADE)
role = models.ManyToManyField(Role)
profile_picture = models.FileField(upload_to='static/profile_pic/'+str(time.time()),default='d.jpeg')
address = models.TextField(max_length=256)
city = models.TextF
class UpdateProfilePic(ModelForm):
class Meta:
model = UserProfileInfo
fields = ['profile_picture']
Below is the code for views.py
@login_required
def profile(request):
current_user_profile = UserProfileInfo.objects.get(user=request.user)
current_user = request.user
form = UpdateProfilePic(instance=current_user_profile)
context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
if request.method=='POST':
if '_user' in request.POST:
temp_user = request.user
temp_user.username = request.POST.get('username')
temp_user.email = request.POST.get('email')
temp_user.first_name = request.POST.get('first_name')
temp_user.last_name = request.POST.get('last_name')
temp_user.save()
context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
return render(request,'instructor_app/profile.html',context)
if '_profile' in request.POST:
temp_user_profile = UserProfileInfo.objects.get(user=request.user)
temp_user_profile.address = request.POST.get('address')
temp_user_profile.city = request.POST.get('city')
temp_user_profile.pincode = request.POST.get('pincode')
temp_user_profile.save()
context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
return render(request,'instructor_app/profile.html',context)
if '_picture' in request.POST:
print("in picture")
form = UpdateProfilePic(request.POST, instance=UserProfileInfo.objects.get(user=request.user))
form.save()
context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form}
return render(request,'instructor_app/profile.html',context)
else:
return render(request,'instructor_app/profile.html',context)
Help me with the code, please!