I'm trying to change the standard django registration using crispy-forms, but at the same time the registration confirmation email stops coming - django-allauth

Installed crispy-forms and configured templates for authentication. Everything works well. Problem with registration. With the standard registration form, I fill out the forms, then an email is sent to the mail confirming registration with a link to activate the account. But as soon as I try to implement the crispy-forms template, the letter stops coming and immediately throws it to the login form. How do I make emails arrive using crispy-forms?
I tried a lot of things but there is no result
forms.py
your
class SignUpForm(UserCreationForm):
email = forms.EmailField(label="Email")
first_name = forms.CharField(label="Имя")
last_name = forms.CharField(label="Фамилия")
class Meta:
model = User
fields = (
"username",
"first_name",
"last_name",
"email",
"password1",
"password2",
)
text
views.py
`your
class SignUpView(CreateView):
model = User
form_class = SignUpForm
success_url = reverse_lazy('login')
template_name = 'registration/signup.html'
success_message = "Ваш профиль создан"
texturls.pyyour
urlpatterns = [
path("signup/", SignUpView.as_view(), name='signup'),
path("update/<int:pk>", AccountUserUpdate.as_view(), name='account_update'),
path('setauthor/', set_me_author, name='set_me_author'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
path('password-change/', views.PasswordChangeView.as_view(), name='password_change'),
path('password-change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'),
path('password-reset/', views.PasswordResetView.as_view(), name='password_reset'),
path('password-reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
text`

Related

How do I send a link using the smtplib module? F string not working

email user specific developer jobs at a given location
import requests # for api
import smtplib # for emails
import auth
class Jobs:
URL = "https://jobs.github.com/positions" # base url for API
def _jobs_api(self): # get json data (jobs)
location = input("Where would you like to become a developer? \U0001f607\n") # location parameter
description = input("What type of developer are you interested in becoming? \U0001f608\n") # search term
response = requests.get(Jobs.URL,
headers={"Accept": "application/json"},
params={"location": location, "description": description} # query params
)
data = response.json()
return data
def _job_links(self):
data = self._jobs_api()
if data:
for job in data:
links = job['url']
return links
else:
print(f"Sorry, I was not able to find any {self.description} jobs in {self.location}...")
def send_jobs(self): # email auth
links = self._job_links()
smpt_object = smtplib.SMTP('smtp.gmail.com', 587)
smpt_object.ehlo()
smpt_object.starttls()
# use own authentication data
email = auth.email()
password = auth.password()
smpt_object.login(email, password)
# next, send the message
from_address = email
to_address = email
subject = "Developer Jobs"
message = "Here are some jobs you are looking for: {}".format(links)
msg = "Subject: "+subject+"\n"+message
print("Check your email for an update! \U0001f601")
smpt_object.sendmail(from_address, to_address, msg)
smpt_object.quit()
user = Jobs()
user.send_jobs()
I'm trying to use the line Here are some jobs you are looking for: {}".format(links) (or an f string preferably) to send the links found from the API. But, when I check my email, it doesn't show the message with the links.
You can try to send a html structured mail in python to send the url you want.
See this post to find out

Have to add a simple condition in Rails

