Django UserCreationForm custom fields

2024/10/13 15:18:45

I am trying to create form for user registration and add some custom fields. For doing that, I've subclassed UserCretionForm and added fields as shown in django documentation. Then I've created function-based view and template based on this form. Now, I can successfully create user and this user is added to admin panel as expected. Problem is that, I can't add class and style for this form's fields. Widgets are not working except for username field. I'm adding my scripts here for illustrating my problem more accurately:

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import Userclass SignUpForm(UserCreationForm):first_name = forms.CharField(max_length=32, help_text='First name')last_name = forms.CharField(max_length=32, help_text='Last name')email = forms.EmailField(max_length=64, help_text='Enter a valid email address')class Meta(UserCreationForm.Meta):model = User# I've tried both of these 'fields' declaration, result is the same# fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)widgets = {'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}),'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}),'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}),'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}),'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}),'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}),}

views.py

from django.contrib.auth import login, authenticate
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirectfrom .forms import SignUpForm, SignInFormdef signup(request):if request.method == 'POST':form = SignUpForm(request.POST)if form.is_valid():form.save()username = form.cleaned_data.get('username')raw_password = form.cleaned_data.get('password1')user = authenticate(username=username, password=raw_password)login(request, user)return redirect('/')else:form = SignUpForm()return render

Widgets in 'forms.py' are not working except for 'username' field. In other words, in web browser 'username' input is shown with "class='form-control'" and "placeholder='Username'", but other fields don't have class and placeholder attribute as I expected. What can be the reason?

Answer

You don't need to define fields unders widgets. Define them as static at class level.

class SignUpForm(UserCreationForm):username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}))first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name')last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name')email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address')password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}))password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}))class Meta(UserCreationForm.Meta):model = User# I've tried both of these 'fields' declaration, result is the same# fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)
https://en.xdnf.cn/q/69518.html

Related Q&A

Why val_loss and val_acc are not displaying?

When the training starts, in the run window only loss and acc are displayed, the val_loss and val_acc are missing. Only at the end, these values are showed. model.add(Flatten()) model.add(Dense(512, ac…

Is there a python module to solve/integrate a system of stochastic differential equations?

I have a system of stochastic differential equations that I would like to solve. I was hoping that this issue was already address. I am a bit concerned about constructing my own solver because I fear m…

How does thread pooling works, and how to implement it in an async/await env like NodeJS?

I need to run a function int f(int i) with 10_000 parameters and it takes around 1sec to execute due to I/O time. In a language like Python, I can use threads (or async/await, I know, but Ill talk abou…

Calculate centroid of entire GeoDataFrame of points

I would like to import some waypoints/markers from a geojson file. Then determine the centroid of all of the points. My code calculates the centroid of each point not the centroid of all points in the …

Flask-Babel localized strings within js

Im pretty new to both Python and Flask (with Jinja2 as template engine) and I am not sure I am doing it the right way. I am using Flask-Babel extension to add i18n support to my web application. I want…

a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib

I am very new to Python (and web scraping). Let me ask you a question. Many website actually do not report its specific URLs in Firefox or other browsers. For example, Social Security Admin shows popul…

Why is tuple being returned?

I have the following:tableNumber = session.query(TABLE.TABLESNUMBER).filter_by(TABLESID=self.TABLESID).first() return str(tableNumber)This is my TABLE class:class TABLE(Base):.... TABLESID =…

How to assert both UserWarning and SystemExit in pytest

Assert UserWarning and SystemExit in pytestIn my application I have a function that when provided with wrong argument values will raise a UserWarnings from warnings module and then raises SystemExit fr…

Distinguish button_press_event from drag and zoom clicks in matplotlib

I have a simple code that shows two subplots, and lets the user left click on the second subplot while recording the x,y coordinates of those clicks.The problem is that clicks to select a region to zoo…

String reversal in Python

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?I a…