I am trying to make a signup interface in Django. at first, I have created a form using Django user creation form along with two extra fields. but whenever I submit the form I can not find the data of extra field.
here is the code for form creation:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserSignUp(UserCreationForm):
email=forms.EmailField()
age=forms.CharField()
adress=forms.CharField()
class meta:
model=User
fields=['username','password1','password2','email','age','adress']
and here is the view for signup validation
def signupuser(request):
if request.method=="POST":
form=UserSignUp(request.POST)
if form.is_valid():
form.save()
return render(request,'diabetes/home.html')
else:
form=UserSignUp()
return render(request,"diabetes/signupuser.html",{'form':form})
now, what should I do?
You are trying to save fields which aren't on the model.
The defautl django.contrib.auth.models.User has only the fields:
username
password
email
first_name
last_name
The UserCreationForm has the "additional"/changed fields:
password1
password2
But the fields age, address aren't on the User model and therefore nowhere saved.
You can either extend the existing User model or use a custom user model
Related
I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city.
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
full_name=forms.CharField(max_length=50,required=True)
phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'}))
address=forms.CharField(max_length=200,required=True)
city=forms.CharField(max_length=200,required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city')
def register(self):
self.save()
I created form by using this method. First, created forms.py for extra fields then inherited it. It is working; but still some fields disappear.
Because, you are adding additional fields to the default user model. First you have to
-Create a Custom User Model by using AbstractUser
Then
-Create a Custom Form for UserCreationForm
You can search google for:
Extend-existing-user-model-in-django
What would be the steps to create a user profile other than the administrator user please, I am a newbie. I leave the model class of which I want to be a user profile
from django.contrib.auth.models import User
user = models.OneToOneField(User, ondelete=models.CASCADE)
Add this field to the model.
If you are using Django's auth user registration form then, while registering new user in views.py:
form = UserRegistrationForm(request.POST)
if form.is_valid():
instance = form.save()
apoderado = Apoderado()
apoderado.user = instance
apoderado.other_fields = form.cleaned_data['other_fields']
apoderado.save()
This will create new user with extra fields. This is a simple trick but, if any error occurs then only half of data will be stored. If you want to go for extra, use Django signals.
I am trying to create a simple user login system where a user gets to sign up on one page and then use those credentials to login to the website on another page. Here's my sign-up and login views:
class SignupView(CreateView):
model = User
form_class = SignupForm
template_name = 'journal_app/signup.html'
success_url = reverse_lazy('home')
class LoginUserView(LoginView):
template_name = 'journal_app/login.html'
As you can see I'm using the CreateView to create User objects. After the user signs up I can see that the record is successfully updated in the Users group in my Admin console. The problem is that when I try to login, it always throws me a username/password don't match error. Any ideas what could be the reason? I am a beginner at Django so it could be something pretty simple.
SignupForm-
class SignupForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'username', 'password']
widgets = {
'password': forms.PasswordInput()
}
The problem is that you need to hash the password. Django stores a hash of the password [Django-doc]. If you make a custom user model, you should normally implement a UserManager [Django-doc] as well. This takes a password, and will hash it, for examply by calling a method .set_password(…) [Django-doc]. This method will then hash the password.
You thus can rewrite the form to save the user with:
class SignupForm(forms.ModelForm):
class Meta:
model = User
fields = ['first_name', 'username', 'password']
widgets = {
'password': forms.PasswordInput()
}
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data['password'])
if commit:
user.save()
return user
Hi I am new to Django and I have created a login/logout model Django inbuilt User and UserCreationForm. It is working fine but my issue is I have define two custom inputs in my form and it is displaying on the web page when I run the server but when I check the user under the admin, I only see the details of User defined fields not my custom fields.
How to save it's data to my User model?
or maybe If I defined the custom fields wrong how do I change it so that I can save it's data in my model.
My custom defined fields that is address and phone number is not showing in Admin User and it's data is not getting saved.
model.py
from django.db import models
from django.contrib import auth
# Create your models here.
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django import forms
class UserCreateform(UserCreationForm):
address = forms.CharField(max_length=150, required=True)
phone_number = forms.IntegerField(required=True)
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('username','email','password1','password2')
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateform
success_url = reverse_lazy('login')
template_name = 'account/signup.html'
Adding fields to a ModelForm doesn't do anything in terms of saving them, if they are not fields of the Model. So of course, address and phone_number aren't saved, your User model doesn't have those fields.
You need to have a Model to save those fields. As explained here, you have two options:
Create a Profile model to save all extra fields
Create a custom User model, subclassing AbstractUser or AbstractBaseUser.
My advice: Do both. Save your extra fields in a Profile model.
And subclass AbstractUser, so you have the option to add useful methods and properties to the User model (right now, just __str__()).
Why not just subclass? Because as your app grows, you'll want to add more an more things to a user's profile. Maybe you want to create different types of profiles, e.g. the private profile and the professional profile. The User itself should be compact, just managing authentication and permissions.
Note: your current User model is wrong. You must not subclass auth.User but auth.AbstractUser.
I need two extra fields for the user data so I followed the official django docs Extending the existing User model, the admin form for users works fine but I have a UserCreationForm and I want to add the two extra fields in that form too, already tried to use two forms, the UserCreationForm and the form for my extended user model but I can't get the id of the UserCreationForm to fill the user_id of my extended user model so I search how to use a signal to do that like the django docs recommend and find this Django Signals: create a Profile instance when a new user is created but that only fill the user_id of my extended user model that is the OneToOneField but not the two extra fields.
sorry for my bad english.
I need to run but here's a quick implementation. It needs some tweaks apparently but should get you started:
# this is your model form for extended OneOnOne with user
class ExtendedForm(forms.ModelForm):
model = ExtendedModel
# temporary exclude user field to pass the validation
exclude = ('user')
def create_user(request):
user_form = UserForm(request.POST or None)
extra_form = ExtendedForm(request.POST or None)
if user_form.is_valid() and extra_form.is_valid():
# create a new user first
new_user = user_form.save()
# create an object in memory but not save it
new_extended_obj = extra_form.save(commit=False)
# assign the user to the extended obj
new_extended_obj.user = new_user
# write to database
new_extended_obj.save()