I'm making a blog type website, and it's pretty much done but earlier today I realized a major flaw in it. When creating creating a username (when registering or editing one's profile) it asks for certain characters, but it won't allow me to have spaces in my name.
For example if I wanted my username to be "Winston Pichardo", it won't be possible because that will trigger the error that says "only letters and digits as @/./ /-/_ are allowed".
So how can I edit these 'requirements' to allow spaces in the username?
I'm using the default django forms and combining those with Crispy Forms to make it all work.
these are some examples of my code:
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(
label= 'Correo Electrónico',
required=True,
)
username = forms.CharField(
label = 'Nombre de Usuario',
required=True,
)
password1 = forms.CharField(
label = "Contraseña",
required=True
)
password2 = forms.CharField(
label = "Confirmar Contraseña",
required=True
)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField(
label='Correo Electrónico',
required=True
)
username = forms.CharField(
required=True,
label='Nombre de Usuario'
)
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
image = forms.ImageField(
label = 'Foto de perfil'
)
class Meta:
model = Profile
fields = ['image']
register.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Cree su cuenta</legend>
{{ form|crispy }}
</fieldset>
<div>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Registrarse</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
¿Ya tiene una cuenta? <a class="ml-2" href='{% url 'login' %}'>Inicie sesión</a>
</small>
</div>
</div>
{% endblock content %}
apps.py
class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
def ready(self):
import users.signals
Please feel free to tell me if you guys need something else from my code.
CodePudding user response:
One of the method is you can update your Model's username filed and can add validator like :
username = models.CharField(max_length=30, unique=True,
validators=[
validators.RegexValidator(r'^[\w. @ -] $', _('Enter a valid username.'), 'invalid')
])