带有基数10的int()的无效文字:使用foreignkey时

时间:2017-01-29 21:15:11

标签: python django

我正在尝试与频道建立私聊,我在将用户名传递给网址时遇到问题。

  

对于带有基数10的int()的无效文字:'username'

可能会发生此错误,因为我使用的是ForeignKey,因为使用ChatField一切运行良好,我想知道如何解决此问题。

models.py:

class Room(models.Model):
    gig = models.ForeignKey(Gig, null=True)
    creator = models.ForeignKey(User, related_name='creator', null=True)

views.py

def new_room(request):
    try:
        #get the submited product object
        gig = Gig.objects.get(id=request.POST.get('inGig_id'))
    except Gig.DoesNotExist:
        return redirect('/')

    creator = request.user
    Room.objects.get_or_create(gig=gig, creator=creator)
    return redirect(commenting_room, gig=gig.id, creator=creator)


def commenting_room(request, gig, creator):
    room = Room.objects.get(gig=gig, creator=creator) #error occurs here
    ...

urls.py

url(r'^room/(?P<gig>\d+)/(?P<creator>\w+)/$', views.commenting_room, name='commenting_room_detail'),

有关如何解决此问题的任何建议?

1 个答案:

答案 0 :(得分:1)

您应该将创建者ID传递给.get而不是通过网址传递的用户名文字,因为creatorRoom中的ForeignKey字段:

def commenting_room(request, gig, creator):
    creator_id = User.objects.get(username=creator).id
    room = Room.objects.get(gig=gig, creator=creator_id)