I have authentication app with email verification in it. I send an email like this:
If registration form is valid then we save the form(create user) and set his token to uuid.uuid4.
class customer_register(CreateView):
model = User
form_class = CustomerSignUpForm
template_name = 'authentication/customer_register.html'
def form_valid(self, form):
user = form.save()
user.token = str(uuid.uuid4)
subject = 'Verify your account | Zane'
message = f"http://127.0.0.1:8000/verify/{user.token}/"
send_mail(
subject,
message,
'from#example.com',
['to#example.com'],
fail_silently=False,
)
In my mailtrap.io email arrives but it has some weird body:
http://127.0.0.1:8000/verify/<function uuid4 at 0x103f32040>/
Please use str(uuid.uuid4()) instead of str(uuid.uuid4)
Related
class ProjectListAndFormView(SuccessMessageMixin, ListView, FormView):
model = Project # data from database
template_name = 'mainpage/main.html'
context_object_name = 'list_projects' # name of the var in html template
queryset = Project.objects.all().order_by("-pub_date")# list of all projects
object_list = None
form_class = ContactForm
success_url = '/' # After submiting the form keep staying on the same url
success_message = 'Your Form has been successfully submitted!'
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
cd = form.cleaned_data
con = get_connection('django.core.mail.backends.console.EmailBackend')
send_mail(
cd['name'],
cd['message'],
cd.get('email', 'noreply#example.com'),
['22agrandon#gmail.com'],
fail_silently=False
)
return super(ProjectListAndFormView, self).form_valid(form)
views.py
im having trouble with a form page on my website. Whenever i enter a random email on the email form part on the website it sends a succesful mail but from my own emayil even if i put a random email. How do i fix this so when someone enters their email, it sucesfully sends me an email from their email?
Here is the simple view for creating user and staff model.After creating user and staff, it sends the html email to the user's email to fill up the details and the view works fine.
Now I want to write test case for this view and tried like this below but i got stuck on how can i write test to check whether the email will be sent or not after saving staff model, to the users.
models.py
class Staff(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
name = models.CharField(max_length=255, blank=True, null=True)
organization = models.ForeignKey(Organization, on_delete=models.SET_NULL,related_name='staff')
position = models.ForeignKey(Position, on_delete=models.SET_NULL,related_name='staff')
.......
views.py
def register_staff(request):
form = RegisterStaffForm()
if request.method == 'POST':
form = RegisterStaffForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
organization = form.cleaned_data['organization']
position = form.cleaned_data['position']
......
user = form.save(commit=False)
user.is_staff = True
user.is_active = True
user.save()
# creating staff model with user data
Staff.objects.create(user=user, name=name, organization=organization, position=position,....)
# sending html_email to the user
config = EmailConfiguration.objects.order_by('-date').first()
backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user,
password=config.email_host_password, use_tls=config.email_use_tls)
subject, from_email, to = "Staff Details", config.email_host_user, user.email
text_content = "Staff Details "
site = get_current_site(request)
html_content = render_to_string('send_email.html',
{'user': user, 'site_domain': site,})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to],connection=backend)
msg.attach_alternative(html_content, "text/html")
msg.send()
tests.py
class StaffTestCase(TestCase):
def setUp(self):
self.position = Position.objects.create(title='Developer')
self.org = Organization.objects.create(name='name')
self.user = get_user_model().objects.create_user(username='username01',password='Admin#321',email='abc#xyz.com',is_staff=True)
self.staff = Staff.objects.create(user=self.user,position=self.position,organization=self.org,name='Julia')
self.client = Client()
def test_view_staffs(self):
self.client.login(username='username01', password='Admin#321')
response = self.client.get(reverse('app:view_staff_users'))
self.assertEqual(response.status_code, 200)
def add_staff(self):
self.client.login(username='username01', password='Admin#321')
url = reverse('app:register_staff')
response = self.client.post(url, {'user': self.user,'organization':'name1','position':'Designer','name':'Mark'})
self.assertEqual(response.status_code, 302)
def check_email_will_sent_or_not(self):
??
Django provides tools to test the sending of emails, but from my understanding, these only work with the default email backend configured in your settings file.
That leaves you with four options:
figure out if you can monkeypatch your view to use locmem backend in testing
mock EmailBackend in your register_staff view and check if its send_messages function is called.
spin up a dummy SMTP server and check if it receives the messages
use valid credentials to actually send the emails to addresses you control and check if the email is received
The options 3 & 4 give you the most confidence that your email sending really works, but they might turn out to be slow and brittle and actually test the email sending code of Django itself. I would go with option 2.
I'm overriding the built-in PasswordResetView but the email isn't sent. I'm currently using django.core.mail.backends.console.EnailBackend but the email's content doesn't show up on console.
My code is like this
class CustomPasswordResetView(PasswordResetView):
email_template_name = 'accounts/password_reset_email.html'
form_class = CustomForm
template_name = 'accounts/password_reset.html'
subject_template_name = 'accounts/password_reset_subject.txt'
title = 'Custom Title'
success_url = reverse_lazy('accounts/password_reset_done')
It redirects to the password_reset_done as expected but the email doesn't show on concole.
Is there something I missed? As long as I see the Django's code, I cannot find the part handling with sending email in PasswordResetView Do I have to write email functionality manually?
forms.py
class CustomPasswordResetForm(PasswordResetForm):
def __init__(self, *args, **kwargs):
super(CustomPasswordResetForm, self).__init__(*args, **kwargs)
...
def save(self, ...):
super().save()
Problem is that, the email is sent from the form, not the view. So if you are using CustomForm, its better to implement the send email method in the form like this:
class CustomForm(forms.Form):
...
def send_mail(self):
return send_mail(
'Subject here',
'Here is the message.',
'from#example.com',
[self.cleaned_data.get('email')],
fail_silently=False,
)
def is_valid(self):
valid = super(CustomForm, self).is_valid()
if valid:
self.send_email()
return valid
Or you can override from PasswordResetForm and put your customization there.
I am writing an API view where am accessing API to POST email and password to the address and fetch response.So i want if response is 200 or repose message is 'Success' then to login with available email and password datas, but i'm not able to do so. How to achieve such?
class ApiLoginView(TemplateView):
template_name = 'index.html'
def post(self,request):
email = request.POST.get('login-email')
print(email)
password = request.POST.get('login-password')
print(password)
API_KEY = '*********************'
API_URL = 'http://devstudio.com/rest/storeLogin'
parameter = {
'authToken':API_KEY,
'email':email,
'password':password,
}
r = session.post(url = API_URL, params=parameter)
return HttpResponse(r)
if you are using djagno's built-in auth and user system then you can use something like this
from django.contrib.auth import authenticate, login
class ApiLoginView(TemplateView):
template_name = 'index.html'
def post(self,request):
email = request.POST.get('login-email')
print(email)
password = request.POST.get('login-password')
print(password)
API_KEY = '*********************'
API_URL = 'http://devstudio.com/rest/storeLogin'
parameter = {
'authToken':API_KEY,
'email':email,
'password':password,
}
r = session.post(url = API_URL, params=parameter)
if r.status_code==200:
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
else:
# Return an 'invalid login' error message.
return HttpResponse(r)
for reference check this https://docs.djangoproject.com/en/2.1/topics/auth/default/#topic-authorization
hope this helps..
I've create following form:
class ContactForm(forms.Form):
full_name = forms.CharField(required=False)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea(attrs={'class':'special', 'size': '40'}))
But when I add data in Message field with some data it isn't coming up in my email associated with this form with settings mentioned in Settings.py. But full_name and email is coming up fine.
My view is:
def contact(request):
title = "Contact Us"
form = ContactForm(request.POST or None)
if form.is_valid():
form_email = form.cleaned_data.get('email')
form_message = form.cleaned_data.get('message')
form_full_name = form.cleaned_data.get('full_name')
subject = "Site Contact Form"
from_email = settings.EMAIL_HOST_USER
to_email = [from_email, myemail#gmail.com']
contact_message = "%s: %s via %s"%(form_full_name, form_message, form_email)
html_template = "<h1>Hello There</h1>"
send_mail(subject, contact_message, from_email, to_email, html_message=html_template, fail_silently=True)
context = {
"form":form,
"title": title
}
return render(request, 'contact/form.html', context)
Also I need to know what would be the best option to create some form to recieve information directly to my email. Should I use models based form or simple form without models? Please advise as my message field text is not coming up in email but Name and email is coming up fine.
Try this,
message = forms.CharField(widget=forms.TextInput(attrs={'class':'special', 'size': '40'}))