matching query does not exist - Django - python

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
})

Related

Saving username to model in Django

I am creating a donation app that allows donors to create listings. This data is stored in a Django Model and is going to be displayed on a page. I want to save the user's username to the Django model and display it on the page. My code is down below
Models.py
class Donation(models.Model):
title = models.CharField(max_length=30)
phonenumber = models.CharField(max_length=12)
category = models.CharField(max_length=20)
image = models.CharField(max_length=1000000)
deliveryorpickup = models.CharField(max_length=8)
description = models.TextField()
Views.py
from django.contrib.auth.models import User
from django.http.request import RAISE_ERROR
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import forms, inlineformset_factory
from django.contrib.auth.forms import UserCreationForm, UsernameField
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from home.models import Donation
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def dashboard(request,*args, **kwargs):
return render(request, "dashboard.html", {} )
def register(request, ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
image = request.POST['imagelink']
deliveryorpickup = request.POST['deliveryorpickup']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, image = image, deliveryorpickup = deliveryorpickup, description = description )
ins.save()
return render(request,'donate.html')
Forms.py (This is where the user is created)
class CreateUserForm(UserCreationForm):
username = forms.CharField(required=True, max_length=30, )
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True, max_length=50)
last_name = forms.CharField(required=True, max_length=50)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]
#function to display errors
def clean(self):
cleaned_data=super().clean()
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if User.objects.filter(username=cleaned_data["username"]).exists():
raise ValidationError("This username is taken, please try another one")
elif password1 != password2:
raise forms.ValidationError("2 password fields do not match")
elif len(password1) < 8 or len(password2) < 8:
raise forms.ValidationError("Passwords must be at least 8 characters long")
To associate the user with the Donation model, you should first add a ForeignKey field to the model class:
from django.conf import settings
class Donation(models.Model):
... # your other donation fields
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
Once you've made this change, and run the migrations, in your views.py you'll pass the currently signed in user to the Donation model creation:
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
ins = Donation(
title=request.POST["title"],
... # all of the other fields
user=request.user, # 👈 This adds the user
)
ins.save()
return render(request,'donate.html')
Notes
Using settings.AUTH_USER_MODEL allows your class to use a custom user model, or django's default user model, based on your project's settings.
To understand what on_delete=models.CASCADE does, you should read django's documentation about it.
Also, instead of manually passing all of the request.POST[...] values to the Donation model, I recommend that you use a ModelForm. It will handle errors and validation for you, as well as generate the HTML displayed in the template. Using a model form here would make your view code change to this:
from django.forms import ModelForm
class DonationForm(ModelForm):
class Meta:
model = Donation
exclude = ["user"]
#login_required(login_url="/login/")
def donate(request):
if request.method == "POST":
form = DonationForm(request.POST)
if form.is_valid():
donation = form.save(commit=False)
donation.user = request.user
donation.save()
# Use a redirect to prevent duplicate submissions
# https://docs.djangoproject.com/en/3.2/topics/http/shortcuts/#redirect
return redirect(request, ...)
else:
form = DonationForm()
return render(request, "donate.html", {"form": form})

RelatedObjectDoesNotExist at / User has no customer

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)
...

How to add username in admin page who logged in when withdrawing an amount?

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']

Trying to extend User to UserProfile in form Django

Hi I am having serious trouble this getting this form to work. When I try to run my program it gets to print("4") then throws the error
UNIQUE constraint failed: slug_trade_app_userprofile.user_id
To be clear the new user i am creating doesnt exist prior to clicking submit on the form
It seems like profile is trying to create a new user again but since (i think) user created a new user, that user already exists its throwing the error. HELP!!
Views.py
def signup(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
print("1")
user = user_form.save(commit=False)
user.save()
print("2")
profile = profile_form.save(commit=False)
print("3")
profile.user = user
print("4")
profile.save()
print("5")
user = authenticate(username=user_form.cleaned_data['email'],
password=user_form.cleaned_data['password1'],
)
login(request, user)
return redirect('/home')
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'slug_trade_app/signup.html', {'user_form': user_form, 'profile_form': profile_form})
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True )
bio = models.TextField(max_length=500, blank=True)
on_off_campus = models.CharField(max_length=3,
default="on",
choices=CAMPUS_STATUS)
forms.py
class UserForm(UserCreationForm):
email = forms.EmailField(required=False)
class Meta:
model = User
fields = (
'first_name',
'last_name',
'email',
'password1',
'password2',
)
def save(self, commit=True):
user = super(UserForm, self).save(commit=False)
user.username = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
class UserProfileForm(forms.ModelForm):
class Meta():
model = UserProfile
fields = ('profile_picture', 'bio', 'on_off_campus')
Try profile_form = UserProfileForm(instance=request.user) Also I believe profile.user = user should be profile.user = request.user otherwise user refers to the user form not the user instance

RelatedObjectDoesNotExist User has no Profile

I am new to Django.I am creating a user registration by using the built in Django User model and Usercreation form. I am trying to extend the built-in User Model in Django so I can include an extra field company name.I am encountering this recurring error below.I would really appreciate any help in trying to solve this problem.
RelatedObjectDoesNotExist User has no Profile
(1)Here is my Model.py of the Profile model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Company_name = models.CharField(max_length=30)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
(2.)Here is my views.py.I am trying to update the profile model each time a new user instance is created.It seems like I have to link the create_user_profile and save_user_profile functions to my view but I am not too sure how to do this.
def Register(request):
if request.method == 'POST':
User_form = RegisterRecruiterForm(request.POST, instance=request.user)
Profile_form = ProfileForm(request.POST, instance=request.user.profile)
if User_form.is_valid() and Profile_form. is_valid():
User_form.save()
Profile_form.save()
return HttpResponse('you are now registered')
else:
User_form = RegisterRecruiterForm(instance=request.user)
Profile_form = ProfileForm(instance=request.user.profile)
return render(request, 'Register.html', {
'User_form': User_form,
'Profile_form': Profile_form
})
3.Here is my forms.py.
class RegisterRecruiterForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super(RegisterRecruiterForm, self).save(commit=False)
user.email(self.cleaned_data["email"])
user.username(self.cleaned_data["username "])
user.password(self.cleaned_data["password1 "])
user.password(self.cleaned_data["password2 "])
if user.password1 != user.password2:
raise forms.validationError("Password do not match")
return Profile.Company_name
if commit:
user.save()
return user
class ProfileForm(forms.ModelForm):
Company_name = forms.CharField(max_length=10,help_text='Required')
class Meta:
model = Profile
fields = ('Company_name',)
def save(self, commit=True):
Profile = super(ProfileForm, self).save(commit=False)
Profile.Company_name(self.cleaned_data["Company_name"])
if commit:
Profile.save()
return Profile
As I can see, your problem is that you are trying to get "request.user.profile" in this line:
Profile_form = ProfileForm(request.POST, instance=request.user.profile)
In your models the "User" doesn't has a "Profile" but a "Profile" has a "User", so the correct way to get this profile is:
profile = Profile.objects.get(user = request.user)
Profile_form = ProfileForm(request.POST, instance = profile)
This fix your problem with the "RelatedObjectDoesNotExist" error. If you have another error, you can open a new question.
Finally, you "Register" function will be:
def Register(request):
if request.method == 'POST':
User_form = RegisterRecruiterForm(request.POST, instance=request.user)
profile = Profile.objects.get(user = request.user)
Profile_form = ProfileForm(request.POST, instance = profile)
if User_form.is_valid() and Profile_form. is_valid():
User_form.save()
Profile_form.save()
return HttpResponse('you are now registered')
else:
User_form = RegisterRecruiterForm(instance=request.user)
profile = Profile.objects.get(user = request.user)
Profile_form = ProfileForm(request.POST, instance = profile)
return render(request, 'Register.html', {
'User_form': User_form,
'Profile_form': Profile_form
})

Categories

Resources