I have a mistake like this "AttributeError at /uz/account/update/ 'str' object has no attribute '_meta' "

Viewed 43

The above error occurs when you click the save button,but in the docs I think I am putting in the correct parameters. Where that bit of code is in my views.py:

class AllUserUpdate(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
    alluser = CustomUser.objects.get(username=self.request.user.username)
    form = CustomUserForm(instance=alluser)
    context = {'form':form}
    return render(request, 'account/AllUserAccount.html', context)

def post(self, request, *args, **kwargs):
    form = CustomUserForm(self.request.POST, self.request.FILES, instance=self.request.user.username)
    if form.is_valid():
        form.save()
        messages.info(self.request, "Your are change successfully created!")
        context = {'form': form}
        return redirect('all_user_update')

This is what my template looks like:

<form  method="post" enctype="multipart/form-data">
            {% csrf_token %}
                <h3>Full name: {{ request.user.full_name }}</h3>
                {{ form.as_p }}
                <input type="submit" class=" btn btn-primary" value="Save">
        </form>

forms.py:

class CustomUserForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput(
    attrs={'class': 'form-control mt-2', 'name': 'password1', 'placeholder': 'enter the password...'}))
password2 = forms.CharField(widget=forms.PasswordInput(
    attrs={'class': 'form-control mt-2', 'name': 'password2', 'placeholder': 'Repeat the password...'}))

class Meta:
    model = CustomUser
    fields = ('full_name', 'email', 'user_type', 'phone', 'password1', 'password2', 'username')
    widgets = {
        'full_name': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'full_name'}),
        'username': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'username'}),
        'email': forms.EmailInput(attrs={'class': 'form-control mt-2', 'name': 'email'}),
        'phone': forms.TextInput(attrs={'class': 'form-control mt-2', 'name': 'phone'}),
        'user_type': forms.Select(attrs={'class': 'form-control mt-2', 'name': 'user_type'}),
    }

enter image description here

I want users to change their personal pages

1 Answers

On this line:

    form = CustomUserForm(self.request.POST, self.request.FILES, instance=self.request.user.username)

you're passing a string (str) as the form's instance. That's not what the instance argument expects; it expects a Model instance (like you correctly pass it in the get method, a few lines before).

Pass the CustomUser you want to be updated as the instance, instead, for example:

    customuser = CustomUser.objects.get(username=request.user.username)
    form = CustomUserForm(request.POST, instance=customuser)
Related