please help change the order of the form fields on the screen.
I created the following model:
class UserProfile(User):
status = models.CharField(
max_length=30,
blank=True,
)
address = models.EmailField(
max_length=50,
blank=True,
)
objects = UserManager()
then combined field of this model built with fields of the registration form:
class MyRegistrationForm(UserCreationForm):
username = forms.CharField(
label='username',
help_text='',
required=True,
)
password1 = forms.CharField(
label='pass1',
help_text='',
required=True,
)
password2 = forms.CharField(
label='pass2',
help_text='',
required=True,
)
class Meta:
model = UserProfile
fields = ('status', 'address')
as a result the user sees on the display field in this order:
status, address, username, pass1, pass2
but I need the user to see the screen fields in the following order:
username, address, pass1, pass2, status
According to the documentation:
The generated Form class will have a form field for every model field
specified, in the order specified in the fields attribute.
class MyRegistrationForm(UserCreationForm):
...
class Meta:
model = UserProfile
fields = ('username', 'address', 'password1', 'password2', 'status')
See also: How can I order fields in Django ModelForm?
Related
I currently have a single page signup form implemented with allauth
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
email = models.EmailField(_('Professional email address'), unique=True)
username = models.CharField(_("User Name"), blank=False, max_length=255, unique=True)
first_name = models.CharField(_("First Name"), null=True, max_length=255, default='')
last_name = models.CharField(_("Last Name"), null=True, max_length=255, default='')
country = CountryField(_("Country of Practice"), blank_label='(Country of Practice)', blank = False, default='GB')
terms = models.BooleanField(verbose_name=_('I have read and agree to the terms and conditions'), default=False)
def get_absolute_url(self):
return reverse(
"users:detail", kwargs={"username": self.username}
)
objects = UserManager()
And this is the forms.py
class UserCreationForm(forms.UserCreationForm):
error_message = forms.UserCreationForm.error_messages.update(
{"duplicate_username": _("This username has already been taken.")}
)
username = CharField(label='User Name',
widget=TextInput(attrs={'placeholder': 'User Name'}))
class Meta(forms.UserCreationForm.Meta):
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms']
field_order = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms']
def clean_terms(self):
is_filled = self.cleaned_data['terms']
if not is_filled:
raise forms.ValidationError('This field is required')
return is_filled
def clean_username(self):
username = self.cleaned_data["username"]
if self.instance.username == username:
return username
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise ValidationError(
self.error_messages["duplicate_username"]
)
I would like however for the first sign up page to have a ‘next’ button at the bottom and then there would be a second page where the user input separate details (the data input here might vary based on the inputs in the first page). The Django ‘form tools’ form wizard seems well suite to this but I can’t work out how to integrate it with all auth
Any suggestions much appreciated
I created a user profile model for my system. I created all models and it works perfectly. I have a form, and the form works too. But when I look user create form from admin page, it doesn't look the same.
There are some missing parts like rank, comp_name. How can I fix it?
models.py
class UserProfile(models.Model):
ranks = (
('xxx', 'xxx'),
...
)
comp_name = models.CharField(max_length=200, default="Choose")
user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
username = models.CharField(max_length=500)
first_name = models.CharField(max_length=200, default=None)
last_name = models.CharField(max_length=200, default=None)
password = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
rank = models.CharField(max_length=200, choices=ranks)
forms.py
class SignUpForm(UserCreationForm):
comp_name = forms.CharField(label='What is your company name?')
email = forms.CharField(max_length=254)
rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks)
first_name = forms.CharField(max_length=250)
last_name = forms.CharField(max_length=250)
comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all())
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'comp_name', 'password1', 'password2', 'rank'
admin
admin panel "Change User" screen
In forms.py
class SignUpForm(UserCreationForm):
comp_name = forms.CharField(label='What is your company name?')
email = forms.CharField(max_length=254)
rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks)
first_name = forms.CharField(max_length=250)
last_name = forms.CharField(max_length=250)
comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all())
class Meta:
model = User --> change to UserProfile
fields = ('username', 'first_name', 'last_name', 'email', 'comp_name', 'password1', 'password2', 'rank'
I'm trying to make a custom User Model and have parameters like Date of Birth, current level and other such parameters. When I run python manage.py createsuperuser, it gives an error saying these values cannot be null. I don't want these parameters for the superuser account. WHat do I do?
I tried adding the following line to the class that inherits from the UserAdmin class
exclude = ('date_of_birth', 'currentLevel', 'totalStars', 'badges')
This is the model fields
class Learner(AbstractBaseUser):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=255, unique=True)
date_of_birth = models.DateField(auto_now=False, auto_now_add=False)
currentLevel = models.ForeignKey(SubLevelConcepts, related_name='currentLevel', on_delete=models.CASCADE)
totalStars = models.IntegerField(default=0)
badges = models.IntegerField(default=0)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
superuser = models.BooleanField(default=False)
objects = LearnerManager()
This is the admin class
class LearnerAdmin(UserAdmin):
add_form = LearnerCreationForm
form = LearnerChangeForm
model = Learner
exclude = ('date_of_birth', 'currentLevel', 'totalStars', 'badges')
list_display = (
'first_name',
'last_name',
'email',
'staff',
'active'
)
list_filter = (
'email',
'active'
)
fieldsets = (
(None, {'fields': ('email', 'password',)}),
('Permissions', {'fields': ('staff', 'active')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name','password1', 'passsword2', 'staff', 'active')}
)
)
search_fields = ('email',)
ordering = ('id',)
filter_horizontal = ()
This is the final error when i run python manage.py createsuperuser
django.db.utils.IntegrityError: (1048, "Column 'currentLevel_id' cannot be null")
I want the superuser to just take email and password and finish the job. I'll add the first_name and last_name later
Add null=True and default=None to your ForeignKey field so it's not required, ie
class Learner(AbstractBaseUser):
# ...
currentLevel = models.ForeignKey(SubLevelConcepts, null=True, related_name='currentLevel', on_delete=models.CASCADE)
You may also want to use either models.PROTECT or models.SET_NULL instead of models.CASCADE - unless you really want your users accounts to be deleted when their matching SubLevelConcept is deleted, that is...
And you may also want to check the blank=True models field option FWIW.
I have created a registration form using Django's usercreation form.
Then i created a EditProfileForm using the registration form.
My issue is that EditProfileForm uses User Model, and the Birthdate field is in Profile Model. Thus, I am able to edit all fields except Birthdate as it is not from the User Model.
How do I go about editing birthdate, or creating a form where I can edit all fields instead of only the user fields?
My Model for Profile:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT)
def __str__(self):
return self.user.username;
USWEST = 'usw'
USEAST = 'use'
EUROPE = 'eu'
OCEANIA = 'oce'
ASIA = 'as'
SOUTHAMERICA = 'sam'
SOUTHAFRICA = 'saf'
MIDDLEEAST = 'me'
PREF_SERVER_CHOICES = (
(USWEST, 'US-West'),
(USEAST, 'US-East'),
(EUROPE, 'Europe'),
(OCEANIA, 'Oceania'),
(ASIA, 'Asia'),
(SOUTHAMERICA, 'South America'),
(SOUTHAFRICA, 'South Africa'),
(MIDDLEEAST, 'Middle-East'),
)
pref_server = models.CharField(
max_length=3,
choices=PREF_SERVER_CHOICES,
default=USWEST,
)
birth_date = models.DateField(null=True, blank=False,)
sessions_played = models.IntegerField(null=False, blank=False, default='0',)
teamwork_commends = models.IntegerField(null=False, blank=False, default='0',)
communication_commends = models.IntegerField(null=False, blank=False, default='0',)
skill_commends = models.IntegerField(null=False, blank=False, default='0',)
positivity_commends = models.IntegerField(null=False, blank=False, default='0',)
FORMS.PY
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from apps.api.models import Profile, Feedback
from django.forms import ModelForm
#form to create profile
#RegistrationForm VIEW must be created first as well as URl
class RegistrationForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required = False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required = False, help_text='Optional.')
email = forms.EmailField(max_length=254, required=True, help_text='Required. Enter a valid email address.')
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
#Class meta will dictate what the form uses for its fields
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'birth_date',
'password1',
'password2',
)
#Function to save form details
def save(self,commit=True):
if commit:
#Setting Commit to false,otherwise It will only save the fields existing in UserCreationForm
user = super(RegistrationForm, self).save(commit=False)
#Adding additional Fields that need to be saved
#Cleaned data prevents SQL Injections
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
Profile.birth_date = self.cleaned_data['birth_date']
user.save()
return user
# User editing profile details
class EditProfileForm(RegistrationForm):
class Meta:
model = User
fields = [
'email',
'first_name',
'last_name',
'birth_date',
]
I'm integrating ModelForm with Django's restless to make an API for my server. By now, I'm working on a update operation on a User.
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_("email address"), unique=True)
username = models.CharField(_("username"), max_length=30, unique=True)
first_name = models.CharField(verbose_name=_("First name"), max_length=100, blank=True)
last_name = models.CharField(verbose_name=_("Last name"), max_length=100, blank=True)
description = models.TextField(verbose_name=_("Description"), blank=True)
phone = models.CharField(verbose_name=_("Phone"), max_length=30, blank=True)
last_location = models.PointField(verbose_name=_("Last location"), geography=True, null=True, blank=True)
other fields...
Here's my ModelForm for the User class:
class ProfileForm(ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'description', 'phone', 'last_location', 'lang')
And here's the call I make to update the user from the restless Resource update function:
form = ProfileForm(self.data, instance=user)
if form.is_valid():
user = form.save()
where self.data is a dictionary including the values received on the call.
{dict} {u'lang': u'es', u'phone': u'293923293', u'first_name': u'Name'}
My problem comes when updating a User. The other fields not included in self.data dictionary are setting their values to ''.
Any ideas?