如何使用表单在表格上插入数据?

时间:2018-01-29 10:08:51

标签: html django django-forms django-views

我想将消息发布到我的数据库中的消息表,其中包含以下字段:

  • ID
  • 体;
  • normaluser;

chat.html:

<form method="post" id="msg">
    <div class="form-group">
        <label for="comment">Message:</label>
        <textarea class="form-control" rows="5" id="comment"></textarea>
    </div>
    {% csrf_token %} {{ form.as_p }}
    <button type="submit">Enter</button>
</form>

views.py

@login_required
def msg(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        form.save()
        body = form.cleaned_data.get('body')
        raw_password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=raw_password)
        Message(request, user)
else:
    form = 'msg'
    args = {'form': form}
return render(request, 'accounts/chat.html', args)

class MessageListView(APIView):
def get(self, request): # lista objectos
    serializer = MessageSerializer(instance=Message.objects.all(), many=True)
    return Response(serializer.data)

def post(self, request): # cria objecto
    serializer = MessageSerializer(data=request.data, many=False)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

models.py

class Message(models.Model):
body = models.CharField(max_length=500)
normaluser = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.body

serializer.py

class MessageSerializer(serializers.ModelSerializer):
normaluser = MessageUserSerializer(many=False, read_only=True)
class Meta:
    model = Message
    fields = ('id', 'body', 'normaluser')

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ('id', 'username', 'email')

我的观点基于我用来创建新用户的def。但我不知道如何更改它以接受消息,它还接收在发送消息时经过身份验证的用户的信息。我正在使用django User表来创建用户并登录。

1 个答案:

答案 0 :(得分:0)

Django用户创建表单用于创建用户。您基本上想要自定义此项以添加额外的消息字段并将其另存为相关对象。你的表格应该是这样的(没有机会测试它):

class UserCreateWithMessageForm(UserCreationForm): 
    message = forms.TextField()

    def save(self, @args, **kwargs):
        user = super(UserCreateWithMessageForm, self).save()
        message_txt = self.cleaned_data['message']
        Message.objects.create(body=message_txt, normaluser=user)
        return user