Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Users(models.Model):
- alpha_field = RegexValidator(regex=r'^[a-zA-Z]+$', message='Name can only contain letters')
- user_id = models.AutoField(unique=True, primary_key=True)
- username = models.SlugField(max_length=50, unique=True)
- first_name = models.CharField(max_length=50, verbose_name='first Name', validators=[alpha_field])
- last_name = models.CharField(max_length=50, validators=[alpha_field])
- password = models.SlugField(max_length=50)
- {% for field, error in form.errors.items %}
- {% if forloop.counter == 1 %}
- {{ field }}{{ error | striptags }}
- {% endif %}
- {% endfor %}
- from django import forms
- from models import Users
- class UsersForm(forms.ModelForm):
- class Meta:
- model = Users
- widgets = {'password':forms.PasswordInput()}
- def __init__(self, *args, **kwargs):
- super( UsersForm, self ).__init__(*args, **kwargs)
- self.fields[ 'username' ].widget.attrs[ 'placeholder' ]="Username"
- self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"
- self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
- self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"
- self.fields['first_name'].label='first Name'
- def home_page(request):
- form = UsersForm()
- if request.method == "POST":
- form = UsersForm(request.POST)
- if form.is_valid():
- form.save()
- c = {}
- c.update(csrf(request))
- c.update({'form':form})
- return render_to_response('home_page.html', c)
- {% load getattribute %}
- {% for field, error in form.errors.items %}
- {% if forloop.counter == 1 %}
- {% with field_obj=form|getattribute:field %}
- {{ field_obj.label }}{{ error | striptags }}
- {% endwith %}
- {% endif %}
- {% endfor %}
- from django import template
- from django import forms
- from django.forms.forms import NON_FIELD_ERRORS
- from django.forms.util import ErrorDict
- register = template.Library()
- @register.filter
- def nice_errors(form, non_field_msg='General form errors'):
- nice_errors = ErrorDict()
- if isinstance(form, forms.BaseForm):
- for field, errors in form.errors.items():
- if field == NON_FIELD_ERRORS:
- key = non_field_msg
- else:
- key = form.fields[field].label
- nice_errors[key] = errors
- return nice_errors
Add Comment
Please, Sign In to add comment