Django:仅将表单字段渲染为可编辑文本字段一次,然后将其渲染为只读
我有典型的个人资料/帐户设置表格。因此,正如预期的那样,您将有一个“名称”字段和一个“域”字段(将用作网站网址:maddy.mywebsite.com)。该域字段只需可编辑一次。一旦设置为一件事,以后将无法编辑(因为这就像网站网址)。
在模型级别,我正在比较该对象(用户配置文件)的created_on和modified_on并验证“域”值保存。但在表单级别,如何根据我所采取的条件单独定制该字段的呈现?
注 1:我不想将“域”字段移至注册页面。
注 2:我尝试使用普通表单(django.forms)而不是 ModelForm。
I have typical profile/account settings form. So as expected you would be having a "name" field and a "domain" field(which will be used as like a website url: maddy.mywebsite.com). This domain field needs to be editable only once. Once set to one thing, will not be made editable later(since this is like a site url).
At the model level, I am comparing created_on and modified_on of that object(userprofile) and validating "domain" value saving. But at the form level, how do I customize the rendering of that field alone based on the condition I have taken ?
Note 1: I don't want to move the "domain" field to the signup page.
Note 2: I am trying to use normal forms(django.forms) and not a ModelForm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试使用两个 html,一个用于创建配置文件,一个用于编辑配置文件。在创建配置文件和编辑配置文件中呈现完整的表单,如果您使用相同的 django,则可以使用 css 或 javascript 禁用 #id_name 和 #id_domain 归档。使用js实现:
You may try using two htmls, One for create profile and one for editing profile. Render the complete form in create profile and for editing profile if you use same django you may disable the #id_name and #id_domain filed by using either css or javascript. An implementation using js:
这看起来很棘手,您可以阅读以下一些内容以获得一些想法:
在 Django 表单中,如何使字段只读(或禁用)以便它无法编辑?
http://lazypython.blogspot.com/2008/12/building-read-only-field-in-django.html
不过,这些都不是特别简单,所以我建议(@dcrodjer 也是如此) :
创建两种表单,一种用于创建,一种用于编辑。在编辑表单上,删除“域”字段,以便不需要/不会保存它:
在您的视图中,创建适当的表单,并在模板中,根据给定的表单呈现不同的 HTML:
This looks tricky, you can read some of the following for some ideas:
In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
http://lazypython.blogspot.com/2008/12/building-read-only-field-in-django.html
None of those are particularly simple though, so I'd suggest (as did @dcrodjer):
Creating two forms, one for creating, one for editing. On the editing form, remove the Domain field so it's not required/won't be saved:
In your view, creating the appropriate form, and in your template, rendering different HTML depending on which form you've been given: