python - 如何修复 limit_choices_to 不能成为 Django 中的外键?

标签 python django

我有一段代码如下:

模型.py
class Notebook(models.Model):
    owner = models.ForeignKey(User, on_delete = models.CASCADE)
    name= models.CharField(max_length=50)

class Note(models.Model):
    create_user = models.ForeignKey(User, on_delete = models.CASCADE)
    text=models.CharField(max_length=500)
    notebook=models.ForeignKey(Notebook, on_delete = models.CASCADE, limit_choices_to = {'owner' : create_user})
<小时/>

但我收到一条错误,指出 limit_users_to 不能是外键。 我希望用户在编写笔记时仅选择他们创建的笔记本,但现在用户可以在未设置 limit_choices_to 的情况下选择其他笔记本。 并且笔记本必须是ForeignKey。 我能做什么?

最佳答案

创建注释时必须在 View 中执行此操作

表单.py

from .models import Note
from django.forms import ModelForm

class NoteForm(ModelForm):
    class Meta:
       model = Note

查看.py

from django.views.generic.edit import CreateView
from .form import NoteForm
from .models import Note, Notebook

class NoteCreateView(CreateView):
    model=Note
    form_class=NoteForm

    def get_form(self, form_class=None):
        form = super(NoteCreateView, self).get_form(form_class)
        # Thats the solution:
        form.fields['notebook'].queryset = Notebook.objects.filter(owner=self.request.user)
        return form

关于python - 如何修复 limit_choices_to 不能成为 Django 中的外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861946/

相关文章:

django - 该 View 没有返回 HttpResponse 对象。它返回 None 相反

python - 类型错误 : 'unicode' object is not callable

python - django登录到上一页

python - 克服 Python 2.3 中的 os.system() 限制

python - Django - 默认字段值取决于其他字段值

javascript - 使用单选按钮以订单形式动态增加/减少总价

django - 如何自动将 slug 添加到 URL 中?

python - 为 Mac django-admin 启动 Python 3 的 Django 不工作

python - pandas groupby 列并检查组是否满足多个条件

c++ - 内置mpi的自定义boost python模块?