User Customer Crash

Hello, I am new to Django and in fact this is my first post.I am experiencing the following error. Create a form to register new users. The problem appears when I want to log in with the new user. When I log in, I would have to redirect to my home page, but doing so gives me an error. If I enter the Django administration site, the user is created and the customer also creates me with the same name (since I want in this case that both user and customer have the same name). But the entire site becomes inaccessible. If I only create, the user does the same and if I create only customer too. In the only case that the site works is when I link from the Django administration site, the name of the user with the name of the customer. I do not know why this happens, nor how to solve it so that you do not have to enter the administration site and do the latter. since in practice it would be impossible. I attach the code and relevant images and thank you very much to anyone who can help me with this since I can not solve it.

def register_page(request):

    form = CreateUserForm()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():

            user = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            customer, created = Customer.objects.get_or_create(email=email)
            customer.name = user
            customer.save()
            form.save()

            messages.success(request, 'La cuenta fue creada por ' + user)

            return redirect('login')

    context = {'form': form}
    return render(request, 'store/register.html', context)
class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=254, null=True)

    def __str__(self):
        return self.name

Customers and users
Screenshot_20200715_022754

Users was created created by the registration process that we can see in views, except the admin of course.
Screenshot_20200715_022639

List of customers

Screenshot_20200715_032216

Screenshot_20200715_022616

Customer matt1, created by the registration process that we can see in views. Crash the page.

Screenshot_20200715_022704

Customer rosa, created by the registration process that we can see in views, but the difference is that among the Django administration site, I went to Clients chose rosa and in the checkbox select the rosa user. This is the only thing that saves my site from error. I just can’t solve it!

First, when posting code here, please don’t post screenshots. Copy your code between two lines consisting only of three backtick ` characters. (You’ll have a line of ```, your code, and then another line of ```. Be sure you use the backtick ` and not the apostrophe '.)
example:

# The line above is just ```
def function(self):
    return self
# The next line is just ```

This maintains the formatting and appearance of your code.

Having said that, can you post your CreateUserForm? Also, including the complete traceback would be helpful. (It might be easier to copy it from the terminal session where you’re running runserver than from the browser window, but either should have all the useful information.)

Ken

Hi Ken, that’s my CreateUserForm function.

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

This is the tracerute of my terminal

[15/Jul/2020 21:21:19] “GET /register/ HTTP/1.1” 200 3195
[15/Jul/2020 21:21:43] “POST /register/ HTTP/1.1” 302 0
[15/Jul/2020 21:21:43] “GET /login/ HTTP/1.1” 200 2133
[15/Jul/2020 21:21:52] “POST /login/ HTTP/1.1” 302 0
Internal Server Error: /
Traceback (most recent call last):
File “/home/matt/.local/lib/python3.8/site-packages/django/core/handlers/exception.py”, line 34, in inner
response = get_response(request)
File “/home/matt/.local/lib/python3.8/site-packages/django/core/handlers/base.py”, line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File “/home/matt/.local/lib/python3.8/site-packages/django/core/handlers/base.py”, line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File “/home/matt/PycharmProjects/ecommerce/ecommerce/store/views.py”, line 57, in store
data = cartdata(request)
File “/home/matt/PycharmProjects/ecommerce/ecommerce/store/utils.py”, line 46, in cartdata
customer = request.user.customer
File “/home/matt/.local/lib/python3.8/site-packages/django/utils/functional.py”, line 225, in inner
return func(self._wrapped, *args)
File “/home/matt/.local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py”, line 420, in get
raise self.RelatedObjectDoesNotExist(
django.contrib.auth.models.User.customer.RelatedObjectDoesNotExist: User has no customer.
[15/Jul/2020 21:21:52] “GET / HTTP/1.1” 500 87376

Matt

Ok, looking at these lines - you’re creating a Customer object, but you’re never relating it to the user. In other words, you’re not assigning the customer.user attribute to refer to the User object being created.

If you’re creating a new user from a model form, you need to save the form first, then get the instance from the form and assign it to the Customer.user attribute:

new_user = form.save()
customer.user = new_user
customer.name = user
customer.save()

(By the way, I think you’re going to find it very confusing if you don’t make your naming conventions more consistent.)

Also, you will have a problem here if a second person ever registers with the same email address as a prior registered user. (You’ll change the User reference to the new user, but that will leave the original User object without the corresponding Customer object, creating the same problem you’re having now.)

Ken

It works, will take your comments into account. Verify that indeed if I enter the same email with another user it changes the references and the same error occurs, as you commented. So I am going to put a condition so that the same email cannot be entered twice, think that should suffice.

Thanks, Matt