how to map user model to customer model in django - python

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.

Related

Populate OneToOneField after submitting form Django

I wrote the following code which creates a new user and tries to create a profile for that user:
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
#login_required(login_url="/login")
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = form
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
user_model = get_user_model()
users = user_model.objects.all()
paginator = Paginator(users, 15)
page = request.GET.get('page')
users = paginator.get_page(page)
return render(request, 'users/index.html', {'users': users, 'form': form})
class Profile(models.Model):
has_premium_until = models.DateTimeField(null=True, blank=True)
has_premium = models.BooleanField(default=False)
has_telegram_premium_until = models.DateTimeField(null=True, blank=True)
has_telegram_premium = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class CustomUser(AbstractUser):
email = models.EmailField(max_length=255, unique=True)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True)
When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null).
Anyone who can help me out?
Your user is actually just a reference to the ProfileForm you constructed. You can obtain the user that has logged in with request.user. So you can update the user with:
#login_required(login_url='/login')
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = request.user
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
# …

How can I save values with user.id to Database - Django

I want to save the values that users enter into the repository. But if the user has already entered a value, I want it to update.
It's saving the data right now. But it cannot update.
I' am use Django
forms.py
class Meta():
model = UserProfileInfo
fields = ('apikey', 'apivalue', 'apisupplier')
views.py
def user_set_api(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
current_user = request.user
user_form = UserProfileInfoForm(data=request.POST)
user_id = current_user.id
print('UserId:', user_id)
if user_form.is_valid() and user_id:
user_form.save(request.user)
print('User: ', user, 'Userformid:', UserProfileInfo(['user_id']))
else:
print(user_form)
else:
keysvalue = UserProfileInfoForm()
return render(request, 'form.html',
{'apisupplier': UserProfileInfo})
models.py
user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
apisupplier = models.CharField(max_length=40, blank=True, default="null")
apikey = models.CharField(max_length=40, blank=True, default="null")
apivalue = models.CharField(max_length=40, blank=True, default="null")
def __str__(self):
template = '{0.user} {0.apikey} {0.apivalue} {0.apisupplier}'
return template.format(self)```
I'm not sure why you are passing the user id to form.save(). You need to pass the user object to the form instantiation:
if request.method == 'POST':
...
user_form = UserProfileInfoForm(data=request.POST, instance=request.user)
if user_form.is_valid()
user_form.save()
...
else:
user_form = UserProfileInfoForm(instance=request.user)
return render(request, 'form.html',
{'apisupplier': UserProfileInfo, "user_form": user_form})

Password mismatch in registration form that inherits from UserCreationForm

I have a form that inherits from the UserCreationForm. The file looks like this:
from django import forms
from django.contrib.auth import password_validation
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User, Group
from main.models.users import MyUser
class MyUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
group = forms.CharField(max_length=50, required=True)
class Meta:
model = MyUser
fields = ("group", "email", "username", "email", "password1", "password2")
def save(self, commit=True):
user = super(MyUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
For some reason, when trying to fill up the form, I get a password mismatch error like so:
ERROR - {'password_mismatch': "The two password fields didn't match."}
I tried overriding the clean_password1 and clean_password2 with no help. Code:
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
# Method inherited from BaseForm
self.add_error('password1', error)
return password1
Any ideas why this is happening? Why is it thinking that both of my passwords are not identical? I'm sure they are, as I tried a million times and even copy and pasted.
view:
def register(request):
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
print(f"Valid form. Choosen group: {form.cleaned_data.get('group')}")
user = form.save()
group = Group.objects.get(name=form.cleaned_data.get('group'))
user.groups.add(group)
login(request, user)
messages.success(request, f"Thanks, {form.cleaned_data.get('username')}, "
f"for signing up as a {form.cleaned_data.get('group')} ")
return redirect('main:homepage')
else:
logger.error(form.error_messages)
for msg in form.error_messages:
messages.error(request, f'{msg}: {form.error_messages[msg]}')
return render(request,
template_name='main/register.html',
context={'form': form})
else:
form = MyUserCreationForm()
return render(request,
template_name='main/register.html',
context={'form': form})
i am not sure about code but you can try this
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
#inhereting Usercreation form
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
#validating the password match while creating the user.
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('home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})

ValueError at /accounts/signup/

this is my signup view ->
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
print('hello')
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)
account = Account(user=user)
account.save()
login(request, user)
return redirect('/gallery/index')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})
this is my accounts model ->
class Account(models.Model):
user = models.OneToOneField(User,
related_name="profile",on_delete=models.CASCADE)
following=models.ManyToManyField(User,related_name="followers",null=True,blank=True)
this is the error I am getting -
The view accounts.views.signup didn't return an HttpResponse object.
It returned None instead.
I am getting this error whenever I submit the form. I am using the django admin signup form by default
Try
def signup(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
print('hello')
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)
account = Account(user=user)
account.save()
login(request, user)
return redirect('/gallery/index')
else:
form = UserCreationForm()
return render(request, 'accounts/signup.html', {'form': form})

Edit groups in user edit form in Django

I do not use admin apps in Django, and I want to edit the user with form, but when I edit the groups to the users, Django doesn't save my choice and user has no groups.
views.py:
def useredit(request, pk):
user = get_object_or_404(User, pk=pk)
if request.method == "POST":
form = EditUserForm(request.POST, instance=user)
if form.is_valid():
user.save()
messages.success(request, 'Utilisateur édité avec succés !')
return HttpResponseRedirect('/user')
else:
form = EditUserForm(instance=user)
return render(request, 'compta/users/edit.html', {'form': form})
forms.py:
class EditUserForm(UserChangeForm):
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit)
self._save_m2m()
return user
You need to save form instead of user instance
replace
if form.is_valid():
user.save()
#^^^^
with
if form.is_valid():
form.save()
#^^^^

Categories