将用户first_name保存为django模型的默认值 [英] Save user first_name as default value for model django

查看:104
本文介绍了将用户first_name保存为django模型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有author变量的文章模型,我想另存为用户的名字和姓氏.我使用名为Account的自定义用户模型.

I have an article model with author variable which I want to save as the users first and last name. I use custom user model called Account.

author = models.CharField('author',max_length=50 default=User.first_name)

保存后显示作者为<django.db.models.query_utils.DeferredAttribute object at 0x10b461dc0>,那么保存此表单时如何检索帐户的名字:

When saved it shows the author is <django.db.models.query_utils.DeferredAttribute object at 0x10b461dc0> So how can I retrieve the account first name when saving this form:

form = ArticleCreationForm(request.POST) 
        # check if form data is valid 
        if request.method == "POST":
            if form.is_valid(): 
                form.save() 
            # save the form data to model 
    
        context['form']= form 

forms.py:

class ArticleCreationForm(forms.ModelForm): 
    # specify the name of model to use 
    class Meta: 
        model = Article 
        fields = "__all__"
        exclude = ['votes', 'author']

如果可以的话,最好让用户看到带有其姓名的author字段,但不能对其进行编辑.

It would be good if you can make it so that the user sees the author field with his name but can't edit it.

推荐答案

您需要在CharField中提供类似这样的默认值.

You need to provide some default value like this in CharField.

author = models.CharField('author',max_length=50, default='First Name')

在保存表单时,您可以像这样在用户字段中保存用户(当前用户)的名字.

You can save the user(current user) first name in your author field like this while saving the form.

if request.method == "POST":      
    form = ArticleCreationForm(request.POST) 
    if form.is_valid(): 
        article = form.save(commit=False) 
        article.author = request.user.first_name # the user must be logged in for this.
        article.save()
        return redirect('some_path')

这篇关于将用户first_name保存为django模型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