2

我有一个包含四个字段的模型表单:消息、作者、房间和时间戳。时间戳设置为 auto_now,因此不会出现在表单中。Author 和 Room 都是外键,我希望它们自动填写在表单中,作者设置为 request.user 并且房间通过 url 传递给查看:/add_message/{{ room.id }}/'我希望客户填写的唯一字段是消息。这是迄今为止的观点,但我不确定如何实现这一目标:

@login_required(login_url="/login/")
def add_message(request, room_id):
    p = get_object_or_404(Room, pk=room_id)
    m = Message.objects.all().order_by('-timestamp')
    form = MessageForm(request.POST or None)
    if form.is_valid():
        cmodel = form.save()
        cmodel.save()
    return HttpResponseRedirect(reverse('chat.views.add_message', args=(p.id,)))

return render_to_response('chatroom.html', {'contact_form': form, 'room':p, 'latest_message_list': m}, context_instance=RequestContext(request))
4

1 回答 1

1

没有测试,但应该工作

表格.py

class MessageForm(forms.ModelForm):
    def __init__(self, **kwargs):
        self.room = kwargs.pop('room', None)
        self.author = kwargs.pop('author', None)
        super(MessageForm, self).__init__(**kwargs)

    def save(self, commit=True):
        obj = super(MessageForm, self).save(commit=False)
        obj.room = self.room
        obj.author = self.author
        if commit:
            obj.save()
        return obj

    class Meta:
        model = Message

视图.py

@login_required(login_url="/login/")
def add_message(request, room_id):
    room = get_object_or_404(Room, pk=room_id)
    form = MessageForm(room=room, author=request.user, data=request.POST)
    if form.is_valid():
        form.save()
    return HttpResponseRedirect(reverse('chat.views.add_message', args=(p.id,)))
于 2012-04-08T16:05:46.447 回答