我是django的新手。
我正在使用基于类的视图构建CRUD应用程序,如下所示:
views.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')
forms.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相同的页面上创建/更新/删除干预(我有用于执行粗操作的按钮,当用户单击它时,它将使用形式)
我尝试过:
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
该模式正在运行,并且我在其中具有表单,但是当我创建新干预时,它不起作用,并且我不知道如何在列表视图中进行验证。
欢迎任何建议。 非常感谢。
最诚挚的问候。
答案 0 :(得分:0)
这里的问题是您没有返回您的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
的{{1}}属性连接到适当的 url ;因此,假设您使用以下网址来创建新的form
实例:
Intervention
然后,您需要将表单的...
path('intervention/new/', CreateInterventionView.as_view(), name='new-intervention'),
...
更改为:
action