简体   繁体   中英

Django AttributeError at /accounts/profile/ 'User' object has no attribute 'get' while update profile

Hello i get the following error when i tried to add form to update description of the user profile

My models:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    birth_date = models.DateField(null=True, blank=True)
    profile_img = models.ForeignKey(Image,on_delete=models.CASCADE,related_name='images',null=True)
    description = models.TextField()

My form:

class ChangeUserDescription(ModelForm):
    class Meta:
        model = Profile
        fields = ['description','profile_img']
        widgets = {
            'description': forms.Textarea(),
            'profile_img':forms.ImageField()
        }
        labels = {
            'description':'Description',
            'profile_img':'Image'
        }

My view:

@login_required
def profile(request): 
    if request.method == 'POST':
        form = ChangeUserDescription(request.user, request.POST)
        if form.is_valid():
            form.save()
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = ChangeUserDescription(request.user)
    return render(request, 'registration/profile.html', {'form': form})

And my template:

<div class="mainPage">
    <h1>Profile</h1>
    
    <h2>Bonjour {{user.get_username}}</h2>
    
    <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">Save changes</button>
    </form>
      
    
    
    <a href="{% url 'adoptYourOcApp:password_change'%}" >Change password</a>


    {% include "annonces/my_list.html" %}
</div>

Direclty when i go on the corresponding page i get the following error:

AttributeError at /accounts/profile/
'User' object has no attribute 'get'
Request Method: GET
Request URL:    http://localhost:8000/accounts/profile/
Django Version: 2.2.17
Exception Type: AttributeError
Exception Value:    
'User' object has no attribute 'get'

The issue probably lies in the way you initialize your form. You can look at the API reference for ModelForm - https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#django.forms.ModelForm

class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
    pass

It doesn't define an __init__ method, so we look in it's parent __init__ , namely BaseModelForm.__init__ .

class BaseModelForm(BaseForm):
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False, instance=None, use_required_attribute=None,
                 renderer=None):

As you can see there, it doesn't accept the instance as a positional argument, but rather a keyword one. The first argument in init is data=None , so your form instance is treating the request.user you passed as a data dictionary, thus calling the nonexistent .get()

Fixing your code to

form = ChangeUserDescription(request.POST, instance=request.user)

Should solve the case.

Credit: This SO question

You need to instantiate your ModelForm ChangeUserDescription with an actual instance of Profile , eg ChangeUserDescription(instance=profile) .

some_profile = Profile.objects.get(user=request.user)
form = ChangeUserDescription(instance=some_profile)

and similar when updating:

form = ChangeUserDescription(request.POST, instance=some_profile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM