如何将特定的自定义者传递给Django中的基于类的CreateView?

发布于 2025-01-19 20:43:40 字数 810 浏览 1 评论 0原文

完成教程后,我决定将基于功能的视图转换为基于类的视图,以便更好地学习两者。但是我很想将定制程序的字段传递到CreateView:

#model:
class CustomUser(AbstractUser):
    user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student"))
    user_type=models.CharField(default=1, choices=user_type_data, max_length=10)

class Staff(models.Model):
    id=models.AutoField(primary_key=True)
    admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    email=models.EmailField()
    address=models.TextField(blank=True)
    objects=models.Manager()

#view:
@method_decorator(csrf_exempt, name='dispatch')
class SubjectCreateView(CreateView):
    model = Subject
    fields = ['id', ... ]

我想将其放入fields =是:staff.first_namestaff.last_name,但我尝试过的所有组合都没有工作。这是我第一次与Customuser相遇,因此我的搜索并不富有成果。感谢一些指示。

After finishing a tutorial, I decided to convert the function-based views in the app to class-based views as a way to learn both better. But I got stumped with passing the fields of a CustomUser to the CreateView:

#model:
class CustomUser(AbstractUser):
    user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student"))
    user_type=models.CharField(default=1, choices=user_type_data, max_length=10)

class Staff(models.Model):
    id=models.AutoField(primary_key=True)
    admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    email=models.EmailField()
    address=models.TextField(blank=True)
    objects=models.Manager()

#view:
@method_decorator(csrf_exempt, name='dispatch')
class SubjectCreateView(CreateView):
    model = Subject
    fields = ['id', ... ]

What I want to put in the fields= are: staff.first_name, staff.last_name, but none of the combinations I tried worked. This is my first encounter with CustomUser, so my searches weren't fruitful. Appreciate some pointers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一曲琵琶半遮面シ 2025-01-26 20:43:41

我在下面发布的内容并不能解决我的 CreateView 问题,但如果您遇到类似的问题,这篇文章提供了 有关如何显示 ModelForms 中所有字段的提示之一 (fields = '__all__')。 此帖子提供了有关如何获取引用为foreignkey的对象的提示。

如果有人可以帮助解释如何使用 models.py 中未列出的字段为 CustomUser 设置 CreateView,但可能来自 AbstractUserBaseUser,我会接受它作为答案。

What I post below doesn't solve my problem with CreateView, but if you are similarly stuck, this post offers one of the tips on how to display all the fields in ModelForms (fields = '__all__'). And this thread offers tips on how to get objects referenced as ForeignKey.

If someone can help explain how to set up a CreateView for a CustomUser with fields that aren't listed in models.py-but maybe coming out of AbstractUser or BaseUser, I'll accept it as the answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文