简体   繁体   English

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

[英]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:当我在相应页面上的 go 时直接出现以下错误:

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您可以查看 ModelForm 的ModelForm参考 - https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#django.ZAC68B62ABFD6A9FE26E8AC4236C8C模型。

class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass):
    pass

It doesn't define an __init__ method, so we look in it's parent __init__ , namely BaseModelForm.__init__ .它没有定义__init__方法,所以我们查看它的父__init__ ,即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.如您所见,它不接受instance作为位置参数,而是接受关键字参数。 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() init 中的第一个参数是data=None ,因此您的表单实例将您传递的request.user视为数据字典,从而调用不存在的.get()

Fixing your code to将您的代码修复为

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

Should solve the case.应该解决这个案子。

Credit: This SO question信用: 这个SO问题

You need to instantiate your ModelForm ChangeUserDescription with an actual instance of Profile , eg ChangeUserDescription(instance=profile) .您需要使用Profile的实际实例来实例化您的ModelForm ChangeUserDescription ,例如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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django-channels: AttributeError: 'str' object 没有属性 'profile' - Django-channels: AttributeError: 'str' object has no attribute 'profile' AttributeError: &#39;User_Profile&#39; 对象没有属性 &#39;__name__&#39; - AttributeError: 'User_Profile' object has no attribute '__name__' /profiles/user-profile/2/ 'int' 处的 AttributeError object 没有属性 '_meta' - AttributeError at /profiles/user-profile/2/ 'int' object has no attribute '_meta' /profile/ &#39;function&#39; 对象的 AttributeError 没有属性 &#39;object - AttributeError at /profile/ 'function' object has no attribute 'object Django: AttributeError: 'User' object 没有属性 'get' - Django: AttributeError: 'User' object has no attribute 'get' Django 1.9 错误 - &#39;User&#39; 对象没有属性 &#39;profile&#39; - Django 1.9 error - 'User' object has no attribute 'profile' / accounts / login /上的AttributeError&#39;用户&#39;对象没有属性&#39;user&#39; - AttributeError at /accounts/login/ 'User' object has no attribute 'user' / accounts / regist_save /&#39;User&#39;对象上的AttributeError没有属性&#39;user&#39; - AttributeError at /accounts/regist_save/ 'User' object has no attribute 'user' Django更新用户个人资料 - Django update user profile AttributeError: 'Person' object 没有属性 'update' Django - AttributeError: 'Person' object has no attribute 'update' Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM