Django - send email as html (django-sesame ) - html

Hy,
I don't know how to send email as html. I try every example that can i find but i don't know how to implement in my code. When it's arive in mail show all the html not only the the message. Please help me to implement send as html format in my code below. Thank you
def email(request):
campanii = Campanie.objects.order_by('-pub_date')
if request.method == 'POST':
form = EmailLoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email'].lower()
user = UserVot.objects.filter(email=email).first()
if user is None: # daca userul nu exista cu acea adresa de email
messages.error(request, "adresa de email nu este corecta sau valida")
return render(request, 'loginvot/email.html', {'form' : form, 'campanii':campanii , 'error_message' : "adresa de email nu este corecta sau valida"} )
link += sesame.utils.get_query_string(user)
user.email_user(
subject="Link vot",
message="""\
<html >
<head>
<meta charset="UTF-8">
</head>
<body>
<p> Salutare, <h4>{{user.username}}</h4></p><br>
<p>Acceseaza link-ul de mai jos pentru a intra in sectiunea de vot "Ambasadorii Valorilor Profi"</p><br>
{{link}}
</body>
</html>
"""
)
return render(request, 'loginvot/email.html', {'campanii':campanii , 'error_succes' : "in maximum 1 minut vei primi pe adresa de email completata un link de accesare sesiune de vot"} )
context = {'form' : EmailLoginForm, 'campanii' : campanii}
return render(request, 'loginvot/email.html', context)

The solution turned out to be much simpler than I anticipated. I put the email message in a separate file (template_mail.html) and i use funtion render_to_string then in user.email_user I added html_message wich take that template_mail. This is how the code now looks and works.
template_mail = render_to_string ('loginvot/template_email.html', {'user' : user, 'link' : link } )
user.email_user(
subject='Link vot Ambasadorii valorilor Profi',
message=f"""some message""",
html_message = template_mail
)

Related

HTML ActionLink not sending to desired url in a new tab

Here is the code block:
<p>
Confira abaixo as perguntas frequentes. Se ainda assim
precisar, você poderá fazer #Html.ActionLink("contato nas unidades mais próximas",
"Index", "UnidadesEstados", new { target = "_blank" })
ou por e-mail.
</p>
If I remove the new { target = "_blank" } the page open correctly in the same tab.
I want to open this in a new tab, but when I execute, the URL that open its like:
http://localhost:61467/FAQ?**Length=15**
What I´m doing wrong?
I had included a null parameter between the others and this did the trick:
#Html.ActionLink("contato nas unidades mais próximas", "Index", "UnidadesEstados", null, new { target = "_blank" })

Split HTML in a certain form of list in Python

For a django project i need to generate from the Django Website a kind of complex Word document.
I started using Docx-Template that do the job great but i encountered a problem:
For certain "spot" in the word template i need to brake Django rich texte (HTML) in something usable for Docx Template
So i went into transforming my richtext in a list that can have two types of elements (to keep the order of the blocs) : ["some paragraphs","('list',['first elt of the list for bullet','second','ect...")]
For now i have two function : one that break the HTML and one that transform it
My "HTML Breaking function" is like that :
def decoupe_html (raw_html):
soup=BeautifulSoup(raw_html,"html.parser")
arbre=[]
#decoupe en grand bloc HTML
for elt in soup:
arbre.append(elt)
print(arbre)
#On parcours chaque elt pour le transformer en truc compréhensible par Word dans une liste
for elt in arbre:
#recup du tag de début du "chunk"
tag=elt.name
#traitement des paragraphe de texte
if tag == "p":
texte=elt.text
place=arbre.index(elt)
arbre[place]=texte
#traitement des listes
elif tag == "ul":
list_elt=[]
enfants = elt.findChildren()
#on récupère tous les elt de la liste
for chld in enfants:
list_elt.append(chld.text)
place=arbre.index(elt)
arbre[place]=("list",list_elt)
return(arbre)
But i have trouble in "breaking" more complex list with multi level like for example this html :
<p>pfoizepfkjze</p>
<ul>
<li>blabla
<ul>
<li>bla2
<ul>
<li>bla3
<ul>
<li>bla4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>rebla</li>
</ul>
what should i change in my code to keep my data structure and get for example :
arbre = ['pfoizepfkjze',('list',['blabla',('list',['bla2',('list',['bla3',('list',['bla4'])])]),'rebla'])]
Thanks all for your help :)

