我试图结合Django的通用UpdateView和隐藏的输入字段。我的目的是跟踪一个帖子是否被编辑后,它被创建或没有。隐藏字段名称为"updated">
views.py:
class PostUpdateView(UpdateView):
model = Post
template_name = 'journal/post_update_form.html'
form_class = PostUpdateForm
success_url = reverse_lazy('my_posts')
models.py:
class Post(models.Model):
title = models.CharField(max_length=500)
text = models.TextField(max_length=2000, null=True, blank=True)
owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
#storing the link to media files in CharField
image = models.CharField(max_length=500, null=True, blank=True)
audio = models.CharField(max_length=500, null=True, blank=True)
video = models.CharField(max_length=500, null=True, blank=True)
rubric = models.CharField(max_length=100, default="No rubric", choices=RUBRIC_CHOICES)
private = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
updated = models.CharField(max_length=10, default="False")
forms.py:
from django import forms
from .models import Post
class PostUpdateForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "text", "image", "audio", "video", "rubric", "private", "updated"]
widgets = {'updated': forms.HiddenInput(attrs={'value':"updated"})}
更新表单模板的相关部分:
<form action="" method="POST">
{% csrf_token %}
{% for field in form %}
{% if field != form.rubric and field != form.private %}
<div class="mb-3 form-group">
<label for="{{field.name}}" class="form-label">{{field.label}}</label>
{{field.errors}}
{% if field == form.text %}
<textarea type="text" class="form-control" id="{{field.name}}" name="{{field.name}}">{{field.value|default_if_none:"" }}</textarea>
{% elif field == form.updated %}
<input type="hidden" id="{{field.name}}" name="{{field.name}}" value="updated">
{% else %}
<input type="text" class="form-control" id="{{field.name}}" name="{{field.name}}" value="{{field.value|default_if_none:"" }}">
{% endif %}
</div>
<...some other fields...>
{% endif %}
{% endfor %}
<input type="submit" class="btn btn-primary" value="Update"/>
</form>
"updated"字段成功传递,但字段值是可见的(不可编辑)。在forms.py中,我试着:
- 从字段列表中排除'updated'。结果:"updated"的值。
- 使用widgets = {'updated': forms.HiddenInput}"结果:值也成功传递,但字段仍然可见。
- 只使用forms.py中的小部件,并注释掉模板中的输入字段[1]。结果:字段是可见的,可编辑的,值不保存。
[1]输入字段:
{% elif field == form.updated %}
<input type="hidden" id="{{field.name}}" name="{{field.name}}" value="updated">
我很感激任何关于这里可能有什么问题的见解。提前谢谢你。
在PostUpdateForm中可以这样做:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['updated'].initial = 'updated'
self.fields['updated'].disabled = True
https://docs.djangoproject.com/en/4.1/ref/forms/fields/禁用