How to get User Email from User model in a function Django - python-3.x

Hi Iam newbie to Django,
I written an function to send email from any user who need to know more info about the trip.
I didn't know to how to collect posted user email id from user database. need help.
def PostDetailView(request, pk):
context = {}
context["data"] = Post.objects.get(id=pk)
if request.method == "POST":
name = request.POST['uName']
# phone = request.POST["phone"]
email = request.POST['uEmail']
desc = request.POST['uDes']
userEmail = I need to assign email id of this trip posted user
subject = 'Iam Interested in your Trip'
message = f'Hi Iam {name}, Iam Interested you trip. Please share more details on {email} {desc}'
email_from = email
recipient_list = [userEmail, ]
send_mail( subject, message, email_from, recipient_list, desc )
messages.success(request, 'Message Sent Successfully.')
return render(request, 'ads/detail.html',context)
return render(request, 'ads/detail.html',context)
Need help to fix this.

I think the posted user is the current authenticated user ?
so you can get email:
userEmail = request.user.email

Related

Unable to verify email while using simple JWT in django

The register and login sections are functioning properly in my django application. When someone registers he receives a confirmation email, but on clicking the email confirmation link the account is not verified. I'm using try and except, it's the except that is being executed each time and try never executes.
models.py
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)
is_verified = models.BooleanField(default=False)
views.py
serializer_class = EmailVerificationSerializer
def get(self, request):
token = request.GET.get('token')
try:
key = jwt.decode(token, settings.SECRET_KEY)
user = User.objects.get(id=key['user_id'])
if not user.is_verified:
user.is_verified = True
user.save()
return Response({'email': 'Your email has been activated'}, status=status.HTTP_200_OK)
except jwt.exceptions.DecodeError as identifier:
return Response({'error': 'token not valid'}, status=status.HTTP_400_BAD_REQUEST)
Please I want to know why the the code in the try section never gets executed even when the token is intact and has not expired.
Try to use key = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])

What is the purpose of the UID within this Django Sign Up Function

I am learning how to create a django sign up page and I am at the point of creating an email verification. I am trying to use the code snippet here:
def usersignup(request):
if request.method == 'POST':
form = UserSignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
email_subject = 'Activate Your Account'
message = render_to_string('activate_account.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token': account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(email_subject, message, to=[to_email])
email.send()
return HttpResponse('We have sent you an email, please confirm your email
but I do not know what purpose the uid serves. Why is encoding the user model object in the verification email necessary?

validating user input using flask_wtf and sqlalchemy

Noob question. I am building a login/registration pages, on the registration page, I am using flask_wtf to verify certain things like length of password, email format and whether the two password a user supplies match. Here is the flask_wtf code I am using to do that.
# import statements omitted for brevity
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
After checking the input, I am using sqlalchemy to check if the username and email already exists in my DB. The problem I am facing right now is I cant get flask_wtf to verify the form. I can type whatever I want and it will be converted to a sql query. Here are my two flask routes that handle registration and user input validation.
#app.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
return redirect(url_for('check_user_input'))
return render_template('register.html',form=form)
#app.route('/status',methods=['POST'])
def check_user_input():
name = request.form.get("username")
email = request.form.get("email")
password = request.form.get("password")
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":name}).rowcount==1:
return render_template("404.html", message="Sorry username already exists")
elif db.execute("SELECT * FROM DB WHERE email= :email",
{"email":email}).rowcount==1:
return render_template("404.html", message="Sorry email already exists")
else:
db.execute("INSERT INTO DB (username,email,password) VALUES
(:username,:email,:password)",
{"username":name, "email":email,"password":password})
db.commit()
return render_template("success.html")
How can I get flask_wtf form to do its verification first and then hand the input to check_user_input() function?
My register.html contains the following line.
<form class="form-signin" method="POST" action="{{url_for('check_user_input')}}">
Any help would be greatly appreciated.
A way is to add a custom validation to the form :
class RegistrationForm(FlaskForm):
username = StringField('Username',
validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email',validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password',
validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
submit = SubmitField('Sign Up')
def validate(self):
rv = FlaskForm.validate(self)
if not rv:
return False
if db.execute("SELECT * FROM DB WHERE username= :username",{"username":self.username.data}).rowcount>0:
self.username.errors.append('Sorry username already exists')
return False
if db.execute("SELECT * FROM DB WHERE email= :email", {"email":self.email.data}).rowcount>0:
self.email.errors.append('Sorry email already exists')
return False
return True

Django Registration - using extended usercreation form. The login is activated before clicking the activation link

I have a registraion form with the basic details and an extended user form with aditional field. The registration works fine, the mail is sent with actiavtion link. But before the activation link is clicked the login in active. I can login with the usernama and password i used for regsitraion even before the activation link is clicked.
Could someone please help and let me know where i am missing:
def register(request):
if request.method == 'POST':
form = ExtentedUserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
profile = profile_form.save(commit=False)
user = form.save(commit=False)
user.is_active = False
profile.user = user
profile.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('registration/acc_activate_email.html', {
'user': user,
'profile': profile,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
#'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, 'spraysyndb-support#uni-due.de',to=['spraysyndb-support#uni-due.de']
)
email.send()
return render(request, 'thankyou.html')
#return HttpResponse('Welcome to the SpraysynDB, you would receive an confirmation from the admin. Thank you')
else:
form = ExtentedUserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form': profile_form}
return render(request, 'registration/regform.html', context )
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
auth_login(request, user)
return render(request, 'userlogindetails.html')
#return HttpResponse('Thank you for your email confirmation. Now you can login your account at www.spraysyndb/login.de')
else:
return HttpResponse('Activation link is invalid!')

How to show validation error for inactive user with some response code

I am trying to build custom user model in django-rest-framework. The problem which i am facing is how should i show the custom message with response code when the user is not activate.
Currently if the user provided the correct credentials but the account is not active then he is throwing error response code 400 with the validation error. Here is my code which I am using for the login validation.
class TokenAuthSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField(
style = {'input_type':'password'},
trim_whitespace = False
)
def validate(self,attrs):
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request= self.context.get('request'),
email = email,
password = password
)
if not user:
msg = _('Unable to authenticate with given credentials')
raise serializers.ValidationError(msg, code = 'authorization')
attrs['user'] = user
return attrs
In views:
class CreateTokenAuthorization(ObtainAuthToken):
serializer_class = TokenAuthSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
How to override this method to get the proper response code for the user is not active. Thank you for looking over it.

Resources