RelatedObjectDoesNotExist at / User has no customer.
I am getting this error after I register a user and attempt to sign in. I am only able to sign in with a superuser I created but not with a new user I register.
views.py
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
form.save()
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
#THIS IS THE ERROR IT LEADS ME TO
def store(request):
data = cartData(request)
cartItems = data['cartItems']
products = Product.objects.all() # getting all the products
context = {
'products': products,
'cartItems': cartItems
} # allows us to use in our template
return render(request, 'store/store.html', context)
models.py
class Customer(models.Model):
user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name=models.CharField(max_length=50, null=True)
email=models.CharField(max_length=200)
def __str__(self):
return self.name #this will show on our admin panel
Change your model class user field like this:
user=models.OneToOneField(
User,
null=True,
blank=True,
on_delete=models.CASCADE,
related_name="customer"
)
and your register view:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
Customer.objects.create(
user = user,
name = user.username,
email = user.email
)
username= form.cleaned_data.get('username')
messages.success(request, f'Your Account has been created! You can now log in')
return redirect('login')
else:
form = UserCreationForm() #creates an empty form
return render(request, 'store/register.html', {'form': form})
When you create user, you should create a customer for this user, for example:
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
#saving the registered user
user = form.save()
username= form.cleaned_data.get('username')
#create customer
Customer.objects.create(user=user, name=username, email=user.email)
...
Related
i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user) and before i save the form i assign the value like this new_form.creator = freelancer .
views.py
#login_required
def create_gig(request):
user = request.user
freelancer = get_object_or_404(Freelancers, user=user)
if request.method == "POST":
form = CreateGig(request.POST, request.FILES)
if form.is_valid():
new_form = form.save(commit=False)
new_form.user = request.user
new_form.creator = freelancer
new_form.slug = slugify(new_form.title)
new_form.save()
messages.success(request, f'Gig Created Successfully, Would be Live Soon')
return redirect('freelance:listings')
else:
form = CreateGig()
context = {
'form': form
}
return render(request, 'freelance/create.html', context)
models.py
class Gigs(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user')
creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator')
title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ")
In my code, it is getting a logged-in user instance and then creating the gig by assigning the freelancer to the created form.
#login_required
def create_gig(request):
freelancer = Freelancers.objects.get(user = request.user )
if request.method == "POST":
form = CreateGig(request.POST, request.FILES)
if form.is_valid():
new_form = form.save(commit=False)
new_form.creator = freelancer
new_form.slug = slugify(new_form.title)
new_form.save()
messages.success(request, f'Gig Created Successfully, Would be Live Soon')
return redirect('freelance:listings')
else:
form = CreateGig()
context = {
'form': form
}
return render(request, 'freelance/create.html', context)
You also don't need this line in your view:
new_form.user = request.user
I am making a library system with signup pages (admin and user), so when I make an admin user I want to make it in staff, so how can I use (is_staff)?
this is my registration function...
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
context = {'form':form}
return render(request, 'pages/register.html', context)
You can alter the .instance wrapped in the form before saving it to the database:
def register(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.instance.is_staff = True
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account created successfully')
return redirect(loginpage)
return render(request, 'pages/register.html', {'form':form})
I would like the user name field for my Django registration to populate with the following function -
def generateUsername():
username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr()
return username
I am currently using the UserRegisterForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also.
views.py -
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
forms.py -
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
firstname = forms.CharField(max_length=20)
middlename = forms.CharField(max_length=20)
lastname = forms.CharField(max_length=20)
class Meta:
model = User
fields = ['email', 'firstname', 'middlename', 'lastname']
You can set this to the user object wrapped in the form:
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
username = f"{data['firstname'][0]}{data['middlename'][0]}{data['lastname'][0]}{randomStringDigits(6)}"
form.instance.username = username
form.save()
messages.success(request, f'Account created for {username}')
return redirect('login')
I am working on a registration page. I extended django's User model to add additional fields. I have two forms connected with OnetoOnefield. I am getting this error.
DoesNotExist at /register/
Influencer matching query does not exist.
I think what I am doing wrong is creating User and Influencer model at the same time.
My models.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Influencer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True, null=True)
ig_url = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return f"{self.user.first_name} {self.user.last_name}"
#receiver(post_save, sender=User)
def create_influencer(sender, instance, created, **kwargs):
if created:
Influencer.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_influencer(sender, instance, **kwargs):
instance.influencer.save()
My forms.py file:
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class InfluencerProfileForm(forms.ModelForm):
class Meta:
model = Influencer
fields = ('bio', 'ig_url')
My views.py file:
def register(request):
user_form = UserForm()
profile_form = InfluencerProfileForm()
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile = Influencer.objects.get(user=request.user)
profile_form = InfluencerProfileForm(request.POST, instance=profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, 'Your profile was successfully updated!')
return redirect('settings:profile')
else:
messages.error(request, 'Please correct the error below.')
return render(request, 'accounts/register.html', {
'user_form': user_form,
'profile_form': profile_form
})
I think the problem is in two places. One, you have a signal which creates Influencer instance where you al. Second, you are assuming you will have a Influencer instance before creating one. You can remove the signals and try with the following code:
def register(request):
user_form = UserForm(request.POST or None)
profile_form = InfluencerProfileForm(request.POST or None)
if request.method == 'POST':
if request.user.is_authenticated:
user_form = UserForm(request.POST, instance=request.user)
try:
profile_form = InfluencerProfileForm(request.POST, instance=request.user.influencer) # due to OneToOne relation, it will work
except:
pass
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
messages.success(request, 'Your profile was successfully updated!')
return redirect('settings:profile')
else:
messages.error(request, 'Please correct the error below.')
return render(request, 'accounts/register.html', {
'user_form': user_form,
'profile_form': profile_form
})
I have made a form to give an option for user to withdraw money. That data is saving in admin page but the problem is I have owner variable also, which I want that as the amount data is going to be saved in admin page the owner username should also be saved in admin, which shows who is desiring this amount?
models.py
from django.contrib.auth.models import User
class WithdrawPayment(models.Model):
payment = models.CharField(max_length=100)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
verbose_name_plural = 'Withdraw Payment'
views.py
#login_required
def withdraw(request):
if request.method == 'POST':
form = WithdrawBalance(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, f'Your request has been submitted.')
return redirect('index')
else:
form = WithdrawBalance()
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)
forms.py
class WithdrawBalance(forms.ModelForm):
class Meta:
model = WithdrawPayment
fields = ['payment']
Something like this:
#login_required
def withdraw(request):
form_class = WithdrawBalanceForm
if request.method == 'POST':
form = form_class(request.POST)
obj = form.save(commit=False)
obj.owner = request.user
obj.save()
messages.success(request, f'Your request has been submitted.')
return redirect('index')
else:
form = form_class()
context = {'form': form}
return render(request, 'nextone/withdraw.html', context)
class WithdrawBalanceForm(forms.ModelForm):
class Meta:
model = WithdrawPayment
fields = ['payment']