HOW to send authentication number by e-mail - django

I want to send an 8-digit authentication number by e-mail.
No matter how hard I try, I don't know what I'm doing wrong.
First, I set the smtp. Then, I filled out the form. After creating the view, I created a template.
After entering e-mail and username, I pressed the Send button.
WHAT? id:
email:
[29/Mar/2022 09:43:39] "GET /recovery/pw/?email=wlgns000%40gmail.com&username=wlgns HTTP/1.1" 200 2030
However, only these logs appear, and the authentication number does not come by e-mail.
How can I send an authentication number by e-mail?
#settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.naver.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = #email
EMAIL_HOST_PASSWORD = #password
EMAIL_USE_TLS = True
DEFAULT_FROM_MAIL = EMAIL_HOST_USER
{% load static %}
<!DOCTYPE html>
<html lang="KO">
<head>
....
<link href="{% static 'users/css/recovery_pw.css' %}" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="{% static 'users/js/recovery_pw.js' %}"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<script>
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
</script>
</head>
<body>
{% block content %}
<form method="get" enctype="multipart/form-data">
{% csrf_token %}
<div class="container">
<div class="inner-box">
...
<div class="input-box">
<div class="id">
<input type="email" placeholder="등록하신 메일로 인증번호가 발송됩니다." name="email" maxlenth="20" autocomplete="off" value="{{ form.email.value|default_if_none:'' }}" required />
</div>
<div class="password">
<input type="username" placeholder="아이디를 입력하세요" name="username" maxlength="20" value="{{ form.username.value|default_if_none:'' }}" required />
</div>
</div>
<div class="btn">
<div class="btn-white" id="btn_white"><button type="submit">send mail</button></div>
</div>
...
</form>
{% endblock %}
</body>
</html>
# views.py
class RecoveryPwView(View):
template_name = 'users/recovery_pw.html'
recovery_pw = RecoveryPwForm
def get(self, request):
if request.method=='GET':
print("here?")
form = self.recovery_pw(None)
return render(request, self.template_name, { 'form':form, })
#csrf_exempt
def ajax_find_pw_view(request):
username = request.POST.get('username')
email = request.POST.get('email')
target_user = User.objects.get(username=username, email=email)
if target_user:
auth_num = email_auth_num()
print(auth_num, "1111")
target_user.auth = auth_num
print(target_user.auth, "2222")
target_user.save()
send_mail(
'email',
['#email'],
html=render_to_string('users/recovery_email.html', {
'auth_num': auth_num,
}),
)
print(send_mail, "3333")
return HttpResponse(json.dumps({"result": target_user.username}, cls=DjangoJSONEncoder), content_type = "application/json")
#forms.py
class RecoveryPwForm(forms.Form):
username = forms.CharField(label='id')
email = forms.EmailField(label='email')
class Meta:
fields = ['username', 'email']
and last email.html
It is an HTML containing the authentication number sent by e-mail.
{% autoescape off %}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="{% static 'users/css/recovery_email.css' %}" rel="stylesheet">
<link href="{% static 'users/css/default.css' %}" rel="stylesheet">
<script>
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
</script>
</head>
<body>
...
<div class="auth"><p class="auth-p">{{ auth_num }}</p></div>
...
</body>
</html>
{% endautoescape %}

Related

Django-ckeditor showing content as textarea

