Skip to content

Instantly share code, notes, and snippets.

@gkrnours
Created September 17, 2016 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkrnours/6461781883e6add258d6a70ea1804b0f to your computer and use it in GitHub Desktop.
Save gkrnours/6461781883e6add258d6a70ea1804b0f to your computer and use it in GitHub Desktop.
A user creation form in django
{#
mySite is the directory created with manage.py startproject, containing settings.py
This template simple take a form and output a basic bootstrap4 compatible html
Could be replaced with {{ form.as_p }}
#}
{% load widget_tweaks %}
{% for field in form %}
<fieldset class="form-group{% if field.errors %} has-error{% endif %}">
{{ field.label_tag }}
{{ field|add_class:"form-control" }}
{% if field.errors %}
<p class="m-x m-y-0 form-control-feedback">
{% for e in field.errors %} <small>{{ e }}</small><br>
{% endfor %} </p>{% endif %}
{% if field.help_text %}
<div class="form-text text-muted">
{{ field.help_text|safe }}
</div>{% endif %}
</fieldset>
{% endfor %}
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django import forms
class NewAccountForm(forms.ModelForm):
confirm_password = forms.CharField(widget=forms.PasswordInput())
def clean_password(self):
pwd = self.cleaned_data.get('password')
if not pwd:
raise forms.ValidationError("You must enter a password")
validate_password(pwd)
return pwd
def clean_confirm_password(self):
pwd1 = self.cleaned_data.get('password')
pwd2 = self.cleaned_data.get('confirm_password')
if not pwd2:
raise forms.ValidationError("You must confirm your password")
if pwd1 != pwd2:
raise forms.ValidationError("Your passwords do not match")
return pwd2
class Meta:
model = User
fields = ['username', 'email', 'password']
widgets = {
'password': forms.PasswordInput,
'password_confirm': forms.PasswordInput
}
{% extends 'user/base.html' %}
{% block main %}
<form method=post>
{% csrf_token %}
{% include "form.html" %}
<fieldset class="form-group">
<button class="btn btn-primary">Create</button>
</fieldset>
</form>
{% endblock %}
from django.conf import settings
from django.urls import reverse_lazy as reverse
from django.views.generic.edit import CreateView
from user.forms import NewAccountForm
class UserCreate(CreateView):
template_name = "user/create_form.html"
form_class = NewAccountForm
success_url = reverse(settings.LOGIN_REDIRECT_URL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment