Reputation: 3176
I am able to update the image of each user's profile picture. But not through the code. Though it doesn't give me any error.
u_form = For changing the username. p_form = For changing the picture in their profile.
NOTE: Profile has one to one relation with the Profile model.
settings.py file section:
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
models.py for Profile model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpeg', upload_to='profile_pics')
status = models.TextField(max_length='200')
def __str__(self):
return self.user.username
forms.py for the same:
class ProfileUpdate(forms.ModelForm):
class Meta:
model = Profile
fields = ['image',]
Main views.py file:
.
.
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm as uc
from django.contrib.auth.forms import AuthenticationForm as af
.
.
@login_required(login_url='/login')
def update_profile(request):
user = request.user
if request.method == 'POST':
u_form = UserUpdate(request.POST, instance=user)
p_form = ProfileUpdate(request.POST, request.FILES, instance=user)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, 'The profile has been updated.')
return redirect('/profile')
else:
#instance: to get pre-filled data of user
u_form = UserUpdate(instance=user)
p_form = ProfileUpdate(instance=user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'update_profile.html', context)
HTML form "update_profile.html":
<form action="{% url 'update_profile' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ u_form }}
{{ p_form }}
<button type="submit">submit</button>
</form>
Upvotes: 0
Views: 64
Reputation: 83
Try this:
p_form = ProfileUpdate(request.POST, request.FILES, instance=user.profile)
Upvotes: 1