Changing image in django user change form

心不动则不痛 提交于 2020-06-17 13:05:10

问题


I am making a django webapp where users can upload profile image. I have also created an EDIT PROFILE page by using the default USERCHANGEFORM. But the problem is, that I cannot update the profile picture from that form. I can delete it but not upload new one? Help needed. This is my USER CREATION FORM:


class SignUpForm(UserCreationForm):

    photo               = forms.ImageField(required=False)
    bio                 = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your bio'}))
    designation         = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your designation'}))
    university          = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your university'}))

    company_name        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's name"}))
    grad_year           = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'What year did you graduate in?'}))
    phone               = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your phone number'}))
    address             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your present address'}))
    city                = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your city'}))
    company_category    = forms.CharField(widget=forms.TextInput(attrs={'placeholder':  "Enter your company's category"}))
    company_desc        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': "Enter your company's description"}))
    company_site        = forms.CharField()
    no_employees        = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter no. of employees in your company'}))
    technologies        = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What technologies are you interested in?'}))
    markets             = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'What markets are you interested in?'}))
    linkedin            = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter your Linked In profile'}))

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        del self.fields['password2']

        for fieldname in ['password1']:
            self.fields[fieldname].help_text = None

        self.fields['password1'].widget.attrs.update({'placeholder': 'Enter your password'})
        self.fields['first_name'].widget.attrs.update({'placeholder': 'Enter your first name'})
        self.fields['last_name'].widget.attrs.update({'placeholder': 'Enter your last name'})
        self.fields['company_site'].widget.attrs.update({'placeholder': "Enter company's website"})
        for field in ['email',
                   'password1',
                   'first_name',
                   'last_name',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'photo',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                   'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin']:

                   self.fields[field].widget.attrs['class'] = "col-lg-4 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
                   self.fields[field].widget.attrs['style'] = "padding:20px;"

        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-1 "


    class Meta:
        model = User
        widgets = {
        "email": forms.fields.TextInput(attrs={'placeholder':'Enter your email'}),
        }
        fields = ('email',
                   'password1',
                  'first_name',
                  'last_name',
                   'photo',
                   'bio',
                   'designation',
                   'university',
                   'company_name',
                   'grad_year',
                   'phone',
                   'address',
                   'city',
                   'company_category',
                   'company_desc',
                    'company_site',
                   'no_employees',
                   'technologies',
                   'markets',
                   'linkedin')


This is my USER CHANGE FORM

class EditProfileForm(UserChangeForm):

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        for field in [
                    'first_name',
                    'last_name',
                    'bio',
                    'designation',
                    'university',
                    'company_name',
                    'grad_year',
                    'phone',
                    'address',
                    'city',
                    'company_category',
                    'company_desc',
                    'company_site',
                    'no_employees',
                    'technologies',
                    'markets',
                    'linkedin']:
            self.fields[field].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6 form-control"
            self.fields[field].widget.attrs['style'] = "padding:20px;"


        self.fields['photo'].widget.attrs['class'] = "col-lg-8 col-md-12 col-sm-12 col-xs-12 offset-lg-2 ml-6"
        self.fields['password'].widget.attrs['class'] = "hidden"


    class Meta:
        model = User
        fields = ('first_name',
        'last_name',
        "photo",
        "bio",
        "designation",
        "university",
        "company_name",
        "grad_year",
        "phone",
        "address",
        "city",
        "company_category",
        "company_desc",
         "company_site",
        "no_employees",
        "technologies",
        "markets",
        "linkedin"
        )```

回答1:


Basically you are getting the instance but you are not only able to update only the picture.




回答2:


Try this!

In your EditProfileForm

replace

super(UserChangeForm, self).__init__(*args, **kwargs)

to

super(EditProfileForm, self).__init__(*args, **kwargs)

same in your SignUpForm replace

super(UserCreationForm, self).__init__(*args, **kwargs)

to

super(SignUpForm, self).__init__(*args, **kwargs)

And you forgot to add photo inside EditProfileForm for field in [...]




回答3:


{% load static %}
{% block content %}

<!-- Inner Page Banner Area Start Here -->
        <div class="inner-page-banner-area" style="background-image: linear-gradient(to bottom,#002147, #fdc800);">
            <div class="container">
                <div class="pagination-area">
                    <h1>Edit Profile</h1>
                </div>
            </div>
        </div>
        <!-- Inner Page Banner Area End Here -->
        <!-- Account Page Start Here -->

<div class="section-space accent-bg">
    <div class="container">
        <div class="row">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">

                    <div class="profile-details tab-content">
                        <div class="tab-pane fade active in" id="Personal">
                            <h3 class="title-section title-bar-high mb-40">Edit Profile</h3>
                            <form id='login-form' style='text-align:left;' method="post" enctype="multipart/form-data">
                              <div class="form-group mt-1">
                              {% csrf_token %}
                               {% for field in form %}
                                <p>

                                  <div class="mb-n5">{% if field.field.required %}{{ field.label_tag}}<span style='color:red;'>*</span>
                                  {% else %}{{ field.label_tag}}
                                  {% endif %}</div>


                                  {% if field.name == 'password' %}

                                  <a href="{% url 'password_change'%}" class="view-all-primary-btn">Change Password</a>

                                  {% else %}
                                  {{ field }}
                                  {% endif %}
                                  <br>
                                  {% for error in field.errors %}
                                    <p style="color: red">{{ error }}</p>
                                  {% endfor %}
                                </p>
                                </br>
                              {% endfor %}


                            </div>
                              <button class="view-all-primary-btn" type="submit">Save</button>
                            </form>
                        </div>
                    </div>
            </div>
        </div>
    </div>
</div>
{% include 'partials/_footer.html' %}
{% endblock %}


来源:https://stackoverflow.com/questions/62134522/changing-image-in-django-user-change-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!