I'm trying to add data from UserCreationForm extra fields to database, i want to add multiple fields to UserCreationForm and save it to database. I saw other examples from topics here in stackoverflow, but it doesn't work.
Here is a example of my code:
( fields: "agree_terms" or "price" could be anything else)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(widget = forms.EmailInput(attrs=
{'placeholder':'Email'}))
agree_terms = forms.BooleanField()
price = forms.DecimalField(decimal_places=2, max_digits=10000)
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('username', 'password1',
'email','password2','agree_terms','price')
views.py
#csrf_protect
def registers(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
print(form)
print(form.is_valid())
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request,'Conta criada {}'.format(username))
return redirect('login')
else:
form = UserRegisterForm()
return render(request,'header-login.html',{'form':form})
Did you also changed your User model to support those fields? You'd need to add them to the model/table as well.
Although, I wouldn't recommend piling up so much extra data directly on the User model.
Related
I was trying to register a new user through the frontend with the help of django but i saw quite a few tutorials use UserCreationForm but for my case it does't seem to work.
views.py
def registerUser(request) :
form = RegisterForm()
context = {'form':form}
if request.method == 'POST' :
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'User Created succesfully')
print('user Created')
return redirect('users:login')
else :
print('Not valid')
return render(request, 'register.html', context)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
My is_valid() function is giving me that the request.POST isn't valid.
Look at Django's UserCreationForm source code.
# default
class Meta:
model = User
fields = ("username",)
field_classes = {'username': UsernameField}
By implementing your own fields, you are potentially destroying Django's default form. All I can see, the error lies as you did not set field_classes for username. Try changing that.
In Your forms.py try this,
class UserCreateForm(UserCreationForm):
fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name')
model = YOUR_MODEL_THAT_YOU_HAVE_CREATED()
class Meta:
# Some Custom Options...
I'm new at using Django forms (Django altogether), and on my first form, I have encountered this error. No matter what data I post via the form it saves the superuser name in all the fields.
Here are the files,
forms.py
from django.forms import ModelForm
from .models import *
class NewCustomer(ModelForm):
class Meta:
model = Customer
fields = ('name', 'mobile_number', 'email', 'address')
Views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import *
from .forms import *
# Create your views here.
def customers(request):
customers = Customer.objects.all().order_by('id')
return render(request, "customers.html", {'customers': customers, 'custactive': "active"})
def customer_details(request, pk):
customer = get_object_or_404(Customer, pk=pk)
return render(request, "customer_details.html", {'customer': customer})
def new_customer(request):
if request.method == 'POST':
form = NewCustomer(request.POST)
if form.is_valid():
customer = form.save(commit=False)
customer.name = request.user
customer.mobile_number = request.user
customer.email = request.user
customer.address = request.user
customer.save()
return redirect ('customers')
else:
form = NewCustomer()
return render(request, "new_customer.html", {'form': form})
Can someone tell me what's wrong with the code? Understandably I need to save new data that I supply with the form.
Really appreciate your help...
The problem is that you need to tell the form which fields to get from User object.
Now if you have extended the User model and have name, mobile_number, address specified, you need to modify your code.
def new_customer(request):
if request.method == 'POST':
form = NewCustomer(request.POST)
if form.is_valid():
customer = form.save(commit=False)
customer.name = request.user.name
customer.mobile_number = request.user.mobile_number
customer.email = request.user.email
customer.address = request.user.address
customer.save()
return redirect ('customers')
The reason whz superuser's name is saved in all fields is because all models have their str method, which tells python what to print out if object itself is used.
I have a signup form which I have defined below
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
class SignUpForm(UserCreationForm):
display_name = forms.CharField(max_length=30, required=True, help_text='Please provide a display name for your profile')
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'display_name')
In the views.py, I handle the signup process
views.py
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from .forms import SignUpForm
from django.shortcuts import render, redirect
#csrf_exempt
def signup_users(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data.get('username')
display_name = form.cleaned_data.get('display_name')
raw_password = form.cleaned_data.get('password1')
user.set_password(raw_password)
user.display_name = display_name
user.save()
user = authenticate(username=username, password=raw_password)
print("signup authencticate", user)
login(request, user)
return render(request, 'index.html')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
The user is able to signup successfully however their display_name doesn't get stored in the django User model.Even in the django admin, I do not see the field display_name.I have even performed a query like serializers.serialize("json",User.objects.filter(username=username)) but even here it shows every other field except the display_name.
What am I doing wrong?
Well quite simply the django.contrib.auth.models.User model has not field named display_name so of course it doesn't get saved. If you want to add fields to your User model you'll have to provide a custom User model.
First attempt at trying to create a student user by extending the User model.
Issue: Upon clicking register btn i.e.Login (btn) instead of
redirecting to home it shows the following: NameError at /register/
...name 'user' is not defined
File "E:\ifb299\tutorial2\accounts\views.py", line 33, in register
Students.objects.create(user=user) NameError: name 'user' is not defined [25/Mar/2018 14:38:07] "POST /register/ HTTP/1.1" 500 67801
Not really sure what I'm doing wrong, why is Students.objects.create(user=user) wrong and how do i fix it, please?
views.py
from django.shortcuts import render
from django.shortcuts import redirect
from accounts.forms import RegistrationForm, EditProfileForm
from django.contrib.auth.models import User
from accounts.models import Students
from django.contrib.auth.forms import UserChangeForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'accounts/home.html')
def login_redirect(request):
return redirect('/login/')
def register(request):
# Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
Students.objects.create(user=user)
return redirect('../home/')
else:
# Create the django default user form and send it as a dictionary in args to the reg_form.html page.
form = RegistrationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
#login_required
def view_profile(request):
args = {'user': request.user}
return render(request, 'accounts/profile.html', args)
#login_required
def edit_profile(request):
# Handle post request - if the user submits a form change form details and pass the intance user
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('../profile')
# Handles the get request - if no post info is submitted then get the form and display it on the edit profile page.
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/profile_edit.html', args)
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.db.models.signals import *
from django.conf import settings
class Students(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
forms.py
from django import forms
from django.contrib.auth.models import User
from .models import *
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
# Create a custom form that inherites form UserCreationForm (adding our own fields to save i db)
# Inheriting form in the paramters ()
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Students
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
'bio',
'location',
'birth_date',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
# Inherits from UserChangeForm class - we keep everything i.e. methods, functionality same but change the things we want to show - connected to the User model
class EditProfileForm(UserChangeForm):
class Meta:
model = User
# Create fields variable get has all the fields we want to show
fields = (
'email',
'first_name',
'last_name',
'password'
)
first, you did not save the return value of form.save() to the variable user.
second, there is no field user your model Student.
I am curious to see what the line model = User does in my forms.py so I decided to comment it out. The result was this error:
ModelForm has no model class specified.
and it is highlighted on line 45 of views.py
args['form'] = MyRegistrationForm()
I'm still not quite sure how the model = User plays a roll in my custom user registration form. (I've been following a tutorial). I was wondering if someone could briefly explain to me this whole process and why model = User is needed
My guess is that model is now a User object. Also args['form'] = MyRegistrationForm() needs to be a model object or else the code will crash. This is as far as my assumptions go.
My views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from forms import MyRegistrationForm
def register_user(request):
if request.method == 'POST':
form = MyRegistrationForm(request.POST) # create form object
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
print args
return render(request, 'register.html', args)
my forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
first_name = forms.CharField(required = False)
last_name = forms.CharField(required = False)
birthday = forms.DateField(required = False)
class Meta:
#model = User
fields = ('email', 'username', 'password1', 'password2', 'last_name', 'first_name', 'birthday') # set up ordering
def save(self,commit = True):
user = super(MyRegistrationForm, self).save(commit = False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.birthday = self.cleaned_data['birthday']
if commit:
user.save()
return user
I'm still not quite sure how the model = User plays a roll in my
custom user registration form.
Your form inherit from django.contrib.auth.forms.UserCreationForm which is a ModelForm.
I was wondering if someone could briefly explain to me this whole
process and why model = User is needed
ModelForms are documented here : https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/
As a side note, if you had inherited your form's Meta from UserCreationForm.Meta you wouldn't need to specify the model once again.
My guess is that model is now a User object.
User is a class.
Also args['form'] = MyRegistrationForm() needs to be a model object
or else the code will crash. This is as far as my assumptions go.
Don't assume: read the doc, then read the code (remember, it's open source software).