【问题标题】:Problem with a request call Post in django在 django 中请求调用 Post 的问题
【发布时间】:2021-01-04 18:56:25
【问题描述】:

我正在调用POST 以在on_message() 函数中添加事件,在该步骤中是调用addEvent 函数(以添加事件)的URL,然后是具有我定义的值的有效负载(在mqtt_iot 文件中)。

编译器没有进入addEvent 函数,它锁定但没有出错(我正在使用终端)。 我附上代码。我该如何解决?

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)

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})

urls.py:

  path('homeProva1/<int:pk>/calendars/<int:pk1>/events/new/', views.addEvent, name='event_newprova1'),

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)

forms.py:

class EventForm(ModelForm):
    class Meta:
        model = Event
        fields = ('title', 'day', 'start_time', 'end_time','notes',)

【问题讨论】:

    标签: django django-models django-forms django-views django-request


    【解决方案1】:

    通过组合这两个request.POST and form.is_valid(),您永远不会呈现无效的验证表单,因此您永远不会看到错误。

    您需要简化该视图中的逻辑,并确保当表单包含错误时返回到页面并且错误完好无损;

    def addEvent(request, pk=None ,pk1=None):
        print("sono dentro add event")
        instance = Event()
        instance = Event(calendar_id=pk1)
        
        if request.method == "POST":
            form = EventForm(request.POST or None, instance=instance)
            if form.is_valid():
                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'))
        else:
            # GET request
            form = EventForm(instance=instance)
    
        # An invalid POST request still hits here, where form contains errors
        return render(request, 'cal/form.html', {'form': form})
    

    然后确保在您的模板中显示非字段错误以及字段错误;

    
    <form method="post" action=''>
        {% csrf_token %}
    
        {% if form.non_field_errors %}
            {{ form.non_field_errors }}
        {% endif %}
    
        {% for hidden in form.hidden_fields %}
            {{ hidden }}
        {% endfor %}
    
        {% for field in form.visible_fields %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }} {{ field }}
                {% if field.help_text %}
                    <p class="help">{{ field.help_text|safe }}</p>
                {% endif %}
            </div>
        {% endfor %}
    
        <button type="button" value="submit">Submit</button>
        <button type="button" value="cancel">Cancel</button>
    </form>
    

    【讨论】:

    • 感谢您的回答,但它不起作用,因为它甚至没有编译“addEvent()”函数中的 print("sono dentro add event")
    • @carciofinospinoso 你所说的“编译”是什么意思,因为 python 不是编译语言?您的意思是它没有在控制台中显示该打印吗?如果是这种情况,那么您在其他地方遇到了问题,因为视图从未被请求击中。
    猜你喜欢
    • 2017-07-13
    • 2018-09-02
    • 2014-03-22
    • 2021-11-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多