Django 1.3 CreateView/ModelForm: unique_together validation with one field excluded from form

孤者浪人 提交于 2019-12-04 14:05:55

Yehonatan's example got me there, but I had to call the messages from within the ValidationError of form_valid, rather than a separate form_invalid function.

This works:

class SubscriberCreateView(AuthCreateView):
    model = Subscriber
    template_name = "forms/app.html"
    form_class = SubscriberForm
    success_url = "/app/subscribers/"

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user

        try:
            self.object.full_clean()
        except ValidationError:
            #raise ValidationError("No can do, you have used this name before!")
            #return self.form_invalid(form)
            from django.forms.util import ErrorList
            form._errors["email"] = ErrorList([u"You already have an email with that name man."])
            return super(SubscriberCreateView, self).form_invalid(form)

        return super(SubscriberCreateView, self).form_valid(form) 
ydaniv

Taking from the docs at: https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#validating-objects

You should only need to call a model’s full_clean() method if you plan to handle validation errors yourself, or if you have excluded fields from the ModelForm that require validation.

Taking from the docs at: https://docs.djangoproject.com/en/dev/ref/class-based-views/#formmixin

Views mixing FormMixin must provide an implementation of form_valid() and form_invalid().

This means that in order to view the error (which isn't form related) you'll need to implement your own form_invalid, add the special error message there, and return it.

So, running a full_clean() on your object should raise the unique_together error, so your code could look like this:

def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object.user = self.request.user
    # validate unique_together constraint
    try:
        self.object.full_clean()
    except ValidationError:
        # here you can return the same view with error messages
        # e.g.
        return self.form_invalid(form)
    return super(SubscriberListCreateView, self).form_valid(form)

def form_invalid(self, form):
    # using messages
    # from django.contrib import messages
    # messages.error('You already have a list with that name')
    # or adding a custom error
    from django.forms.util import ErrorList
    form._errors["name"] = ErrorList([u"You already have a list with that name"])
    return super(SubscriberListCreateView, self).form_invalid(form)

HTH

adding another example that might be a bit easier for noobs.

forms.py

class GroupItemForm(ModelForm):
    def form_valid(self):
        self.object = self.save(commit=False)
        try:
            self.object.full_clean()
        except ValidationError:
            # here you can return the same view with error messages
            # e.g. field level error or...
            self._errors["sku"] = self.error_class([u"You already have an email with that name."])
            # ... form level error
            self.errors['__all__'] = self.error_class(["error msg"]
            return False
        return True

views.py

def add_stock_item_detail(request, item_id, form_class=GroupItemForm, template_name="myapp/mytemplate.html"):
    item = get_object_or_404(Item, pk=item_id)
    product = Product(item=item)
    if request.method == 'POST':
        form = form_class(request.POST, instance=product)
        if form.is_valid() and form.form_valid():
            form.save()
            return HttpResponseRedirect('someurl')
    else:
        form = form_class(instance=product)

    ctx.update({
        "form" : form,
     })

    return render_to_response(template_name, RequestContext(request, ctx))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!