2

ジャンゴ 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>

しかし、event_id (またはその他のもの) が POST ディクショナリに存在するため、結果として改ページが発生します。

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

...

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

...

これは、Heroku ステージング環境で発生していますが、ローカルでは発生していません。何か案は?ありがとう。

4

1 に答える 1

1

うーん、おそらくこの行がエラーを引き起こしました:

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

intpkの代わりに渡す必要があるstringため、次のように変更します。

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

編集:

コードの次の部分もあります。

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

したがって、例外が発生した場合は、空の querydict を使用してこの同じビューに自動的にリダイレクトされます。それが問題の原因である可能性があると思います。そのリダイレクトを削除して、もう一度試していただけますか?

于 2013-07-20T13:24:15.123 に答える