python - CBV 通过 CBV 表单并进行验证
问题描述
我是 Django 的新手。
我正在使用基于类的视图构建一个 CRUD 应用程序,如下所示:
视图.py
class CreateInterventionView(CreateView):
form_class = NewIntervention
success_url = reverse_lazy('list')
template_name = 'intervention_create.html'
def form_valid(self, form):
form.instance.speaker = self.request.user
return super().form_valid(form)
class UpdateInterventionView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Intervention
form_class = NewIntervention
success_url = reverse_lazy('list')
template_name = 'intervention_update.html'
def form_valid(self, form):
form.instance.speaker = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.speaker:
return True
return False
class DeleteInterventionView(DeleteView):
model = Intervention
template_name = 'intervention_delete.html'
context_object = 'intervention'
success_url = reverse_lazy('list')
表格.py
class NewIntervention(forms.ModelForm):
class Meta:
model = Intervention
fields = ('subject', 'begin_date', 'end_date', 'description', 'campus')
widgets = {
'description': forms.Textarea(attrs={'class': 'materialize-textarea'}),
'begin_date': forms.DateInput(attrs={'class': 'datepicker'}),
'end_date': forms.DateInput(attrs={'class': 'datepicker'}),
}
def clean(self):
cleaned_data = super().clean()
begin_date = cleaned_data.get("begin_date")
end_date = cleaned_data.get("end_date")
if end_date < begin_date:
raise forms.ValidationError("End date should be greater than start date.")
我的 html 模态
<!-- Modal Trigger -->
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn modal-close waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
</div>
我还有一个 CBV ListView,我希望用户能够在与 ListView 相同的页面中创建/更新/删除干预(我有用于 crud 操作的按钮,当用户单击它时,它会打开带有表单的 materializecss 模式)
我试过这个:
class ListInterventionView(ListView):
model = Intervention
template_name = 'intervention_list.html'
ordering = ''
paginate_by = 5
def get_queryset(self):
return Intervention.objects.filter(speaker=self.request.user)
def get_context_data(self, **kwargs):
context = super(ListInterventionView, self).get_context_data(**kwargs)
context['form'] = CreateInterventionView.form_class
return context
模态正在工作,我在里面有我的表单,但是当我创建新的干预时它不起作用,我不知道如何在我的列表视图中进行验证。
欢迎任何建议。非常感谢。
最好的祝福。
解决方案
这里的问题是你没有在你的方法中返回:cleaned_data
clean
class NewIntervention(forms.ModelForm):
# ...
def clean(self):
cleaned_data = super().clean()
begin_date = cleaned_data.get("begin_date")
end_date = cleaned_data.get("end_date")
if end_date < begin_date:
raise forms.ValidationError("End date should be greater than start date.")
return cleaned_data
编辑
您还需要将action
您的属性连接form
到适当的url;因此,假设您有以下用于创建新Intervention
实例的 url:
...
path('intervention/new/', CreateInterventionView.as_view(), name='new-intervention'),
...
然后您需要将表单更改action
为:
<!-- Modal Trigger -->
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<form method="post" action="{% url 'new-intervention' %}">
{% csrf_token %}
{{ form.as_p }}
<button class="btn modal-close waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
</div>
推荐阅读
- python - 我的 if 和 elif 语句没有执行
- mysql - JPA - 没有名为 {{NAME_HERE}} 的 EntityManager 的持久性提供程序
- python - 远程触发不同网络上的计算机
- node.js - gulp-replace 不使用搜索字符串的完全匹配
- npm - 通过 https 而不是 http 启动 npm run
- unity3d - unity:碰撞检测太慢
- java - 常规 For 循环与增强型 For 循环
- c - 如果输入错误,我的函数应该包括什么来返回 -1.0 的值?
- django - Django中的ManyToMany字段约束
- reactjs - 部署时无法获取 kubectl 环境变量