【问题标题】:CBV pass CBV form with validationCBV 通过 CBV 表单并进行验证
【发布时间】:2019-12-15 17:24:35
【问题描述】:

我是 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 相同的页面中创建/更新/删除干预(我有用于 crud 操作的按钮,当用户单击它时,它会打开一个带有表格)

我试过了:

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

模态正在工作,我在其中有我的表单,但是当我创建新干预时它不起作用,我不知道如何在我的列表视图中进行验证。

欢迎任何建议。 非常感谢。

最好的问候。

【问题讨论】:

  • 欢迎来到 SO。你说它不起作用是什么意思?验证失败了吗?有没有错误?同时向我们展示您的NewIntervention 表单以及添加新Intervention 的模式。
  • 没有错误,当我提交表单时,管理员/数据库中没有任何内容

标签: python django forms materialize


【解决方案1】:

这里的问题是您没有在您的clean 方法中返回 cleaned_data

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

编辑

您还需要将formaction 属性连接到相应的url;因此,假设您有以下 url 用于创建新的 Intervention 实例:

...
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>

【讨论】:

  • 我仍然被模式中的删除/更新所困扰。对于删除,我通过 pk 像这样删除 url
    {% csrf_token %}
    它删除但不是正确的项目。你有什么主意吗?为了更新,我得到了我的表格,但它没有填满对象的日期
  • @cameleon 请编辑您的问题并将代码放在那里。是否出现任何错误?
猜你喜欢
  • 2017-07-06
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 2012-10-12
  • 2015-11-27
  • 1970-01-01
相关资源
最近更新 更多