Django messages framework - django

I'm looking to add Django messages in my form in order to display success message if my form is validated and error message if my form is not validated (missing field, data type error, ...)
My error message works perfectly well, but I don't overcome to display my success message in the next template when my form is valid.
This is my view :
def BirthCertificate_Form_unique_number(request) :
validity = []
submission = []
#User fill some fields
query_social_number = request.GET.get('social_number')
query_social_number_father = request.GET.get('social_number_father')
query_social_number_mother = request.GET.get('social_number_mother')
success = False
if request.method == 'POST':
form = BirthCertificateForm2(request.POST or None)
if form.is_valid() : # Vérification sur la validité des données
post = form.save()
messages.success(request, 'Le formulaire a été enregistré !')
return HttpResponseRedirect(reverse('BC_treated2', args=(messages,),kwargs={'id': post.id}))
else:
messages.error(request, "Le formulaire est invalide !")
elif request.method == 'GET':
form = BirthCertificateForm2()
parent1 = Person.objects.filter(social_number=query_social_number_father)
parent2 = Person.objects.filter(social_number=query_social_number_mother)
if query_social_number :
if Person.objects.filter(social_number = query_social_number).exists() == True :
individu = get_object_or_404(Person, social_number = query_social_number)
messages.success(request, 'Le numéro unique existe !')
form.fields['fk_parent1'].queryset = parent1
form.fields['fk_parent2'].queryset = parent2
form.fields['lastname'].initial = individu.lastname
form.fields['firstname'].initial = individu.firstname
form.fields['birthday'].initial = individu.birthday
form.fields['birthcity'].initial = individu.birthcity
form.fields['birthcountry'].initial = individu.birthcountry
form.fields['sex'].initial = individu.sex
form.fields['social_number'].initial = individu.social_number
elif Person.objects.filter(social_number = query_social_number).exists() == False :
validity = False
messages.error(request, "Le numéro unique est invalide !")
context = {
"form" : form,
"validity" : validity,
"submission" : submission
}
return render(request, 'BC_form2.html', context)
and in my html template :
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
{% endfor %}
How I could display the success message when my form is valid ?
EDIT :
My urls.py file :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^BC_accueil$', views.BirthCertificate_Home, name="BChome"),
url(r'^formulaire$', views.BirthCertificate_Form, name = "BCform"),
url(r'^formulaire2$', views.BirthCertificate_Form_unique_number, name = "BCform2"),
url(r'^formulaire_traite/(?P<id>\d+)/$', views.BirthCertificate_Resume, name="BC_treated"),
url(r'^formulaire2_traite/(?P<id>\d+)/$', views.BirthCertificate_Resume_unique_number, name="BC_treated2"),
url(r'^BirthCertificate_PDF/(?P<id>\d+)/$', views.BirthCertificate_PDF, name="PDF"),
url(r'^not_found$', views.BirthCertificate_notfound, name="BCnotfound"),
]

You need to know one thing that, messages will execute only once. Why did you do
args=(messages, )
You can access those messages in BC_treated2 without passing it as args

Related

Django template == condition on string doesn't work

I want to display in an email template some conditional informations but even if the {{ error }} confirms the value of my error is list index out of range , the condition is not applied and else is taken in account.
I send to my (email) template this:
views.py
try:
[...]
except Exception as e:
error_product_import_alert(
{'order_increment_id': order_increment_id, 'product': item['sku'],
'error': e, 'request': request})
error_product_import_alert()
def error_product_import_alert(context):
product = context['product']
order_id = context['order_increment_id']
error = context['error']
sujet = f' Anomalie : Import SKU {product} ({order_id}) impossible
({error})!'
contenu = render_to_string('gsm2/alerts/product_import_ko.html', context)
[...]
email template
<p>--{{ error }}--</p>
{% if error == 'list index out of range' %}
<p><strong>Le produit est introuvable dans la base.</strong></p>
{% else %}
<p><strong>Erreur inconnue : veuillez contacter l'administrateur.</strong></p>
{% endif %}
Maybe my error is so big that I even can't see it.
Is there one ?
You are comparing an Exception to a string. This would not work in templates. Try doing the logic in your python function itself and return the error string that will be rendered in the template.
For example:
You should try:
views.py
try:
[...]
except Exception as e:
error = "Erreur inconnue : veuillez contacter l'administrateur."
if e.args[0] == 'list index out of range':
error = "Le produit est introuvable dans la base."
error_product_import_alert({
'order_increment_id': order_increment_id,
'product': item['sku'],
'error': error,
'request': request
})
template
<p><strong>{{error}}</strong></p>

