M
M
ma3xak2018-05-24 17:07:38
Django
ma3xak, 2018-05-24 17:07:38

I can't figure out where is the error?

Please help me figure out where the error is. When I try to register a user, I get an error.
Traceback

Traceback (most recent call last):
  File "C:\Phyton\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "C:\Phyton\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Phyton\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\work\life\accounts\views.py", line 82, in register
    user_form = UserForm(data = request.POST, instance=request.user)
  File "E:\work\life\profiles\forms.py", line 27, in __init__
    super(UserForm, self).__init__(*args, **kwargs)
  File "C:\Phyton\lib\site-packages\django\forms\models.py", line 291, in __init__
    object_data = model_to_dict(instance, opts.fields, opts.exclude)
  File "C:\Phyton\lib\site-packages\django\forms\models.py", line 82, in model_to_dict
    opts = instance._meta
  File "C:\Phyton\lib\site-packages\django\utils\functional.py", line 216, in inner
    return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute '_meta'
[24/May/2018 21:06:32] "GET /auth/signup HTTP/1.1" 500 81493

The view code
def register(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user )
        profile_form = ProfileForm(request.POST, instance=request.user.profile)
        if user_form.is_valid() and profile_form.is_valid():
            profile_form.save(commit = True)
            user_form.save()
            profile_form = User
            return redirect('/sms')
        else:
            messages.error(request, ('Ошибка регистраци'))
    else:
        user_form = UserForm(data = request.POST, instance=request.user)
        profile_form = ProfileForm()
    return render(request, 'accounts/register.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jock Tanner, 2018-05-28
@ma3xak

Starting from line 3:
But request.user is not an instance of the User model, it is an object of a special class that represents an anonymous user. Anonymous has no representation in the database.
First, let's create a user:

user_form = UserForm(request.POST)
if user_form.is_valid():
    user = user_form.save()

Now we have a user model in the database, and we can use it to create a profile, etc.

V
Vladimir, 2018-05-24
@vintello

I think he is trying to save the user, who is an animus, but this cannot be done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question