I have to setup my rails project to send a confirmation SMS to new users. I have a table phone_calling_codes which has a column sms_enable_flag. In my DB this field has to be checked or not, so it's boolean.
I use Twilio to send SMS but I want to add a condition to send SMS only to the numbers where this sms_enable_flag is checked.
I also use phonelib to parse the number and take the country code from it.
def perform(phone_number, confirmation_code)
logger.info("Job started sending confirmation code")
overrideToPhone = [ "development","upgrade"].include? Rails.env
deliverSMS = !([ "development", "upgrade"].include? Rails.env)
phone=''
if overrideToPhone
e164Prefix = '+'
phone_number = e164Prefix + "17782002024"
else
phone = Phonelib.parse( phone_number)
phone_number = phone.e164
end
sms=phone_calling_codes.find_by calling_code: phone.country_code
if sms
if sms.sms_enabled_flag
from_phone_number = Rails.application.secrets.twilio_number
body = "Valorbit.com - your phone verification code is: #{confirmation_code}"
logger.info("From #{from_phone_number} to #{phone_number} : #{body}")
twilio_client.messages.create(
to: phone_number ,
from: from_phone_number ,
body: body
) if deliverSMS
logger.info("Sent sms to #{phone_number}") if deliverSMS
else
logger.info("SMS is not enabled for #{phone_number}")
end
end
end
Please help me to this. I am a beginner to OOP and I want to understand if it is ok how I have thought.
Thanks! :D
change line
sms=phone_calling_codes.find_by calling_code: phone.country_code
to
sms=PhoneCallingCode.find_by calling_code: phone.country_code
PhoneCallingCode is the model name present in /app/models folder
Below is the query to find data from model:
ModelName.find_by column_name: parameter

getting Django current user on iOS app

I'm new to Django, I'm starting a Django app, I'm using the registration app and Django rest framework, this app will also serve as the backend for an iOS app, I already manage to create users from the iOS app and edit User Profiles from the browser, I need help to find an approach that lets the user edit his profile details once he is logged in. I tried setting a lookup_field like "user.username" to the UserProfileViewSet so I could access the UserProfile object and edit it, but that didn't work.
I also thought I could somehow return the user id after logging in and use this id to reference the userprofile I wanna edit but it does not seem practical at all. What do you think??
Other way I found to do this is by calling user.get_profile() but I don't know how I can make this work from the iOS app.
Here is my UserProfile Model, and serializers, any help would be great. Thanks
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
# Extra attribuets
pagetitle = models.TextField(null=False)
location = models.TextField(null=True)
website = models.TextField(null=True)
bio = models.TextField(null=True)
sex = models.TextField(null=True)
birthdate = models.DateField(null=True)
def __unicode__(self):
return "%s's profile" % self.user
def create_profile(sender, instance, created, **kwargs):
if created:
profile, created= UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('username','email','password')
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(many=False)
class Meta:
model = UserProfile
fields = ('user','bio')
I create the UserProfile using a signal like this
def create_profile(sender, instance, created, **kwargs):
if created:
profile, created= UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
You didn't post your ViewSet code, so I have to guess. But your model should be set to User and your lookup_field should be set to username.
Something like:
class UserViewSet(ModelViewSet):
model = User
lookup_field = "username"
For everyone trying to get the profile for a user this is the way I managed to do it thanks to Kevin's help.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
depth = 1
fields = ('id','username','email','profile')
class CurrentUserView(APIView):
def get(self, request):
serializer = UserSerializer(request.user)
return Response(serializer.data)
Using a url like this
url(r'^api/current-user',CurrentUserView.as_view(),
name="current_user"),
You will get an answer like this
"id": 1,
"username": "username",
"email": "email#email.com",
"profile": {
"id": 1,
"user": 1,
"bio": "My Bio",
"sex": "M",
"birthdate": "1987-12-02"
}

Django admin - Email username and password on user creation

I'm using django-1.4.3 and the superuser can create users and assign password to them. Here I'm using django-email-as-username to enable users to login with their email as username. When the superuser adds a new user, the newly added user should be notified through email with his username and password.
I'm able to send email after user creation using post_save signal. But I couldn't get the password as it will be encrypted and stored. I want to email the user, the raw password. How can I achieve this?
I have achieved it using the code below:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
#receiver(post_save, sender = User)
def my_callback(sender, **kwargs):
import inspect
records =[]
for frame_record in inspect.stack():
records.append(frame_record[3])
if frame_record[3]=='get_response':
request = frame_record[0].f_locals['request']
email = request.POST.get('email')
password1 = request.POST.get('password1')
password2 = request.POST.get('password2')
if email != None and password1 != None and password2 != None and password1 == password2:
html_content ="Hi,<br> Your username: %s <br> Password: %s"
from_email = settings.DEFAULT_FROM_EMAIL
message = EmailMessage('Welcome', html_content %(email, password1), from_email, [email])
message.content_subtype = "html" # Main content is now text/html
message.send()
break