getting next item in beatiful Soup

With Beautiful soup I need to detect the meaning of one expression. From the many definitions, only one is needed. In the Beautiful soup the contents is like this:
<strong>occhio della testa</strong><br/>
loc.s.m <br/>
<span class="mu"title="">CO</span><span style="color:#000"> </span><br/>
follia<br/>
<strong>pagare un occhio della testa</strong><br/>
loc.v.<br/>
<span class="mu"title="">CO</span><span style="color:#000"> </span><br/>
strapagare<br/>
<strong>passare per la testa</strong><br/>
loc.v.<br/>
<span class="mu" title="">CO</span><span style="color:#000"> </span><br/>
passare per la mente<br/>
<strong>perdere la testa</strong><br/>
loc.v.<br/>
<span class="mu" title="">CO</span><span style="color:#000"> </span><br/>
entrare in uno stato di confusione mentale; impazzire, spec. fig.: ha perso la testa per quella donna, se ne è perdutamente innamorato<br/>
<strong>
What I need from the above text is :
pagare un occhio della testa:strapagare
I tried this
# list of expressions that I need their meaning
myitems = ['pagare un occhio della testa', '....' , '....']
for ex in myitems:
ws = ex.split()
li = ""
url = "https://mydictionary/" + ws[-1]+ ""
if urllib.request.urlopen(url):
htmlfile = urllib.request.urlopen(url)
soup = BeautifulSoup(htmlfile, 'lxml')
txt = soup.text
if ex in txt:
li = '%s = %r' % (es, soup.next_siblings)
print(li)
This code gives only the ex. Can someone help?
I don't know how regular the structure is but for the above you can use the following (bs4 4.7.1):
soup.select_one('strong:contains("pagare un occhio della testa") ~ span + span').next_sibling.next_sibling.strip()

Django: Save forms independently

I have two forms in two different tabs in the same template. The models of the forms are connected through a foreign key.
When I'm trying to save each form independently having a submit button for each form, but unfortunately the two forms are trying to save data again, even I push only one submit button.
Views.py
def input(request):
my_demographics = DemographicForm(request.POST or None)
my_diagnosis = DiagnosisForm(request.POST or None)
context = RequestContext(request)
if request.method == 'POST':
submitted = request.POST.get('form_id', '')
if submitted == 'demographics':
# Get the Form1 instance
my_demographics = DemographicForm(request.POST)
if my_demographics.is_valid():
my_demographics_object= my_demographics.save()
my_diagnosis=DiagnosisForm({'patient': my_demographics_object.patient_id})
elif submitted == 'diagnosis':
# Get the Form2 instance
my_diagnosis = DiagnosisForm(request.POST)
if my_diagnosis.is_valid():
my_diagnosis.save()
else:
raise ValueError('No form specified !')
return render_to_response('input.html', {'frm':my_demographics, 'frm_d': my_diagnosis}, context)
input.html
<div class="tab-content">
<!-- Tab panes -->
<form class="tab-pane fade in active" id="demographics" method="post" >
<input type="hidden" name="form_id" value="demographics">
{%crispy frm%}
</form>
<form class="tab-pane fade" id="diagnosis" method="post">
<input type="hidden" name="form_id" value="diagnosis">
{%crispy frm_d%}
</form>
</div>
First add an hidden input in each of your forms, which will specify which form is posted:
<div class="tab-content">
<!-- Tab panes -->
<form class="tab-pane fade in active" id="demographics" method="post" >
<input type="hidden" name="form_id" value="demographics">
{%crispy frm%}
</form>
<form class="tab-pane fade" id="diagnosis" method="post">
<input type="hidden" name="form_id" value="diagnosis">
{%crispy frm_d%}
</form>
</div>
Then in your view, check which form is posted and only save this form.
edit:
def input(request):
context = RequestContext(request)
if request.method == 'POST':
submitted = request.POST.get('form_id', '')
if submitted == 'demographics':
# Get the Form1 instance
my_demographics = DemographicForm(request.POST)
if my_demographics.is_valid():
my_demographics_object= my_demographics.save()
my_diagnosis=DiagnosisForm({'patient': my_demographics_object.patient_id})
else:
my_diagnosis=DiagnosisForm()
elif submitted == 'diagnosis':
# Get the Form2 instance
my_diagnosis = DiagnosisForm(request.POST)
if my_diagnosis.is_valid():
my_diagnosis.save()
# here you should redirect
my_demographics = DemographicForm()
else:
raise ValueError('No form specified !')
else:
my_demographics = DemographicForm()
my_diagnosis = DiagnosisForm()
return render_to_response(
'input.html',
{'frm':my_demographics, 'frm_d': my_diagnosis},
context
)
The view will have the input names that were inside the form submitted only, that is how you now, so you can add a hidden field and check for its value, if form1, or form2 then you know witch one have being submitted !
if request.POST:
# Get the form submitted
submitted = request.POST.get('form_name', '')
if submitted == 'form1'
# Get the Form1 instance
form = Form1Model(request.POST)
elif submitted == 'form2'
# Get the Form2 instance
form = Form2Model(request.POST)
else:
raise ValueError('No form specified !')
# Validate the form
if form.is_valid():
# If the form is valid save it
if form.save():
# correct data entry
messages.info(
request,
_(u"Fichier copié sur le DHS, mise à jour en cours ...")
)
else:
# Can't save the form
messages.warning(
request,
_(u"Un problème est survenu pendant l'enregistrement "
u"des données, merci de réessayer plus tard.")
)
else:
# Form is not valid, show feedback to the user
messages.error(
request,
_(u"Merci de corriger les erreurs suivantes.")
)
else:
# Empty forms this is the first call
form1 = Form1Model()
form2 = Form2Model()
# Disclaimer
messages.warning(
request,
_(u"L'interface web sera inaccessible durant la mise à jour.")
)

