简体   繁体   English

如何设置模型属性的默认值?

[英]how to set a default value for a model's attribute?

I created a model and then model-form to take input from user. 我创建了一个模型,然后创建了模型表单以接受用户的输入。 I am trying to set the default value of the author to the active user's name, but instead, the default value is set to the username of admin. 我正在尝试将作者的默认值设置为活动用户的名称,但是,默认值设置为admin的用户名。 Please take a look at the code. 请看一下代码。

models.py models.py

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class tweets(models.Model):
    def curr_user():
        for user in User.objects.all():
            if user.is_active:
                return user.get_username
    z = curr_user()
    k = datetime.now
    author = models.CharField(max_length = 50,default=z)
    date_time = models.DateTimeField(default = k)
    body = models.TextField()

    def __str__(self):
        return self.body

forms.py forms.py

from django import forms
from .models import tweets

class TweetsForm(forms.ModelForm):

    class Meta():
            model = tweets
        fields = "__all__"

检查哪个用户已登录(我猜是管理员)以方便地检查它到“ localhost:8000 / admin”(仅在本地运行),然后注销并使用用户“ autor”登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM