如何从模板提交django ModelForm

时间:2015-04-22 03:22:06

标签: django django-models chat modelform

我正在尝试创建

的实例
class Message(models.Model):
    text        = models.TextField()
    created     = models.DateTimeField(auto_now_add=True)
    sender      = models.ForeignKey(User, related_name='messages_sent')
    receiver    = models.ForeignKey(User, related_name='messages_received')

当用户尝试向其他用户发送消息时我有一张表格

<form action="{% url 'chat:submit_message' viewed_user.username %}" method="post">
{% csrf_token %}
    <input type="text" name="message" id="message" value="" />
    <label for="message">Enter your message here</label><br />
<input type="submit" value="Send" />
</form>

并且“发件人”存储在“request.user”中,而“receiver”在

中作为“用户名”传送
url(r'^message/(?P<username>\w+)/$',        views.message

我试过

def send_message(request, username):
    """Add a new comment."""
    # p = request.POST
    print request
    message = Message()
    m = request.POST
    mf = MessageForm(m, instance=message)    
    text    = request.POST['message']
    sender  = User.objects.get(username=username)
    receiver= request.user
    mf.fields["text"] = text
    mf.fields["sender"] = sender
    mf.fields["receiver"] = receiver
    mf.save()

并得到了投诉

`AttributeError at /chat/message/[username]/submit/
'unicode' object has no attribute 'widget'`

如何在提交表单时创建消息?

1 个答案:

答案 0 :(得分:1)

以下是可行的代码:

from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['text']

@login_required
def send_message(request, username):
    if request.method == 'POST':
        message = Message(sender=request.user,
                          receiver=get_object_or_404(User, username=username))
        form = MessageForm(request.POST, instance=message)
        if form.is_valid():
            form.save()
        else:
            # handle the invalid form here if you want
    return redirect('some-view')

请注意,字段名称是text,而不是message,因此您需要使用有效的字段名称更新html表单。