简体   繁体   English

CreateView 不保存 object,抛出 'this field is required' 错误

[英]CreateView doesn't save object , throws 'this field is required ' error

models.py is:模型.py 是:

class Todo(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True)
title=models.CharField(max_length=200)
desc=models.TextField(null=True,blank=True)
complete=models.BooleanField(default=False)
created=models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.title

class Meta:
ordering = ['created']

views.py is: view.py 是:

class TaskCreate(generic.CreateView):
model = Todo
fields = '__all__'
template_name = 'create.html'
success_url = reverse_lazy('home')

create.html is: create.html 是:

<body>
<a href="{% url 'home' %}">go back</a>
{{ form.as_p }}
<form method="post">
{% csrf_token %}
<input type="submit" value="submit">
</form>
</body>

Whenever I submit data from create.html form it doesn't save it to the database and throws this field is required on 'user' field.每当我从 create.html 表单提交数据时,它不会将其保存到数据库并在“用户”字段中抛出此字段是必需的。 How do I resolve this?我该如何解决这个问题?

You probably want to exclude the user field, since it is determined by the logged in user, so:您可能想要排除user字段,因为它是由登录用户确定的,所以:

from django.conf import settings


class Todo(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False
    )
    # …

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['created']

Then we inject the logged in user in the instance of the form:然后我们将登录的用户注入到表单的实例中:

from django.contrib.auth.mixins import LoginRequiredMixin


class TaskCreateView(LoginRequiredMixin, generic.CreateView):
    model = Todo
    fields = '__all__'
    template_name = 'create.html'
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        form.instance.user = request.user
        return super().form_valid(form)

Note : It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly.注意:通常最好使用settings.AUTH_USER_MODEL [Django-doc]来引用用户 model,而不是直接使用User模型[Django-doc] For more information you can see the referencing the User model section of the documentation .有关更多信息,您可以查看参考文档的User model部分


Note : You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc] .注意:您可以使用LoginRequiredMixin mixin [Django-doc]将视图限制为基于类的视图,以供经过身份验证的用户使用。


Note : In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names.注意:在 Django 中,基于类的视图 (CBV) 通常有一个…View后缀,以避免与 model 名称发生冲突。 Therefore you might consider renaming the view class to TaskCreateView , instead of TaskCreate .因此,您可以考虑将视图 class 重命名为TaskCreateView ,而不是TaskCreate

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

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