Getting First Name/Last Name/Email from Twitter using OAuth

I'm using omniauth exclusively to allow login to my website with facebook/google/twitter.
I store first name, last name, and email. However, when I raise the twitter auth hash from oauth I only get nickname, name, location, image, description and urls in the auth hash.
Is there a scope I can pass in my initializer to get the user's email and break name out into the first_name, last_name fields?
Twitter does not give out user emails so you will not be able to get that information from the Twitter API. Instead, you have to ask the user to type in their email address on your sign up form.
As far as splitting the name up, you'd do that once you have the hash returned using something like:
social_params ||= request.env["omniauth.auth"]
fullname = social_params["user_info"]["name"].split(' ')
first_name, last_name = fullname[0], fullname[1]
puts "first name is #{first_name} and last name is #{last_name}"
Just keep in mind that last_name could be nil if they don't have a space in their name or they didn't give a last name. This also doesn't consider the fact that many people have multiple last names in other cultures.
Using the current Twitter API is possible getting the email. You have to fill a form requesting that permission. The process is easy and quick, it is explained here.
Requesting a user’s email address requires your application to be whitelisted by Twitter. To request access, please use this form.
Once whitelisted, the “Request email addresses from users” checkbox will be available under your app permissions on apps.twitter.com. Privacy Policy URL and Terms of Service URL fields will also be available under settings which are required for email access. If enabled, users will be informed via the oauth/authorize dialog that your app can access their email address.
Well Twitter by Design will not pass you use email id.This is a deliberate design decision by the API team.
Here is same thread for your refrence
Is there a way to get an user's email ID after verifying her Twitter identity using OAuth?
If you have integration with FB , Google and Twitter than you will need to have a first and last in your DB (if your UI requires it > my case). This is what I came up with as some countries have people with more than 2 tokens for their names ex: (Marco De Franca Solis) or (Marco, De Franca Solis)
// + TEST CASES
var name1 = handleName("Marco De Franca Solis")
var name2 = handleName("first,last wer wer")
var name3 = handleName("aName")
var name4 = handleName("")
// - TEST CASES
handleName = function(input) {
var n=input.indexOf(" ");
n += input.indexOf(",");
var result = {};
if(n < 0){
result.first = input
result.last = ""
}
else{
arr = input.split(/[ ,]+/);
result.first = arr[0]
result.last = ""
if(arr.length > 1)
{
arr[0] = ""
result.last = arr.join(" ");
}
}
return result
}
OmniAuth is giving you all the names combined in one string. But, some people have more than two-word names, such as "John Clark Smith". You can choose to treat those in three different ways:
(1) first_name: "John", last_name: "Smith"
def first_name
if name.split.count > 1
name.split.first
else
name
end
end
def last_name
if name.split.count > 1
name.split.last
end
end
(2) first_name: "John Clark", last_name: "Smith"
def first_name
if name.split.count > 1
name.split[0..-2].join(' ')
else
name
end
end
def last_name
if name.split.count > 1
name.split.last
end
end
(3) first_name: "John", last_name: "Clark Smith"
def first_name
name.split.first
end
def last_name
if name.split.count > 1
name.split[1..-1].join(' ')
end
end
The above examples assume that if the name contains less than 2 words then it is a first name. This question is similar to this one
for php use:
$names = explode(' ',$socialData->firstName);
$socialData->firstName=array_shift($names);
$socialData->lastName=implode(' ',$names);
Be aware the name could have multiple surnames and possibly multiple firstnames, this deals with multiple surnames but not firstnames.

Resources