将新数据发布到Web服务器后出错

时间:2018-01-28 12:24:48

标签: python django django-forms

当我尝试在我的主题中添加一些帖子时,我发现错误created_by = user

enter image description here

这是我的forms.py

from django import forms
from .models import Topic


class NewTopicForm(forms.ModelForm):
    message = forms.CharField(
        widget=forms.Textarea(
            attrs={'rows': 5, 'placeholder': 'What is on your mind?'}
        ),
        max_length=40000,
        help_text='The max length of the text is 4000.')

    class Meta:
        model = Topic
        fields = ['subject', 'message']

以及我对此表单的查看功能:

def new_topic(request, pk):
board = get_object_or_404(Board, pk=pk)
user = User.objects.first()

if request.method == 'POST':
    form = NewTopicForm(request.POST)
    if form.is_valid():
        topic = form.save(commit=False)
        topic.board = board
        topic.starter = user
        topic.save()
        post = Post.objects.create(
            message=form.cleaned_data.get('message'),
            topic=topic,
            created_by=user
        )

        return redirect('board_topics', pk=board.pk)
else:
    form = NewTopicForm()
return render(request, 'new_topic.html', {'board': board, 'form': form})

models.py

class Post(models.Model):
    message = models.TextField(max_length=4000)
    topic = models.ForeignKey(Topic, related_name='t_posts', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(null=True)
    created_by = models.ForeignKey(Topic, related_name='posts', on_delete=models.CASCADE)
    updated_by = models.ForeignKey(User, related_name='+', null=True, on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:0)

你的Post模型中有一个错误

created_by需要是User表的外键

created_by = models.ForeignKey(User, related_name='created_by', on_delete=models.CASCADE)

在上述更改后运行以下命令以反映数据库中的更改

python manage.py makemigrations
python manage.py migrate