validation - django validationerror not being raised -
so have created a dynamic formset allows user add or remove many forms want. now, trying custom validation in field(block_name) in forms.
it seems working because if user input doesn't match regex, data not saved. problem there no message showing input wrong.
also, if user inputs incorrect data , tries submit page redirect , erase input data. how can make page stay in same view if input wrong , show error messages?
forms.py:
import re django import forms django.forms.models import modelformset_factory inventory.models import block django.core.exceptions import validationerror django.core.validators import regexvalidator # form block requests class blockform(forms.modelform): block_name = forms.charfield(required=true, validators= [regexvalidator('^s\d{3}rf\d*b\d*e\d+r\d+w\d*[cgls][abcdex][ed][hv][sbaec][a-d] [a-d][0-7][apfg]a', message="please enter valid block name", code="invalid_name")]) def __init__(self, *args, **kwargs): super(blockform, self).__init__(*args, **kwargs) self.empty_permitted = false class meta: model = block fields = ['block_name', 'block_derivatives', 'block_subsystems', 'owners'] def clean_block_name(self): print self.cleaned_data block_name = self.cleaned_data.get('block_name') if block_name == "a": print ("block name a") raise forms.validationerror( ('please enter block name')) return block_name
models.py:
import datetime import re django.core.validators import regexvalidator django.core.exceptions import validationerror django.db import models django.utils import timezone class inventory(models.model): class meta: verbose_name_plural = "inventories" inventory_name = models.charfield(max_length=100) pub_date = models.datetimefield('date published') def __str__(self): # __unicode__ on python 2 return self.inventory_name def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class block(models.model): class meta: verbose_name_plural = "request blocks" inventory = models.foreignkey(inventory, null=true) block_status = models.charfield(max_length=20, blank=false) #617block_name = models.charfield(max_length=50, blank=false, null=false, validators=[block_nametest]) block_name = models.charfield(max_length=50, blank=false, null=false) block_derivatives = models.charfield(max_length=100) block_subsystems = models.charfield(max_length=40) owners = models.charfield(max_length=100) def __str__(self): return self.block_name def block_owners(self): return str(self.owners)
views.py:
from django.forms.models import modelformset_factory django.forms.formsets import formset_factory django.shortcuts import render, get_object_or_404 django.http import httpresponseredirect django.core.urlresolvers import reverse django.views import generic django.http import httpresponse django.shortcuts import render_to_response .models import inventory, block .forms import blockform # create views here. def requests(request, inventory_id): blockformset = formset_factory(blockform, extra=1) inventory = get_object_or_404(inventory, pk=inventory_id) formset = blockformset(request.post) if request.method == 'post': formset = blockformset(request.post) if formset.is_valid(): form in formset: print form form.save() print "success" return httpresponseredirect('/inventory/2') else: print "yo, stuff not validated" else: print "lolololol" return render(request, 'inventory/requests.html', {'inventory': inventory, 'formset': blockformset})
requests.html:
{% block content %} <div class="requestform"> <form id="blockform" class="original" action="{% url 'inventory:requests' inventory.id %}" method="post">{% csrf_token %} <!-- <a href="#" id="insert-more"> add new row </a> --> {{formset.management_form}} {% form in formset %} <div class='item'> <ul>{{ form.as_table}}<ul> <p style=""><a class="delete" href="#">delete</a></p> </div> {% endfor %} <p><a id="add" href="#">add item</a></p> <input type="submit" name="submit" value="request blocks" id="submitbutton"> </form> </div> {% endblock %}
you're redirecting after invalid post, rather redisplaying same form. though redirect same view, loses post data , form therefore blank.
drop first else
block, , let execution fall through final render
line.
Comments
Post a Comment