Razor's engine does not automatically encode HTML tags

To be honest, this is my first time using asp.net web api and Razor.
I received an asp.net web api solution which uses itextSharp to generate a pdf.
The pdf is generated, but it is showing html tags that were sent with the content via jquery and JSON.
This is how it looks in PDF:
<div class="nf-filler-control-border"><div class="nf-filler-control-inner"><div class="ms-r
testate-field"><div
class="ExternalClassD88FE0C0B2A64B1797917A506C26ACA2"><div
class="ExternalClassAD6BB90065794E90B1097577B8697812">Aantal genodigden: 19</div><div
class="ExternalClassAD6BB90065794E90B1097577B8697812">Aantal aanwezig: 15</div><p
class="ExternalClassAD6BB90065794E90B1097577B8697812">Aantal ziek/verlof: 3</p><div
class="ExternalClassAD6BB90065794E90B1097577B8697812"><ol><li>Bij veiligheidsrondgang uitgevoerd op 02/04/13. Veel
gereedschap ligt niet op hun plaats, is onbeheerd achtergelaten, ligt in fietskarren, en zijn bovendien niet ingeschreven in
het register; kasten staan open, ladders niet afgesloten.</li><li>Persoonlijk werkgereedschap blijft gewoon liggen zelf
heeft men de dag erna verlof. = rommel.</li><li>Bij controle stekkers verleng kabels zien we dat de trekontlasting niet
correct gebruikt wordt en dat de insnijdingen te groot zijn. Zie foto's.</li>
<li>Alle communicatie (ziektebriefjes, KV,.....)met HR is nu naar Interleuvenlaan 27A - 3001 Herverlee
(achterzijde personeelsbadge)</li></ol></div></div></div></div></div>
this is the piece of code that displays data which is sent via jquery's ajax function: #Model.Description
And this is where the Razor engine parses the html template: return Razor.Parse(template, model);
Anyone has got any idea how to show the content properly inside the pdf without showing up the html tags on the document?
the html table shows fine, only the data displayed by #Model.Description does not show correctly.
this is the code:
private static string GetReport(ToolBoxMeeting tm)
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof (HtmlTemplateBase<>)
};
using (new TemplateService(config))
{
string template = #"<html>
<body >
<table >
<tr>
<td'>Description</td>
<td>
#Model.Description
</td>
</tr>
</table>
</body>
</html>";
var model = tm;
return Razor.Parse(template, model);
}
}