How to open an uploaded file in another template - Django?

my django app acts as an emailing service, emails that are sent are view-able and it's possible to send html emails. How do I display the html emails on the view-mail page rather than just displaying the name of the file ? (the following is the mail-view for an html email):
How would I display the actual html in the body of this page?
This is my views.py:
def outbox(request):
#Mail_Item.objects.all().delete()
if request.method == "POST" and request.POST.get('Username', False)!=False:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
print(username + " has logged in")
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
else:
return render(request, '404.html')
elif request.POST.get('Username', False) == False and request.POST.get('mail_body_field', False) == False:
pass
elif request.method == "POST" and request.POST.get('mail_subject_field')!=False:
subject = request.POST.get('mail_subject_field')
body = request.POST['mail_body_field']
file = ""
try:
file = request.FILES['filename']
except:
pass
print("sending mail:")
for i in range(1, len(Res)+1):
y = Res['ID' + str(i)].email
print("sent to " + y )
msg = EmailMessage(subject, body, 'email#example.com', [y])
msg.content_subtype = "html"
if (str(file)) != "" and (str(file))[-4:] != 'html':
msg.attach_file(str(file))
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
print("email stored in database")
elif (str(file)) != "" and (str(file))[-4:] == 'html' :
uploaded_file = file
fs = FileSystemStorage()
fs.save((str(file)), uploaded_file)
html_message = render_to_string((str(file)), {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <email2#example.com>'
mail.send_mail(subject, plain_message, from_email, [y], html_message=html_message)
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
else:
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name='None')
obj.save()
print("email stored in database")
#msg.send()
i += 1
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return HttpResponseRedirect('../templates/outbox.html', args, request)
else:
print("pleeeeeaassee")
return render(request, '404.html')
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
def login_page(request):
if request.method == "POST":
username = request.POST['sign-up-name']
email = request.POST['sign-up-email']
password = request.POST['sign-up-password']
user = User.objects.create_user(username, email, password)
user.save()
print(username + " has been added to the user database.")
else:
pass
return render(request, 'login.html')
def signup_page(request):
return render(request, 'signup.html')
def mail_view(request, id=None):
if id:
email = Mail_Item.objects.get(id=id)
args = {'email':email}
else:
pass
return render(request, 'mail-view.html', args)
def log_out(request):
logout(request)
return render(request, 'log-out.html')
def delete(request):
Mail_Item.objects.filter(id=id).delete()
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
This is the code for my mail-view template where I'd like to place the html that is being sent:
<div class="mail-view">
<h4 class="m-0">{{ email.subject }}</h4>
<div class="divid"></div>
<div class="media">
<div class="media-left">
<div class="avatar avatar-lg avatar-circle">
<img class="img-responsive" src="{% static '../static/assets/images/221.jpg' %}" alt="avatar"/>
</div><!-- .avatar -->
</div>
<div class="media-body">
<div class="m-b-sm">
<h4 class="m-0 inline-block m-r-lg">
Access Bank
</h4>
</div>
<p><b>Attachment: </b>{{ email.file_name }}</p>
</div>
</div>
<div class="divid"></div>
<div class="row">
<div class="col-md-12">
<div class="m-h-lg lh-xl">
<p>{{ email.body }}</p>
</div>
</div>
</div>
</div>
Models.py:
from django.db import models
class Details(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
class Mail_Item(models.Model):
subject = models.CharField(max_length=200)
body = models.CharField(max_length=300)
time = models.DateTimeField(auto_now=True)
user = models.CharField(max_length=15)
file_name = models.CharField(max_length=100, null=True, default=None)
def __str__(self):
template = '{0.subject} {0.body} {0.time} {0.user} {0.file_name}'
return template.format(self)

Django reverse match error for keyword arguments

I am a newbie in python and I' training to make an app in Django to keep track of my clients problems in a personal training center.
I'm stuck in resolving a reverse match error for keyword arguments that is not passed. Honestly I am trying to understand how django manage this keyword arguments with no success.
The error that django throws me is:
NoReverseMatch at /persone/1/post
Reverse for 'cliente_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['persone\\/(?P<pk>[0-9]+)\\/$']
Request Method: GET
Request URL: http://localhost:8000/persone/1/post
Django Version: 2.0.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'cliente_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['persone\\/(?P<pk>[0-9]+)\\/$']
Exception Location: C:\Users\perso\Envs\djangodev\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636
Python Executable: C:\Users\perso\Envs\djangodev\Scripts\python.exe
Python Version: 3.6.4
Python Path:
['C:\\Users\\perso\\Dropbox\\Django\\Frame\\filo_project',
'C:\\Users\\perso\\Envs\\djangodev\\Scripts\\python36.zip',
'C:\\Users\\perso\\Envs\\djangodev\\DLLs',
'C:\\Users\\perso\\Envs\\djangodev\\lib',
'C:\\Users\\perso\\Envs\\djangodev\\Scripts',
'c:\\users\\perso\\appdata\\local\\programs\\python\\python36-32\\Lib',
'c:\\users\\perso\\appdata\\local\\programs\\python\\python36-32\\DLLs',
'C:\\Users\\perso\\Envs\\djangodev',
'C:\\Users\\perso\\Envs\\djangodev\\lib\\site-packages']
Server time: Mar, 31 Lug 2018 11:58:32 +0200
My views.py:
import json
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormView
#Qui importo la classe per essere sicuro che se l'user non è loggato lo deve far loggare
from django.contrib.auth.decorators import login_required
#Ricordarsi di importare anche i modelli:
from .models import Cliente, FitCheck, Post
#login_required(login_url='/accounts/login/')
def home(request):
return render(request, "filogest/home.html")
class ClienteListView(LoginRequiredMixin, ListView):
#questa vista mi permette di visualizzare tutto l'elenco dei clienti
model = Cliente
template_name= "filogest/elenco_clienti.html"
#quetso per richiamare nel html il nome dell'elenco
context_object_name = 'elenco_clienti'
class ClienteDetailView(LoginRequiredMixin, DetailView):
model=Cliente
template_name="filogest/cliente_detail.html"
context_object_name = 'cliente_detail'
###############################
#Vai di editing di fitcheck
###############################
class FitcheckDetailView(LoginRequiredMixin, DetailView):
model=FitCheck
template_name="filogest/fitcheck_detail.html"
context_object_name = 'fitcheck_detail'
class FitcheckUpdateView(LoginRequiredMixin, UpdateView):
model = FitCheck
fields = ['idfitcheck','colazioneregolare']
template_name="filogest/fitcheck_update.html"
###############################
#Vai di editing di post
###############################
class PostDetailView(LoginRequiredMixin, DetailView):
model = Post
template_name="filogest/post_detail.html"
context_object_name = 'post_detail'
# def myPostListView(request, pk):
# idcli = get_object_or_404(Post, idclientepost=pk)
# posts_fisio = Post.objects.filter(tipologia="FI",idclientepost=idcli)
# posts_pale = Post.objects.filter(tipologia="PA",idclientepost=idcli)
# post = {"posts_fisio": posts_fisio, "posts_pale": posts_pale}
# return render(request, 'filogest/post_list.html', post)
class PostListView(LoginRequiredMixin, ListView):
model = Post
template_name = 'filogest/post_list.html'
context_object_name = 'post_list'
def get_context_data(self, *args, **kwargs):
context = super(PostListView, self).get_context_data(*args, **kwargs)
context['FisioPost'] = Post.objects.filter(tipologia="FI",idclientepost=self.kwargs['idclientepost'])
context['PalePost'] = Post.objects.filter(tipologia="PA",idclientepost=self.kwargs['idclientepost'])
context['fkPost'] = Post.objects.filter(idclientepost=self.kwargs['idclientepost'])
return context
class PostDetailCreate(LoginRequiredMixin, CreateView):
model = Post
template_name = 'post_create'
fields = '__all__'
###############################
#Vai di editing di post
###############################
#da controllare di brutto
def CercaPersona(request):
return render(request, "filogest/seleziona_cliente.html")
def AutocompleteCliente(request):
q = request.GET.get("term", "")
clienti = Cliente.objects.filter(nome__icontains=q)
results = []
for cliente in clienti:
place_json = {}
place_json = cliente.nome + " " + cliente.cognome
results.append(place_json)
data = json.dumps(results)
return HttpResponse(data, 'application/json')
models.py
from django.db import models
from django.contrib.auth.models import User
#importo timezone perchè così posso usare la funzione per capire quando è stato inserito
#un cliente oppure un fitcheck
from django.utils import timezone
from datetime import datetime
# Create your models here.
#questa funzione permette di far fare al sistema django i link per
#gli articoli referenziati
from django.urls import reverse
class Cliente(models.Model):
SESSO = (
('M','Maschio'),
('F','Femmina'),
)
idcliente = models.AutoField(primary_key=True)
nome = models.CharField(max_length=50)
cognome = models.CharField(max_length=50)
datadinascita = models.DateField()
sesso = models.CharField(max_length=1,choices=SESSO)
datainsert = models.DateTimeField(auto_now=True)
def __str__(self):
return self.cognome + " " + self.nome
def age(self):
return int((datetime.now().date() - self.datadinascita).days / 365.25)
#Qui uso questa funzione per far gestire al sistema i link che andro poi a richiamare
#con la classe.get_absolute_url
def get_absolute_url(self):
return reverse("filogest:cliente_detail", kwargs={"pk":self.idcliente})
class Meta:
# link utile : https://docs.djangoproject.com/en/2.0/ref/models/options/
verbose_name = "Cliente"
verbose_name_plural = "Clienti"
class FitCheck(models.Model):
STILE_PROFESSIONE = (
('PA','Poco attiva'),
('MA','Mediamente attiva'),
('A', 'Attiva'),
('MM','Molto Attiva'),
('US','Usurante'),
)
SI_NO = (
('S','Si'),
('N','No'),
)
ALIMENTAZIONE_TIPO = (
('D','Dietologo'),
('F', 'Fai da te'),
('N', 'Nutrizionista'),
('O', 'Nulla'),
)
STILE_DI_VITA = (
('PA','Poco Attivo'),
('MA', 'Mediamente Attivo'),
('AA', 'Attivo'),
('AM', 'Molto Attivo'),
('US', 'Usurante'),
)
OBIETTIVO_PRIMARIO = (
('DI','Dimagrimento'),
('PE', 'Performance'),
('DO', 'Dolore'),
('MU', 'Muscolazione'),
('FI', 'Fitness Generale'),
('GR', 'Gravidanza'),
('PG', 'Post Gravidanza'),
('PO', 'Postura'),
('RI', 'Rieducazione'),
('OP', 'Pre-Intervento'),
('CV', 'Cardio Vascolare'),
('PM', 'Prescrizione Medica'),
)
HA_DOLORE = (
('A','Acuto'), #dall'ultima settimana ha dolore
('S','Sub-acuto'), #dalla fase di dolore a 6 settimane
('C','Cronico'),
('N','No')
)
PROFESSIONE = (
('A','Altro'),
('C','Casalinga'),
('I','Impiegato'),
('O','Operaio'),
('S','Sportivo'),
('U','Studente'),
('P','Pensionato'),
('L','Libero Professionista'),
('T','Autista'),
)
STRESS = (
('PS','Poco Stressante'),
('ST','Stressante'),
('MS','Molto Stressante'),
)
DISP_ORARIA = (
('MA','Mattina'),
('PP','Pausa Pranzo'),
('PO','Pomeriggio'),
('SE','Sera'),
('TU','Turni'),
('LI','Libero'),
)
PROPOSTA_ACCETTATA = (
('S','Si'),
('N','No'),
('F','Fa Sapere'),
)
OSTEO = (
('F','Fatta'),
('D','Da Fare'),
('N','No'),
)
FONTE = (
('MA','Mattia'),
('PC','Paolo Cucchetti'),
('FD','Federico Dal Corso'),
('IN','Insegna'),
('IT','Internet'),
('UM','Monsellato'),
('MC','Marco'),
('PR','Paolo Roma'),
('TR','Trainer'),
('CL','Clienti'),
('MD','Medici'),
('AM','Amicizie'),
('VA','Varie'),
)
EFFETTUATO_DA = (
('MP','Marco P'),
('PR','Paolo R'),
('MA','Marco A'),
('PC','Paolo C'),
)
FUMATORE = (
('SI','Si'),
('ST','Saltuariamente'),
('NO','No'),
('EX','Ex'),
)
VAS = (
('0','0'),
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
('8','8'),
('9','9'),
('10','10')
)
idfitcheck = models.OneToOneField(Cliente, on_delete=models.CASCADE, primary_key=True)
luogodinascita = models.CharField(max_length=50, verbose_name="Luogo di nascita")
email = models.EmailField(verbose_name="E-mail")
telefono = models.CharField(max_length=20, verbose_name="Numero di telefono")
indirizzo = models.CharField(max_length=100, verbose_name="Indirizzo")
citta = models.CharField(max_length=20, verbose_name="Città")
cap = models.CharField(max_length=5, verbose_name="CAP")
figli = models.CharField(max_length=50, verbose_name="Figli")
professione = models.CharField(max_length=1,choices=PROFESSIONE, verbose_name="Professione")
stileprofessione = models.CharField(max_length=2,choices=STILE_PROFESSIONE, verbose_name="Stile Professione")
stiledivita = models.CharField(max_length=2,choices=STILE_DI_VITA, verbose_name="Stile di vita")
stress = models.CharField(max_length=2,choices=STRESS, verbose_name="Come definisce il suo stile di vita?")
fumatore = models.CharField(max_length=2, choices=FUMATORE, verbose_name="Fuma?")
obiettivoprimario = models.CharField(max_length=2,choices=OBIETTIVO_PRIMARIO, verbose_name="Obiettivo Primario")
noteprimario = models.TextField(verbose_name="Note obiettivo primario")
obiettivosecondario = models.TextField(verbose_name="Obiettivo secondario")
alimentazione = models.CharField(max_length=2,choices=ALIMENTAZIONE_TIPO, verbose_name="Cura alimentazione")
alimcontrollataattiva = models.CharField(max_length=2,choices=SI_NO, verbose_name="Attualmente l'alimentazione è controllata")
pastialgiorno = models.IntegerField(verbose_name="Quanti pasti fa al giorno?")
colazioneregolare = models.CharField(max_length=2,choices=SI_NO, verbose_name="Fa colazione regolarmente?")
giabia = models.CharField(max_length=2,choices=SI_NO,verbose_name="Ha già fatto test BIA?")
attivitaattuali = models.CharField(max_length=2,choices=SI_NO,verbose_name="Attualmente svolge attività fisiche?")
attivitafisicarecente = models.CharField(max_length=500, verbose_name="Attività fisiche recenti")
attivitapassato = models.CharField(max_length=2,choices=SI_NO, verbose_name="In passato ha svolto attività?")
qualiattivita = models.CharField(max_length=500,verbose_name="Se si quali?")
assumealcool = models.CharField(max_length=2,verbose_name="Assume alcool?", choices=FUMATORE)
quantitaalcol = models.FloatField(verbose_name="Quanti bicchieri beve al giorno?")
attualmenteagonista = models.CharField(max_length=2,choices=SI_NO, verbose_name="Attualmente Agonista")
hadolore = models.CharField(max_length=2,choices=HA_DOLORE, verbose_name="Attualmente ha dolore?")
vasnrs = models.CharField(max_length=1, choices=VAS, verbose_name="Scala vas del dolore acuto e sub-acuto")
doloripassati = models.CharField(max_length=2,choices=SI_NO, verbose_name="Dolori in passato?")
notedoloripassati = models.TextField(verbose_name="Note su dolori")
traumipassati = models.CharField(max_length=2,choices=SI_NO, verbose_name="Ha subito traumi in passato")
interventichirurgici = models.CharField(max_length=2,choices=SI_NO)
notetraumiinterventi = models.TextField(verbose_name="Note traumi/interventi")
altremalattie = models.TextField(verbose_name="Altre malattie?")
altro = models.TextField(verbose_name="Altro da segnalare?")
disponibilitaoraria = models.CharField(max_length=2,choices=DISP_ORARIA)
freqsettimanale = models.FloatField(verbose_name="Quante volte riuscirebbe a venire regolarmente?")
seduteproposte = models.IntegerField(verbose_name="Sedute proposte dal trainer")
propostaaccettata = models.CharField(max_length=1,choices=PROPOSTA_ACCETTATA, verbose_name="Proposta fatta dal trainer accettata?")
fonte = models.CharField(max_length=2,choices=FONTE, verbose_name="Fonte")
sedutaprova = models.CharField(max_length=2,choices=SI_NO, verbose_name="Seduta di prova fissata?")
totaleeconomico = models.FloatField(verbose_name="Totale economico proposto?")
biaprogrammata = models.CharField(max_length=1,choices=OSTEO, verbose_name="Bia programmata?")
osteoprogrammata = models.CharField(max_length=1,choices=OSTEO, verbose_name="Valutazione osteopatica programmata?")
fisioprogrammata = models.CharField(max_length=1,choices=OSTEO, verbose_name="Valutazione fisioterapica programmata?")
stapedio = models.CharField(max_length=2,choices=SI_NO)
datainserimento= models.DateTimeField(auto_now=True)
effettuato = models.CharField(max_length=2, choices=EFFETTUATO_DA, verbose_name="Colloquio effettuato da?")
def __str__(self):
return self.idfitcheck.cognome + " "+ self.idfitcheck.nome
def nome_persona(self):
return self.idfitcheck.cognome + " "+ self.idfitcheck.nome
def fitchekpk(self):
return self.idfitcheck
def get_absolute_url(self):
return reverse("filogest:fitcheck_detail", kwargs={"pk":self.idfitcheck})
class Meta:
# link utile : https://docs.djangoproject.com/en/2.0/ref/models/options/
verbose_name = "FitCheck"
verbose_name_plural = "FitChecks"
#da qui parte lo script per il modello di balke che prendere:
#1- età
#2-SESSO
#3-Peso che va creato ad ok
#4- da qui calcolare poi la frequenza cardiaca massima
#5- permettere l'inserimento dei dati del test
#6- elaborare e salvare i risultati
class Balke(models.Model):
idbalke = models.ForeignKey(Cliente,on_delete=models.CASCADE, related_name="filogest_balke_clienti")
etasogg = models.IntegerField()
pesosogg = models.FloatField()
blocco1=models.IntegerField()
blocco2=models.IntegerField()
blocco3=models.IntegerField()
blocco4=models.IntegerField()
blocco5=models.IntegerField()
blocco6=models.IntegerField()
blocco7=models.IntegerField()
def __str__ (self):
return self.idbalke.cognome + " "+ self.idbalke.nome
def cooper(self):
return 220-Cliente.age
def tanaka(self):
return (208-(0,7*Cliente.age))
class Post(models.Model):
OBIETTIVO_PERSONA = (
('DI','Dimagrimento'),
('PE', 'Performance'),
('DO', 'Dolore'),
('MU', 'Muscolazione'),
('FI', 'Fitness Generale'),
('GR', 'Gravidanza'),
('PG', 'Post Gravidanza'),
('PO', 'Postura'),
('RI', 'Rieducazione'),
('OP', 'Pre-Intervento'),
('CV', 'Cardio Vascolare'),
('PM', 'Prescrizione Medica'),
)
TIPO = (
('FI', 'Fisio / Osteo'),
('PA', 'Palestra'),
)
idpost = models.AutoField(primary_key=True)
idclientepost = models.ForeignKey(Cliente, on_delete=models.CASCADE, related_name="cliente")
tipologia = models.CharField(max_length=2, choices=TIPO)
titolo = models.CharField(max_length=250)
obiettivo = models.CharField(max_length=2, choices=OBIETTIVO_PERSONA)
autore = models.ForeignKey(User, on_delete=models.CASCADE,related_name="filogest_post")
corpo = models.TextField()
creato = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-creato',)
def get_absolute_url(self):
return reverse("filogest:post_detail", kwargs={"idclientepost": self.idclientepost.idcliente, "pk":self.idpost})
return reverse("filogest:post_list", kwargs={"idclientepost": self.idclientepost.idcliente})
def __str__(self):
return self.titolo
Urls.py:
from django.urls import path, include, reverse
from .views import home, ClienteListView, ClienteDetailView, AutocompleteCliente, CercaPersona, FitcheckDetailView, FitcheckUpdateView
from .views import PostListView, PostDetailView, PostListView
app_name='filogest'
urlpatterns = [
path ('', home, name='homepage'),
path ('persone/', ClienteListView.as_view(), name='elenco_clienti'),
path ('persone/<int:pk>/', ClienteDetailView.as_view(), name='cliente_detail'),
path ('getperson/', AutocompleteCliente, name='autocomplete_cliente'),
path ('cercaper/', CercaPersona, name='cerca_persona'),
path ('persone/<int:pk>/fitcheck', FitcheckDetailView.as_view(), name='fitcheck_detail'),
path ('persone/<int:pk>/fitcheckupdate', FitcheckUpdateView.as_view(), name='fitcheck_update'),
#uso idcliente post perchè il modello è il post ma il riferimento è la chiave esterna
path ('persone/<int:idclientepost>/post', PostListView.as_view(), name='post_list'),
path ('persone/<int:idclientepost>/post/<int:pk>',PostDetailView.as_view(), name='post_detail'),
]
cliente_detail template
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %}{{ block.super }} - Dettagli Cliente{% endblock head_title %}
{% block content %}
<br>
<div class="">
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:cliente_detail' pk=cliente_detail.idcliente %}';">Dettagli Anagrafici</button>
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:fitcheck_detail' pk=cliente_detail.idcliente %}';">FitCheck</button>
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:post_list' idclientepost=cliente_detail.idcliente %}';">Note operative</button>
<button type="button" class="btn btn-primary">Test Balke</button>
<button type="button" class="btn btn-primary">Test Motori</button>
</div>
<br>
<div class="alert alert-warning" role="alert">
<br>
<h1>Dettagli persona:</h1>
<hr>
<strong>Cognome:</strong> {{ cliente_detail.cognome }} <br>
<strong>Nome:</strong> {{ cliente_detail.nome }} <br>
<strong>Data di nascita:</strong> {{ cliente_detail.datadinascita }} <br>
<strong>Sesso:</strong> {{ cliente_detail.sesso }} <br>
<strong>Età:</strong> {{ cliente_detail.age }} <br>
<hr>
</div>
{% endblock content %}
post_list
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block head_title %}{{ block.super }} - Dettagli Cliente{% endblock head_title %}
{% block content %}
<br>
<div class="">
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:cliente_detail' pk=post_list.idclientepost %}';">Dettagli Anagrafici</button>
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:fitcheck_detail' pk=1 %}';">FitCheck</button>
<button type="button" class="btn btn-primary">Note operative</button>
<button type="button" class="btn btn-primary">Test Balke</button>
<button type="button" class="btn btn-primary">Test Motori</button>
</div>
<div>
<br>
<h1>Commenti di {% for post in fkPost %}
{% if forloop.first %}
{{ post.idclientepost.cognome }} {{ post.idclientepost.nome}}
{% endif %}
{% endfor %}</h1>
<div class="container">
<div class="row">
<div class="col">
<h2>Note Osteofisio :</h2>
<br>
{% for post in FisioPost %}
<div class="p-2 border border-primary">
<strong>Titolo:</strong> {{ post.titolo }} <br>
<strong>Obiettivo:</strong> {{post.get_obiettivo_display}} <br>
<div class="p-1 border">
<strong>Nota:</strong><br>
{{post.corpo}}<br>
</div>
<i>Creato da: <strong>{{post.autore}}</strong> in data {{post.creato}}</i>
{{post.idclientepost}}
</div>
{% endfor %}
</div>
<div class="col">
<h2>Note Trainer:</h2>
<br>
{% for post in PalePost %}
<div class="p-2 border border-success">
<strong>Titolo:</strong> {{ post.titolo }} <br>
<strong>Obiettivo:</strong> {{post.get_obiettivo_display}} <br>
<div class="p-1 border">
<strong>Nota:</strong><br>
{{post.corpo}}<br>
</div>
<i>Creato da: <strong>{{post.autore}}</strong> in data {{post.creato}}</i>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock content %}
Any help would be appreciated.
As far as I can see this exception is raised at PostListView. In your template filogest/post_list.html you have a detail button:
<button type="button" class="btn btn-primary" onclick="location.href='{% url 'filogest:cliente_detail' pk=post_list.idclientepost %}';">Dettagli Anagrafici</button>
You are creating the url with the argument pk=post_list.idclientepost. I believe the post_list.idclientepost maybe null or blank for the instance. As it's mentioned in the error pk is passed blank (with keyword arguments '{'pk': ''}').
Reverse for 'cliente_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['persone\\/(?P<pk>[0-9]+)\\/$']