I'm working with django ckeditor now and I can't display content that can be saved normally and is displayed in the admin panel. Content is always displayed as textarea
As you can see at the image, editor is working properly, also if i go to admin panel everything is OK, but if i want to display content of "body" ({{ form.body|safe}}), it will display only textarea of HTML code.
models.py
class Stage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
game_id = models.ForeignKey(Game,
on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sequence = models.IntegerField(null=False)
body = RichTextUploadingField(config_name='LeftFields', blank=True, null=True)
def get_questions(self):
return Question.objects.filter(stage_id = self.id)
def __str__(self):
return str(self.name)
forms.py
class StageForm(ModelForm):
class Meta:
model = Stage
fields = ['body','name']
widgets = {
'name': TextInput(attrs={
'class': "left_input",
'style': "width: 69.3%;",
}),
}
views.py
#login_required(login_url='/signin')
#user_passes_test(lambda u: u.is_staff)
def edit(request, gameid,id):
stage = Stage.objects.get(pk=id)
if request.method == 'POST':
form = StageForm(request.POST, instance=stage)
if form.is_valid():
form.save()
return redirect('/edit/' + gameid + '/' + id)
form = StageForm(instance=stage)
return render(request, "homeSuperuser/edit_stage.html", {'stage': stage, 'form': form,'gameid':gameid})
edit_stage.html
<!doctype html>
<html>
<head> {% load static %}
<link rel="stylesheet" href="{% static 'css/edit_pages.css' %}" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/edit.js' %}"></script>
</head>
<body>
<div class="row" id="mainDIV">
<form id="main" method="post" action="{{ request.path }}">
{% csrf_token %}
<div class="divs">
<a>Název: </a>
{{ form.name}}
</div>
<div class="divs"><a>Kontent:</a>
{{ form.media }}
{{ form.body}}
</div>
<div class="div_cent"><input type="submit" value="Uložit" class="subm" /></div>
</form>
</div>
{{ form.body|safe}}
</body>
</html>
form.body is the field itself, so includes the HTML textarea markup.
Instead of
{{ form.body|safe}}
try
{{ form.body.value|safe}}

Update is creating new entry rather than updating it

I have a model where users save their details. I am able to save user details through the template I have created. But whenever I edit the data to update it, a new entry is created in database
models.py
class User(AbstractUser):
pass
def __str__(self):
return self.username
class Detail(models.Model):
"""
This is the one for model.py
"""
username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="")
matricno = models.CharField(max_length=9, default="")
email = models.EmailField(default="")
first_name = models.CharField(max_length=200, default="")
last_name = models.CharField(max_length=255, default="")
class Meta:
verbose_name_plural = "Detail"
def __str__(self):
return self.first_name+ " "+self.last_name
views.py
#login_required(login_url="signin")
def details(request):
form = Details()
if request.method == "POST":
form = Details(request.POST)
if form.is_valid():
detail = form.save(commit=False)
detail.username = request.user
detail.save()
return redirect(success, pk=detail.pk)
else:
form = Details(initial={"matricno":request.user.username})
return render(request, "details.html", {"form":form})
def success(request,pk):
return render(request, "success.html", {"pk":pk})
def updatedetails(request, pk):
detail = Detail.objects.get(id=pk)
form = Details(instance=detail)
if request.method == "POST":
form = Details(request.POST, instance=detail)
if form.is_valid():
form.save()
return redirect(success, pk=detail.pk)
return render(request, "details.html", {"form":form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("details/", views.details, name="details"),
path("success/<int:pk>/", views.success, name="success"),
path("edit/<int:pk>/", views.updatedetails, name="updatedetails"),
]
The template used for rendering out the form to input user details goes as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>details</title>
</head>
<body>
<form action="/details/" method="POST">
{% csrf_token %}
{% if request.user.is_authenticated %}
<p>
{{form.matricno}}
</p>
<p>
{{form.email}}
</p>
<p>
{{form.first_name}}
</p>
<p>
{{form.last_name}}
</p>
<p>
<input type="submit" value="Create">
</p>
{% endif %}
<div>
<input type="button" value="SignOut">
</div>
</form>
</body>
</html>
After a user enters their details and it is saved to database successfully, it redirect to a success where their is a link that takes you back to the other page to edit the data you inputed and it goes as follows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Thank You for Filling Out the Form</h1>
<p>Click Here To Edit</p>
</body>
</html>
My problem now is that whenever i click on the link to edit, and i edit the details i have entered, it creates a new entry in database rather than updating previous data.
You need to POST to the edit view, so:
<form action="{% url 'updatedetails' pk=form.instance.pk %}" method="POST">
...
</form>
You should thus make two templates: one to create data, and one to edit data.

Customer registration with dynamic forms django

By entering the phone number in the customer registration form , if the customer already exists then should fill the rest of the fields by fetching it from the backend. if the user does not exists then have to register. help me with the script used for this
this is the model i have.
class Customers(models.Model):
customer_id = models.AutoField(primary_key=True)
cname = models.CharField(max_length=100)
cnumber= models.IntegerField()
caddress= models.CharField(max_length=100)
I m using the modelform here.
class CustForm(forms.ModelForm):
class Meta:
model=Customers
fields = '__all__
this is my view
def customer(request):
form=CustForm()
if request.method=='POST':
form = CustForm(request.POST)
form
if form.is_valid():
form.save(commit=True)
messages.success(request,'successfully customer added')
return render(request,'hello.html')
else:
messages.error(request,'Invalid')
return render(request,'custdata.html',{'form':form})
This is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% block content %}
<div>
<center><h2><b>Add Customer</b></h2></center>
<p><form method='post'>
{% csrf_token %}
<center>
{{form.as_p}}
<button type="submit" style="width:200px; height:30px; font-size: 20px;">ADD</button>
</center>
</form>
</div>
{% endblock %}
</body>
</html>```

My django form is not displaying on the html page

I am trying to create an addform to take input from a user and add it to my model, however, the form is not showing on the page, can someone tell me what I am doing wrong? Here is the code for the forms.py, views.py and add.html:
forms.py
class AddForm(forms.Form):
vehicle = forms.CharField(max_length=10)
carrier = forms.FloatField()
location = forms.ChoiceField(choices=[(1, 'Mathura Installation')])
customer_code = forms.FloatField()
zone = forms.ChoiceField(choices=[('NW', 'North West'),
('NCR', 'North Central'),
('SCR', 'South Central'),
('S', 'South'), ('N', 'North'),
('W', 'West'), ('E', 'East')
])
quantity = forms.FloatField()
load = forms.FloatField()
rtkm = forms.FloatField(label='RTKM')
rate = forms.ChoiceField(label='Rate ', widget=forms.RadioSelect, choices=[('avg', 'Average Rate'),
('user', 'User Rate')])
views.py
def add(request):
addform = forms.AddForm()
dict = {'addform': addform}
return render(request, 'add.html', dict)
urls.py
from django.contrib import admin
from django.urls import path
from searchapp import views
urlpatterns = [
path('', views.search, name='search'),
path('add/', views.add, name='add'),
path('admin/', admin.site.urls),
]
html - add.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<head>
<meta charset="UTF-8">
<title>Transport Portal - Add Page</title>
</head>
<body>
<div class="header">
<img src="{% static 'images/hpcl_logo.png' %}">
<h1>Transportation Portal</h1>
</div>
<div class="topnav">
<ul>
<li>Home</li>
<li>Search</li>
<li><a class="active" href="add.html">Add</a></li>
</ul>
</div>
<div class="add">
<form method="POST">
{% csrf_token %}
{{ addform.as_p }}
</form>
</div>
</body>
</html>
I think the problem is how you're getting there.
You have the following in your html
<li><a class="active" href="add.html">Add</a></li>
This is going to pick up the html page but you want href="{% url 'add' %}" which will pick up the django url.
Instead of dict use context
def add(request):
addform = forms.AddForm()
context= {'addform': addform}
return render(request, 'add.html', context)
Please read this. context

check column value and manipulate css djangotables2

I am using djangotables2 for the first time. I have successfully displayed a table which
is a list of dictonaries,where key and values are calculated from various sources in my
project database.
I have a requirement where i have to check the value of a column and change the background color like css or apply bootstrap badges.
Sample code :-
views.py
data_list = []
#search
query = request.GET.get('q')
if query:
user_list = UserProfile.objects.filter(user__email__icontains=query)
else:
user_list = UserProfile.objects.order_by("-user__date_joined")
for userprofile in user_list:
data_list.append({'user_id': userprofile.id,
'first_name': userprofile.user.first_name,
'last_name': userprofile.user.last_name,
'address': get_city(userprofile),
'dateofbirth': userprofile.dateofbirth,
'anniversary': "NA",
'number_of_orders':
get_total_orders(userprofile),
'total_revenue': get_total_revenue(userprofile),
'highest_order': get_higest_order(userprofile),
'registration_date':
userprofile.user.date_joined.date().strftime("%B %d %Y"),
'last_order_date': get_last_order(userprofile),
'last_order_to_present_day_differene':
get_difference_from_last_order(userprofile)
})
data = ThemedCRMTable(data_list, prefix="3-")
RequestConfig(request, paginate={"per_page": 15}).configure(data)
tables.py
class CRMTable(tables.Table):
user_id = tables.Column()
first_name = tables.Column()
last_name = tables.Column()
address = tables.Column()
dateofbirth = tables.Column()
anniversary = tables.Column()
number_of_orders = tables.Column()
total_revenue = tables.Column()
highest_order = tables.Column()
registration_date = tables.Column()
last_order_date = tables.Column()
last_order_to_present_day_differene = tables.Column()
class ThemedCRMTable(CRMTable):
class Meta:
attrs = {'class': 'paleblue'}
template
{% load static %}
{% load render_table from django_tables2 %}
<!doctype html>
<html>
<head>
<title>CRM Report</title>
<link rel="stylesheet" href="/static/report/css/screen.css" />
<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
<script src="{% static 'js/jquery.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</head>
<body>
<div class="container">
<div class="row" style="margin-top:2%;text-align:center;">
<form class="form-search pull-left">
<div class="input-append">
<input type="text" class="span4 search-query" name="q">
<button type="submit" class="btn">Search</button>
</div>
</form>
<strong style="font-size:20px;">CRM Report</strong>
<a class="btn btn-inverse pull-right offset1" href="/">
<span><i class="icon-step-backward icon-white icon-alignment"></i></span>
Go Back
</a>
<a class="btn btn-success pull-right offset1" href="{% url generate_crm_report_csv %}">
<span><i class="icon-download icon-white icon-alignment"></i></span>
CRM Report
</a>
</div>
{% render_table data_list %}
</div>
</body>
</html>
Question:-
I want to make the cell background red where the value of last column last_order_to_present_day_differene is greator than 30