无法在Django表单提交中将值插入数据库

时间:2019-10-04 07:35:35

标签: django django-forms

我创建了一个表单,该表单接受来自用户的2个输入,并且当我在POST方法中收到用户输入时,我想添加当前日期时间和当前登录的用户。

帮我写一个视图来编辑表单。在下面的代码中,我无法为blog_author赋值。

models.py(我接受用户的blog_name和blog_details)

class blogs(models.Model):
    blog_name = models.CharField(max_length=100,blank=False,null=False)
    blog_details = models.TextField(blank=False,null=False)
    blog_author = models.CharField(max_length=100,blank=True,null=True)
    blog_created_at = models.DateTimeField(auto_now=True)

forms.py#仅包含两个字段

class blogForm(forms.ModelForm):
    class Meta:
        model = blogs
        fields = ('blog_name','blog_details')

views.py#表单验证

def create_blog(request):
    if request.method == 'POST':
        form = blogForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            form.cleaned_data['blog_author'] = request.user
            form.save()   
    form = blogForm()
    context = {"form":form}
    return render(request,'create_blog.html',context)

1 个答案:

答案 0 :(得分:1)

您的错误在此行:

form.cleaned_data['blog_author'] = request.user返回一个User对象。

但是

blog_author = models.CharField(max_length=100,blank=True,null=True)

CharField

如果要保存blog_author实例,则必须将User更改为ForeignKey,或者必须将request.user替换为request.user.username,这将返回用户名字符串可以进入您的CharField的用户数量。

带有request.user.username option的完整代码:

def create_blog(request):
    if request.method == 'POST':
        form = blogForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            form.cleaned_data['blog_author'] = request.user.username
            form.save()   
    form = blogForm()
    context = {"form":form}
    return render(request,'create_blog.html',context)

基于聊天进行编辑

def create_blog(request):
    if request.method == 'POST':
        form = blogForm(request.POST)
        if form.is_valid():
            blog = form.save()
            blog.refresh_from_db()
            blog.blog_author= request.user.get_username()
            blog.save()   
    form = blogForm()
    context = {"form":form}
    return render(request,'create_blog.html',context)