This field is required error on Django using formset

I have three forms, forms.py:
class HotelForm(forms.Form):
rooms = forms.IntegerField(label=(u'Rooms'), min_value=1)
class TouristsForm(forms.Form):
adult = forms.IntegerField(label=(u'Adults'), min_value=1, initial=1)
children = forms.IntegerField(label=(u'Children'), min_value=0, initial=0, required=False)
class ChildrenAgeForm(forms.Form):
children_age = forms.IntegerField(label=(u'Children Age'), min_value=2, max_value=10, initial=2, required=False)
That's how i realize formset and validation in views.py:
def bookingForm(request):
TouristsFormSet = formset_factory(TouristsForm, extra = 1, max_num = 15)
ChildrenAgeFormSet = formset_factory(ChildrenAgeForm, extra = 1, max_num = 20)
if request.method == 'POST':
booking_form = HotelForm(request.POST, prefix='booking_form')
tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
if booking_form.is_valid() and tourists_formset.is_valid() and childrenage_formset.is_valid():
rooms = booking_form.cleaned_data['rooms']
for i in range(0, tourists_formset.total_form_count()):
tourists_form = tourists_formset.forms[i]
tourists = tourists_form.cleaned_data
for n in range(0, childrenage_formset.total_form_count()):
childrenage_form = childrenage_formset.forms[n]
childrenage = childrenage_form.cleaned_data
template = get_template("booking/result.html")
context = Context({'tourists_formset':tourists_formset, 'childrenage_formset':childrenage_formset })
html = template.render(context)
return HttpResponse( html )
else:
booking_form = HotelForm()
tourists_formset = TouristsFormSet(prefix='tourists')
childrenage_formset = ChildrenAgeFormSet(prefix='childrenage')
return render(request, 'booking/booking.html', { 'booking_form' : booking_form, 'tourists_formset' : tourists_formset, 'childrenage_formset' : childrenage_formset })
And this is how i realize html file:
{{ tourists_formset.management_form }}
{% for tourists in tourists_formset %}
{{ tourists }}
{% endfor %}
{{ childrenage_formset.management_form }}
{% for childrenage in childrenage_formset %}
{{ childrenage }}
{% endfor %}
Every time when i fill all fields in the form i have an error 'This field is required' for the HotelForm form. I can't understand why it is happen. Thanks for help
You are using a prefix when handling the POST request.
booking_form = HotelForm(request.POST, prefix='booking_form')
You need to use the same prefix for the GET request.
booking_form = HotelForm(prefix='booking_form')

