简体   繁体   中英

how to map user model to customer model in django

I was working on an e-commerce website using Django for which I created a customer model in models.py

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200)

    def __str__(self):
        return self.name

and when I register a new user on my site using this view:

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('store')

    else:
        form = SignUpForm()
    return render(request, 'store/signup.html', {'form': form})

The user gets created but I get the error RelatedObjectDoesNotExist: User has no Customer I know it's because the User model is created but not Customer, I'm new to Django and want to know a way to map these two models at the time of registration.

In views.py when you register the user you can also a create a customer modal ıf its what you want. If so try this:

def signup(request):
if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
        form.save()
        username = form.cleaned_data.get('username')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=raw_password)
        Customer.objects.create(user=user,name=username,email=email) // get the email from the form
        login(request, user)
        return redirect('store')

else:
    form = SignUpForm()
return render(request, 'store/signup.html', {'form': form})

                    

Also can add your customer modal ın admin panel and manually add your customer info just for demonstration.

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