1

我刚开始用 django 开发,我被卡住了......

我有我的models.py:

 from django.db import models
class Meeting(models.Model):
    title = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    latCoord = models.FloatField(default = 0.0)
    longCoord = models.FloatField(default = 0.0)

    def __unicode__(self):
        return self.title

class Location(models.Model):
    address = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')
    participants = models.IntegerField()
    latCoord = models.FloatField()
    longCoord = models.FloatField()
    meeting = models.ForeignKey(Meeting)

我的 urls.py:

from django.conf.urls import patterns, include, url
    urlpatterns = patterns('',
                       url(r'^(?P<meeting_id>\d+)/$', 'meeting.views.meeting'),
                       url(r'^add_location/(?P<meeting_id>\d+)/$', 'meeting.views.add_location'),
                       url(r'^create/$', 'meeting.views.create'),
                       )

和我的views.py:

from django.shortcuts import render_to_response
from meeting.models import Meeting, Location
from forms import MeetingForm, LocationForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.utils import timezone
from django.core import serializers
import math
import encodeUrl
def meeting(request, meeting_id = 1):
    l = Location.objects.filter(meeting_id = meeting_id)
    ...
    ...

    return render_to_response('meeting.html', 
                              {'meeting': Meeting.objects.get(id = meeting_id), 'data':data})

def create(request):
    print "test"
    if request.POST:
        form = MeetingForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/meetings/%s' % len(Meeting.objects.all()))
    else:
        form = MeetingForm()
    args = {}
    args.update(csrf(request))

    args['form'] = form
    return render_to_response('create_meeting.html', args)

到目前为止一切正常。每个新会议的 url 是 meeting/meeting_id。现在我希望 url 是一个字符串而不是一个数字。所以我改变了代码:

网址.py:

    from django.conf.urls import patterns, include, url
    urlpatterns = patterns('',
                           url(r'^(?P<meeting_id_str>\w+)/$', 'meeting.views.meeting'),
                           url(r'^add_location/(?P<meeting_id_str>\w+)/$', 'meeting.views.add_location'),
                           url(r'^create/$', 'meeting.views.create'),
                           )

和views.py

    def meeting(request, meeting_id_str = 'b'):
    #encode the string to an integer
    meeting_id = encodeUrl.alphaID(meeting_id_str, True)
    l = Location.objects.filter(meeting_id = meeting_id)
    ...
    ...
    ...    
    return render_to_response('meeting.html', 
                              {'meeting': Meeting.objects.get(id = meeting_id), 'data':data})

def create(request):
    print "test"
    if request.POST:
        form = MeetingForm(request.POST)
        if form.is_valid():
            form.save()
            meeting_id_str = encodeUrl.alphaID(len(Meeting.objects.all()), False)
            return HttpResponseRedirect('/meetings/%s' % meeting_id_str)
    else:
        form = MeetingForm()
    args = {}
    args.update(csrf(request))

    args['form'] = form
    return render_to_response('create_meeting.html', args)

编码有效,如果我调用一个 URL,例如 meeting/b,它会更改为 meeting/1,但是当我想创建一个新会议时,我得到“查询不存在”异常

 Request Method:    GET
Request URL:    http://127.0.0.1:8000/meetings/create/
Django Version:     1.5.1
Exception Type:     DoesNotExist
Exception Value:    

Meeting matching query does not exist. Lookup parameters were {'id': 3945298144L}

Exception Location:     C:\Python27\lib\site-packages\django\db\models\query.py in get, line 389
Python Executable:  C:\Python27\python.exe
Python Version:     2.7.5

感谢每一个提示,谢谢

4

2 回答 2

1

问题出在您创建视图的这些行中。

...
meeting_id_str = encodeUrl.alphaID(len(Meeting.objects.all()), False)
return HttpResponseRedirect('/meetings/%s' % meeting_id_str)

我认为您期望id创建的最后一个对象等于 DB 中的对象数,但这可能不是真的。

尝试将创建视图代码更新为

....
if request.POST:
    form = MeetingForm(request.POST)
    if form.is_valid():
        mobj = form.save()  #get object created using form
        meeting_id_str = encodeUrl.alphaID(mobj.id, False) #use its id
        return HttpResponseRedirect('/meetings/%s' % meeting_id_str)
else:
....
于 2013-11-08T13:39:47.460 回答
0

你永远不会进入create,因为第一个模式 - r'^(?P<meeting_id_str>\w+)/$'- 也匹配“create/”。您应该移动创建模式,使其位于列表的首位。

于 2013-11-08T14:37:51.473 回答