I Need Help in this problem
Tags: django, help, python
Published: 2021-01-22 13:28:52

Hello Guys! I am making a profile update page in my django website.
The following is the problem that I am facing:
<li>Whenever I clicks on "Update Pic" button the name gets blank even in admin</li>
This is  my views.py
```python
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from .models import Profileforusers
from .forms import UserUpdateForm, PicUpdateForm, BioUpdateForm

# Create your views here.

@login_required
def userprofile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = PicUpdateForm(request.POST, request.FILES, instance=request.user.profileforusers)
        bio_form = BioUpdateForm(request.POST, instance=request.user.profileforusers)
        if u_form.is_valid():
            u_form.save()
            messages.success(request, "Profile Is Updated Successfully!")
            return redirect("profilesettings")
        elif p_form.is_valid():
            p_form.save()
            messages.success(request, "Profile Picture Is Updated Successfully!")
            return redirect("profilesettings")
        elif bio_form.is_valid():
            bio_form.save()
            messages.success(request, "Bio Updated Successfully!")
            return redirect("profilesettings")
            
    else:
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = PicUpdateForm(request.POST, instance=request.user.profileforusers)
        bio_form = BioUpdateForm(request.POST, instance=request.user.profileforusers)
        context = {
            'u_form': u_form,
            'p_form': p_form,
            'bio_form': bio_form
        }
    return render(request, 'siteaccount/usersettings.html', context)
```
This is My signals.py
```python
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profileforusers

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profileforusers.objects.create(user=instance)
    

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profileforusers.save()
```
This is My model
```python
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.

class Profileforusers(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_bio = models.CharField(max_length=150, default='Write About Yourself')
    user_image = models.ImageField(upload_to='thephotos/userphotos', default='defaultpicture.jpg')

    def __str__(self):
        return f"Profile Of {self.user.username}"
    
    def save(self, *args, **kwargs):
        super(Profileforusers, self).save(*args, **kwargs)
        usr_img = Image.open(self.user_image.path)
        if usr_img.height>300 or usr_img.width>300:
            output_img = (300, 300)
            usr_img.thumbnail(output_img)
            usr_img.save(self.user_image.path)
```
This is my forms.py
```python
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profileforusers

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()
    class Meta:
        model = User
        fields = ['first_name']
        widgets = {
            'first_name' : forms.TextInput(attrs={'class': 'form-control'})
        }

class PicUpdateForm(forms.ModelForm):
    class Meta:
        model = Profileforusers
        fields = ['user_image']

class BioUpdateForm(forms.ModelForm):
    class Meta:
        model = Profileforusers
        fields = ['user_bio']
```
And this is usersettings.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Profile Update Page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <div class="profilebox">
            <img src="{{user.profileforusers.user_image.url}}" id="output" height="200" width="200" />
            <strong><p class="datejnd">Date Joined: {{user.date_joined|date:"F d, Y"}}</p></strong>
            <strong><p class="datejnd">Username: {{user.username}}</p></strong>
            <strong><p class="datejnd">Name: {{user.first_name}}</p></strong>
        </div>
        <div id="userdata">
            <p>Bio: {{user.profileforusers.user_bio}}</p>
            <div class="form-group">
                <form method='post' enctype="multipart/form-data">
                    {% csrf_token %}
                    {{p_form.as_p}}
                    <button class="btn btn-outline-success" type="submit">Update Pic</button>
                </form>
                <form method='post'>
                    {% csrf_token %}
                    {{u_form.as_p}}
                    <button class="btn btn-outline-success" type="submit">Update Name</button>
                </form>
                <form method='post'>
                    {% csrf_token %}
                    {{bio_form.as_p}}
                    <button class="btn btn-outline-success" type="submit">Update Bio</button>
                </form>
            </div>
            {% for message in messages %}
            <h5 id="messageid">{{message}}</h5>
            {% endfor %}
        </div>
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>     
    </body>
</html>
```
Your answer will be greatly appreciated
Thanks For Your Time
<hr>