尝试使用unique_together

时间:2015-05-15 21:35:50

标签: django django-forms django-class-based-views

使用基于类的视图CreateView时,如何显示完整性错误。

我当前的模型看起来像这样:

class Delivery(models.Model):
    created_date = models.DateTimeField('date created', editable=False)
    modified_date = models.DateTimeField('modified', editable=False)
    user_name = models.ForeignKey(User, null=False)
    stream_name = models.CharField(max_length=50, null=False)
    view_name = models.CharField(max_length=100, null=False, blank=True)
    activity_name = models.CharField(max_length=100, null=False, blank=True)
    jira = models.URLField()
    codereview = models.URLField()
    related_streams = models.CharField(max_length=100, choices=sorted(streams()),blank=True)
    description = models.TextField(null=False,blank=True)
    status = models.BooleanField(default=False, blank=False)

相应的观点是:

class CreateEntryView(CreateView):
    template_name = 'tracker/entry.html'
    model = Delivery
    success_url = reverse_lazy('table_view')
    status = StreamStatus()
    fields = ['stream_name','view_name','activity_name','jira','codereview','related_streams','description','status']

    def get_initial(self):
        if 'codereview-get' in self.request.GET:
            parsedDict = codereviewParser(self.request.GET['codereview-get'])
            return {'stream_name':parsedDict['stream'].split('_')[1:2][0],
                    'view_name':parsedDict['view'],
                    'activity_name':parsedDict['name'],
                    'jira':parsedDict['jira'],
                    'codereview':self.request.GET['codereview-get'],
                    'description':parsedDict['description'],
                    'status':parsedDict['status']}
        else:
            return self.initial.copy()

    def form_valid(self, form):
        form.instance.user_name = self.request.user
        try:
            return super(CreateEntryView, self).form_valid(form)
        except IntegrityError as e:
                messages.error(self.request, "Your data has not been saved!")
                return HttpResponseRedirect(self.request.path)
        return super(CreateEntryView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        ctx = super(CreateEntryView, self).get_context_data(**kwargs)
        ctx['locked'] = self.status.getLocked()
        ctx['unlocked'] = self.status.getUnlocked()
        return ctx

我通过将新上下文传递给render_to_response()来尝试了几种技术,但是我需要再次传递整个上下文。还尝试了HttpResponse(),我不喜欢它,因为它指示我到一个带有消息的空白页面。我想使用警告消息向用户显示错误。

1 个答案:

答案 0 :(得分:0)

如何做form_invalid做什么,但将您的信息添加到上下文中:

return self.render_to_response(self.get_context_data(form=form, integritymsg='Your data has not been saved!', reason=whatever))

当然,请检查并在模板中显示integritymsg/reason

有一件事不是很明显,传递给get_context_data的参数会被添加到上下文中。沿着MRO链调用的所有get_context_data都将它们添加到上下文中。

ccbv.co.uk是一个很棒的工具。不幸的是,您需要检查代码并自己查找执行流程。这并不复杂,但是,图表会有所帮助。 一般来说,从as_view,dispatch,get等开始......