I'm making a POST
call for adding an event in the on_message()
function at which step is a url to call the addEvent
function (to add the event) and then a payload with values defined by me (inside the mqtt_iot
file).
The compiler does not enter into the addEvent
function, it locks but does not make any errors (I'm using the terminal).
I enclose the code. How could I fix it?
In mqtt_Iot.py
:
def on_message(client, userdata, msg):
#convert byte json to json object and then to python dict to extract urls parameters
byte_payload = msg.payload
string_payload = byte_payload.decode('utf-8')
data_dict = json.loads(string_payload)
group_id = data_dict['group_id']
calendar_id = data_dict['calendar_id']
#in base al topic su cui ho ricevuto il messaggio faccio un azione o l'altra
if ( msg.topic == "event/update"):
#invio l'evento più prossimo alla board
client.publish(group_id,calendar_id)
elif ( msg.topic == "event/new"):
#il messaggio attiverà l'aggiunta di un evento facendo una post sul link adatto
url = 'http://127.0.0.1:8000/homeProva1/%d/calendars/%d/events/new/' % (group_id,calendar_id)
now= datet.datetime.now().time()
end_time = datet.datetime.now() + datet.timedelta(hours=1)
end_time = end_time.strftime("%H:%M:%S")
now = now.strftime("%H:%M:%S")
dt = datet.datetime.today()
dt = dt.strftime("%Y-%m-%d")
title = "Evento Node"
description = "Evento prenotato in loco"
payload = {"title": title, "day": dt, "start_time": now, "end_time": end_time, "notes":description}
print("Payload")
print(type(payload))
print(payload)
resp = requests.post(url,data=payload)
content= response.content
print (content)
In views.py
:
def addEvent(request, pk=None ,pk1=None):
print("sono dentro add event")
instance = Event()
instance = Event(calendar_id=pk1)
form = EventForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
print(form)
form.save()
print("form valido")
#controllo se evento appena aggiunto si svolgerà prima di un dato tempo ed in caso richiamo il publisher
e = Event.objects.filter(calendar=pk1).latest('id')
now= datetime.now().time()
#trasformo orari in int per poter sottrarre
now= int(now.strftime('%H%M%S'))
temp= int(e.start_time.strftime('%H%M%S'))
#se l'evento avviene fra meno di un ora chiamo la publish
if((temp-now) < 6000):
publish(pk,pk1)
return HttpResponseRedirect(reverse('cal:home'))
return render(request, 'cal/form.html', {'form': form})
In urls.py
:
path('homeProva1/<int:pk>/calendars/<int:pk1>/events/new/', views.addEvent, name='event_newprova1'),
In models.py
:
class Event(models.Model):
title = models.CharField(u'Title of the event', help_text=u'Title of the event', max_length=200, default='')
day = models.DateField(u'Day of the event', help_text=u'Day of the event')
start_time = models.TimeField(u'Starting time', help_text=u'Starting time')
end_time = models.TimeField(u'Final time', help_text=u'Final time')
notes = models.TextField(u'Textual Notes', help_text=u'Textual Notes', blank=True, null=True)
calendar = models.ForeignKey(Calendar, on_delete = models.CASCADE)
In forms.py
:
class EventForm(ModelForm):
class Meta:
model = Event
fields = ('title', 'day', 'start_time', 'end_time','notes',)
By combining the two
request.POST and form.is_valid()
you never render the validated form if it's invalid, so you never see the errors.You need to simplify the logic in that view and ensure that the form when it contains errors gets returned to the page with the errors intact;
Then in your template make sure you display the non-field-errors as well as the field errors;