I Need Help in this problem
Krishan111

Krishan111 @krishan111

About: M a Good Boy ; )

Joined:
Sep 30, 2020

I Need Help in this problem

Publish Date: Jan 22 '21
16 5

Hello Guys! I am making a profile update page in my django website.
The following is the problem that I am facing:

  • Whenever I clicks on "Update Pic" button the name gets blank even in admin

  • This is my views.py
    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)
    
    Enter fullscreen mode Exit fullscreen mode

    This is My signals.py

    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()
    
    Enter fullscreen mode Exit fullscreen mode

    This is My model

    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)
    
    Enter fullscreen mode Exit fullscreen mode

    This is my forms.py

    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']
    
    Enter fullscreen mode Exit fullscreen mode

    And this is usersettings.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>
    
    Enter fullscreen mode Exit fullscreen mode

    Your answer will be greatly appreciated

    Thanks For Your Time


    Comments 5 total

    • goyal-aman
      goyal-amanJan 22, 2021

      Is it possible for the user to update both Bio and Profile at same time? I cannot be sure with this limited information but I believe problem is in userprofile function

      • Krishan111
        Krishan111Jan 22, 2021

        yes user can update bio & name separately

        • goyal-aman
          goyal-amanJan 22, 2021

          Then I recommend changing code under request.Post statement as follows

          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)
              success_message = ""
              if u_form.is_valid():
                  u_form.save()
                  success_message += "Profile Is Updated Successfully! "
              if p_form.is_valid():
                  p_form.save()
                  success_message += "Profile Picture Is Updated Successfully!"
              if bio_form.is_valid():
                  bio_form.save()
                  success_message += "Bio Updated Successfully!"
              messages.success(request, success_message)
              return redirect("profilesettings")
          
          Enter fullscreen mode Exit fullscreen mode

          lets say user updates both profile picture and bio.. then previous implementation only updates picture and not bio. That seems to be the cause of the issue you.

          update: made an edit.

    Add comment