When I enter the details in this form and press the submit button , I don't see the values of phoneno and otp getting saved in the database .The fields phone number and otp are not shown at all .
SEE image only username is saved and the otp and phone number fields are not displayed nor saved
This is my signup/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Create your models here.
class allusers1(UserCreationForm):
phoneno1=forms.CharField(label = "phonewa",max_length=10)
otp1=forms.IntegerField(label="OTPP",required=False)
class Meta:
model=User
fields=(
'username',
'password',
'phoneno1',
'otp1',
)
def save(self,commit=True):
user=super(allusers1,self).save(commit=False)
user.username1=self.cleaned_data['username']
user.password1=self.cleaned_data['password']
user.phoneno1=self.cleaned_data['phoneno1']
user.otp1=self.cleaned_data['otp1']
if commit:
user.save()
return user
This is mysignup/forms.py
from django.shortcuts import render
from .forms import allusers1
def signup(request):
form1=allusers1(request.POST or None)
if form1.is_valid():
form1.save()
context = {
"form1": form1,
}
return render(request, "signup.html",context)
Your User model is the default django.contrib.auth.models.User that you import in the second line. This model has predefined fields. otp1and phoneno1 are not amongst them as you can see from the docs. So when you save a Userinstance, these attributes are simply ignored.
So you have to extend the User model like described in the docs (Django 2.0).
# models.py
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
otp1 = models.IntegerField(null=True)
phoneno1 = models.CharField(max_length=10)
# settings.py
settings.AUTH_USER_MODEL = 'myapp.User'
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
You won't need a special form then for the Django admin. Your own model will inherit everything Django's User model brings with it, plus your own fields / methods.
Related
During my first Django app i've managed to hit this 'road-block' where i'm trying to extend User model from my .forms file where forms.py looks like this:
#forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
phone = forms.CharField(max_length=50, required=False)
class Meta:
model = User
fields = ['username', 'email', 'phone', 'password1', 'password2']
class UserLoginForm(AuthenticationForm):
class Meta:
model = User
fields = ['username', 'password']
In my .models file i'm only having a 'Profile' model which is being registered within admin.py:
#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import *
from .forms import UserRegisterForm
admin.site.unregister(User)
class CustomUserAdmin(UserAdmin, UserRegisterForm):
fieldsets = UserAdmin.fieldsets + (
(('Personal info'), {'fields': ('phone',)}),
)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Profile)
...and i'm getting this back(bare in mind i've tried also passing just my form class which resulted in allot more errors):
#error
FieldError at /admin/auth/user/1/change/
Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth/user/1/change/
Django Version: 3.0.4
So the end goal would be to have another field available in my Users/'Personal info'(that's been extended within forms.py) and also would be nice to get that field when creating a new user from within the admin page. Any help/idea would be greatly appreciated, thanks.
This is the image of the default Django User fields.
models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Visitor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.IntegerField()
admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from accounts.models import Visitor
class VisitorInline(admin.StackedInline):
model = Visitor
can_delete = False
verbose_name_plural = "visitor"
class UserAdmin(BaseUserAdmin):
inlines = (VisitorInline,)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
This image has the default Django user fields such as username, email address, first name and last name. I want to add a custom field such as a phone number to the existing fields. How can I achieve this? Thank you!
I am trying to create a model UserProfile by extending it from Django's built in User model. After filling out the form the data should be saved in UserProfile model. It's just not happening
Initially, the data was only saved in User model but not in UserProfile model. I applied some recommended solutions from the web but now I cannot even fill up the form. On prompting to/register, I get an error saying,
type object 'UserProfile' has no attribute 'USERNAME_FIELD'
#models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.EmailField( max_length=254)
country = models.CharField( max_length=50)
#forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile
class RegistrationForm(UserCreationForm):
class Meta:
model = UserProfile
fields = ['email', 'country']
#views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import RegistrationForm
from .models import UserProfile
from django.contrib.auth.models import User
def home(request):
return render(request , 'guide/index.html')
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
u= form.save(commit=False)
u.user = request.user
u.save()
return redirect('home')
else:
form=RegistrationForm()
return render(request, 'guide/register.html', {'form':form})
I want the code to run and save the data to UserProfile model, but the page says that UserProfile has no attribute 'USERNAME_FIELD'
I am having difficulty creating custom User fields using the Cookiecutter Django framework. I have changed the cookiecutter template significantly - removing django-allauth but a lot of the structure remains the same.
If I wanted to add another field to the User model (for example, "department" - the users are employees), where would I add it?
I figured I could add a department variable to users/models.py but it doesn't seem to work. When I login to the admin site, I don't see a department field when I add a user. Similarly, I don't see a name field in the admin site - I only see First Name, Last Name, and Email Address.
# users/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
#python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(blank=True, max_length=255)
department = models.CharField(blank=True, max_length=5)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
The admin file:
# users/admin.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import User
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = User
class MyUserCreationForm(UserCreationForm):
error_message = UserCreationForm.error_messages.update({
'duplicate_username': 'This username has already been taken.'
})
class Meta(UserCreationForm.Meta):
model = User
def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
#admin.register(User)
class UserAdmin(AuthUserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
You are missing the fieldsets attribute:
#admin.register(User)
class UserAdmin(AuthUserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
fieldsets = (
('', {'fields': ('department',)}),
) + AuthUserAdmin.fieldsets
list_display = ('username', 'department', 'is_superuser')
search_fields = ['username', 'department']
You don't need to set the attributes list_display and search_fields to display your department field. But I left them in the sample since they are very handy when it comes to Django admin customization.
ModelAdmin.list_display:
Set list_display to control which fields are displayed on the change
list page of the admin.
ModelAdmin.search_fields:
Set search_fields to enable a search box on the admin change list
page. This should be set to a list of field names that will be
searched whenever somebody submits a search query in that text box.
I would like to add some extra fields to user in django-cms (in django admin panel). How to do this in the simplest way?
Need to add two fields user bio and image. And can i use this in frontend to show a page with all the user info?
From the django docs
Create you custom user model like this
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
Change the admin file like this
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import Employee
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
model = Employee
can_delete = False
verbose_name_plural = 'employee'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
OR
Another option is to define a custom user model. For more details please visit https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
Taken from Django documentation:
The simplest way would be to create what is often called a profile model. So for your example you would create something like
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField()
image = models.ImageField()
Then, for seeing this in the admin panel, you would reregister admin for the User
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import Profile
class UserProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'profile'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
As far as showing this in frontend, you can use User as well as Profile the same way you would use other Django models.