儘管表單,Django POST dict 為空 (Django POST dict empty despite form)


問題描述

儘管表單,Django POST dict 為空 (Django POST dict empty despite form)

Django 1.4.1。我有一個表單,它似乎在 html 中存在所有正確的值,但 POST dict 顯示為空。

views.py(相關部分):

@login_required
def event(request, event_id):

    event = Event.objects.get(pk=event_id)
    crew = event.userprofile_set.all()
    current_user = request.user.get_profile()
    if current_user in crew:
         current_user_is_not_crew = False
    elif request.user == event.host:
         current_user_is_not_crew = False    
    else:
         current_user_is_not_crew = True
    if event.date > datetime.now():
        future_event = True
    else:
        future_event = False
    context = RequestContext(request)
    context['event'] = event
    context['crew'] = crew
    context['current_user_is_not_crew'] = current_user_is_not_crew
    context['future_event'] = future_event
    return render_to_response('event.html', context)



def commit(request):
    """
    Commit user to event. Check if enough members
    (2 including event creator) are taking part to
    publish the event. If there are, mark
    sufficient_participants Boolean and publish the
    event to Facebook.

    clashing_commitment checks that request user is not
    already committed to an event on this day. If she is
    they will not be allowed to commit to this.
    """
    member = request.user.get_profile()
    event_id = request.POST.get('event_id','')
    print event_id
    event = Event.objects.get(pk=event_id)
    event_less_3_hours = event.date ‑ timedelta(hours=3)
    event_plus_3_hours = event.date + timedelta(hours=3)
    clashing_commitment = Event.objects.filter(userprofile__exact=member).\
        filter(date__range=(event_less_3_hours, event_plus_3_hours))    
    crew = event.userprofile_set.all()
    print crew
    context = RequestContext(request)
    if clashing_commitment:
        context['event'] = event
        context['crew'] = crew
        messages.add_message(request, messages.INFO, 
            'You are already committed to another event at this time. \
            You cannot commit to two simultaneous events. Sorry! \
            <a href="mailto:me@gmail.com">Ask admin</a> to remove you from other event if necessary.')
        return render_to_response('event.html', context)


    try:
        # cronix test page token:
        graph = GraphAPI("CAAk6zW7VBJL9eUZD")
        # Publish Facebook event on page
        eventdate = event.date
        date_iso = eventdate.isoformat()
        date_iso += '+0100'
        graph.post(
            path = '/449/events',
            retry=1,
            name = event.name,
            description = event.description,
            location = event.location,
            start_time = date_iso,
            )
        # To post event image, retrieve all Page events and identify current event
        # by its precise date in ISO format as captured above.
        # TODO This is a hacky, error‑prone means of identifying
        # events and needs to be fixed.
        fb_events = graph.get('/449/events')
        fb_events = fb_events['data']
        for item in fb_events:
            if item["start_time"] == date_iso:
                fb_event = item
        fb_event_id = fb_event.values()[0]
        fb_event_path = fb_event_id + '/picture'
        # Get appropriate, environment‑specific root url for urllib call below.
        # TODO Set two img_url variables and wrap urllib2.urlopen call
        # in try/except as it is error prone
        try:
            if os.environ['ENV'] == 'staging':
                img_url = 'http://www.mysite.org.uk//img/logo‑fb.jpg'
        except:
            img_url = 'http://localhost:8000/static/img/logo.png'
        print img_url
        graph.post(
            path = fb_event_path,
            source = urllib2.urlopen(img_url))


    except GraphAPI.OAuthError, e:
        print e.message
        return redirect('commit')
    member.event_commitments.add(event)
    crew = event.userprofile_set.all()
    if crew.count() > settings.EVENT_PUB_COMMITTED_CRITICAL_MASS and event.sufficient_participants == 0:
        event.sufficient_participants = 1
        event.save()
        publish_event = True
    context['event'] = event
    context['crew'] = crew
    messages.add_message(request, messages.SUCCESS, 'You have committed to this event.')
    return render_to_response('event.html', context)

urls.py(如評論者要求):

from crewcal.views import user, log_in
from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login, logout
from crewcal import models, views
from crewcal.forms import CustomRegistrationForm
# from crewcal.forms import RegistrationFormUniqueEmail


urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'crewcal.views.index', name='home'),
    # url(r'^ssc/', include('ssc.foo.urls')),

    url(r'^events/(?P<event_id>\d+)/$', 'crewcal.views.event', name='events'),
    url(r'^events/new/$', 'crewcal.views.new_event', name='new_event'),
    url(r'^commit/$', 'crewcal.views.commit', name='commit'),
    url(r'^users/(?P<user_name>[A‑Za‑z]+)/$', 'crewcal.views.user', name="user‑profile"),
    url(r'^users/(?P<user_name>\d+)/$', 'crewcal.views.user', name="user‑profile"),

    url(r'^', include('registration.backends.default.urls')),

    url(r'^register/$', 'RegistrationView',
    {'form_class':CustomRegistrationForm,
        'backend':'registration.backends.default.DefaultBackend' }, name='registration_register'),
#   For Registration simple, one‑step login
#    url(r'^', include('registration.backends.simple.urls')),

     url(r'^facebook/', include('django_facebook.urls')),
    # (r'^$', include('django_facebook.auth_urls')),


    url(r'^messages/', include('postman.urls')),


    # url(r'^event/$', views.object_list, {'model': models.Event}),

    url(r'^accounts/', include('registration.urls')),

    # url(r'^register/$', register, name='join'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
    url(r'^logout/$', logout, {'next_page': '/'}, name='logout'),
    url(r'^log_in/$', log_in, name='log_in'),

這是頁面中呈現的表單:

<p>
<form action="/commit/" method="post" id="event‑commit">
<input type="hidden" name="event_id" id="event_id" value="4">
<input type="submit" value="Commit to this event &raquo;" class="btn")">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='XXOqtkkxYQ0zAN1sv3KYxVD8ljhjMpit' /></div>
</form>
</p>

但是由於 POST 字典中存在 event_id(或其他任何內容),因此分頁符:

Exception Type: ValueError
Exception Value:    
invalid literal for int() with base 10: ''

...

request 
"<WSGIRequest\npath:/commit/,\nGET:<QueryDict: {}>,\nPOST:<QueryDict: {}>,\nCOOKIES:

...

這發生在我的 Heroku 暫存環境中,但不是在本地。有任何想法嗎?謝謝。


參考解法

方法 1:

Hmm maybe this line caused the error:

event_id = request.POST.get('event_id','')
event = Event.objects.get(pk=event_id)

You need to pass int instead of string to pk, so change it to something like:

event_id = request.POST.get('event_id', 0)
event = Event.objects.get(pk=int(event_id))

EDIT:

You also have this part of code:

except GraphAPI.OAuthError, e:
    print e.message
    return redirect('commit')

So if there is an exception, it's automatically redirect to this same view with an empty querydict. I think that could be the source of the problem, could you remove that redirection and try again?

(by KindOfGuyHieu Nguyen)

參考文件

  1. Django POST dict empty despite form (CC BY‑SA 2.5/3.0/4.0)

#post #Dictionary #Django #Heroku






相關問題

將 xml 從經典 asp 發佈到 asp.net (Posting xml from classic asp to asp.net)

POST 和 PUT HTTP 請求有什麼區別? (What's the difference between a POST and a PUT HTTP REQUEST?)

使用 formdata 發布數組 (Posting array using formdata)

儘管表單,Django POST dict 為空 (Django POST dict empty despite form)

表單提交為空 (Form submission empty)

ajax post 只看到第一個參數 (ajax post only sees first param)

使用 PHP 變量搜索 SQL 數據庫 (Use PHP variable to search through SQL database)

表單不通過 Post 發送數據 (Form not sending data through Post)

在 PHP 中使用 cURL 的 RAW POST (RAW POST using cURL in PHP)

使用 php 和 curl 更新 mediawiki (using php and curl to update mediawiki)

在 python 中開發時,如何在 post 請求中使用“format=json&data=”? (How do I use "format=json&data=" in post requests when developing in python?)

Nodejs GET 和 POST 在實時服務器中混合,但在 localhost 中工作 (Nodejs GET and POST mixed up in live server but working in localhost)







留言討論