Django form with no errors return False for is_valid()

I'm generating a form from metadata
class MeasureForm(forms.Form):
def __init__(self,*args,**kwargs):
super(MeasureForm,self).__init__()
measure_id = kwargs['measure_id']
m = Measure.objects.get(pk=measure_id);
if (m):
# add the measure identifier as a hidden field
self.fields["measure_id"] = forms.IntegerField(initial = m.id , widget=forms.HiddenInput())
for mp in MeasureParameters.objects.filter(measure = m):
# get the NVL'ed copy of the parameter
p = mp.get_parameter_for_measure()
if not p.is_modifiable:
# the file has a constant value
if (p.values and p.default): # constant must have both values and default index
value_ = p.values[p.values.keys()[p.default-1]];
self.fields[p.name] = forms.IntegerField(
label = p.description ,
initial = value_,
help_text = p.help_text)
self.fields[p.name].widget.attrs['readonly'] = True
else:
raise Exception("Parameter set as unmodifiable but has no value. \
[measure: %s, parameter: %s, measureparameter %s]"
% (m.id , p.id , mp.__unicode__()))
elif (p.values):
# convert hstore dict to list of tuples for the choices to read
values_ = [(v, k) for k, v in p.values.iteritems()];
# set default if exists , else take the first item
default_ = values_[p.default-1][0] if p.default else values_[0][0]
self.fields[p.name] = forms.ChoiceField(
label = p.description ,
choices = values_ ,
initial = default_,
help_text = p.help_text)
else:
self.fields[p.name] = forms.IntegerField(label = p.description, help_text = p.help_text)
if (not p.is_visible):
self.fields[p.name].widget = forms.HiddenInput()
else:
raise Exception ("Could not find measure. [measure %s]" % (m.id))
def clean(self):
return self.cleaned_data;
this is my view
def index(request,measure_id = None):
owners = Owner.objects.all()
form = None
result = None
title = None;
msg = None;
# handle the form
if request.method == 'POST': # the form has been submitted
form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id')) # A form bound to the POST data
result = -100
if form.is_valid(): # All validation rules pass
result = 100
msg = "%s" % repr(form.errors) # list of validation errors
else:
if (measure_id):
title = Measure.objects.get(pk=measure_id).name;
# make an unbound form
form = MeasureForm(measure_id = measure_id)
return render(request, 'calc/index.html' ,
{'owners' : owners,
'form' : form ,
'title' : title ,
'result' : result,
'debug' : msg })
this is a snippet from my template
<div class="content">
{{ form.errors }}
{{ form.non_field_errors }}
{% if form %}
<h2>{{ title }}</h2>
<form action="/calc/{{m.id}}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Calculate" />
</form>
{% if result %}
The Result is <span class="result"> {{ result }} </span>
{% endif %}
</div>
So i get empty braces {} for "%s" % repr(form.errors), form.errors and form.non_field_errors returns nothing. the form posts and I can see the raw data in the request but i keep getting false from is_valid(). why is that ?
EDIT: when checking if the form is bound i also get false. guessing this is the problem. why isn't the form bound after the call for form = MeasureForm(request.POST, measure_id = request.POST.get('measure_id')) ?
** django newbie, Thanks.
Because you're not passing the arguments into the super call. You should do this:
super(MeasureForm,self).__init__(*args, **kwargs)
otherwise the form will never actually be initialised with the POST data.
Edit after comment The answer to that question didn't recommend removing all the arguments from the super call. If you're passing in measure_id you'll simply need to remove it from kwargs beforehand:
def __init__(self, *args, **kwargs):
measure_id = kwargs.pop('measure_id', None)
super(MeasureForm,self).__init__(*args, **kwargs)