form not saving email in django admin - python

django forms doesn't save email in the database.i try all sort of things but still it is the only thing that is not saving .I need help
https://i.imgur.com/LJymHeS.png
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
email=forms.EmailField()
class meta:
model=User
fields= ['username', 'email_address', 'password1','password2']
views.py code
register(request):
if request.method=='POST':
form=UserRegistrationForm(request.POST)
if form.is_valid():
form.save(commit=False)
username=form.cleaned_data['username']
password1=form.cleaned_data['password1']
password2=form.cleaned_data['password2']
email_address=form.cleaned_data['email']
form.save()
return redirect('/')
else:
form=UserRegistrationForm()
return render(request, 'blog/register.html',{'form':form})

The name of the field is email, not email_address. You thus should change this to:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField()
class meta:
model = User
fields = ['username', 'email']
Furthermore password1 and pasword2 are no model fields either. The UserCreationForm has some logic to compare the fields, and set a password.
In your register view, there is no need to unpack the cleaned data, you can just use form.save(). You can call login(request, user) if you want to automatically login the user you just created:
from django.contrib.auth import login
def register(request):
if request.method=='POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('/')
else:
form = UserRegistrationForm()
return render(request, 'blog/register.html',{'form':form})
You can override the UserAdmin admin with:
# blog/admin.py
from blog.forms import UserRegistrationForm
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
admin.site.unregister(User)
#admin.register(User)
class NewUserAdmin(UserAdmin):
add_form_template = 'blog/register.html'
add_form = UserRegistrationForm

In django documentation the class used in UserCreationForm is Meta. you have to use capital M for meta class.You should get it correct when you have changed to capital M
class Meta:
model = User
fields = ['username', 'email']

Related

How can I save a django form

So I want to save a Biographie for each new created User. The user can enter his Bio and it will the it to his Profile.
For this I created a model with OneToOneField
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, null=True, blank=True)
bio = models.CharField(max_length=30)
To create the form I did the following in forms.py:
class BioForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('bio',)
Then I created in the views.py the saving, so the bio will be saved to the specific user:
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
There is something big wrong in the views.py but I don't get it.
I can submit the form and the form will be saved (sometimes) but without the user who wrote it + I get this error:
ValueError at /test/
Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000253B7140D00>>": "Profile.user" must be a "User" instance
Try to assign the user id instead
from .forms import LoginForm, RegisterForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.contrib.auth import get_user_model
def test_view(request):
form = BioForm(request.POST)
user = get_user_model
if form.is_valid():
profile = form.save(commit=False)
profile.user_id = request.user.id
profile.phone_number = request.phone_number
profile.save()
return render(request, 'test.html', {'form': form})
Your problem is that the user you try to save with, is not an authenticated user that exists in the database. Only authenticated (logged in) users exist in the database and can be used in a relational field

ModelForm has no model class specified error django framework

I'm receiving the error
"ValueError at /accounts/create/
ModelForm has no model class specified."
Views.py:
from django.shortcuts import render
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.contrib.auth.models import Group
def signupView(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
signup_user = CustomUser.objects.get(username=username)
customer_group = Group.objects.get(name='Customer')
customer_group.user_set.add(signup_user)
else:
form = CustomUserCreationForm()
return render(request, 'signup.html', {'form':form})
I can't find any the error for the life of me, any help would be appreciated. Thanks.
Edit::
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
Meta = CustomUser
fields = UserCreationForm.Meta.fields + ('age',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
Above is the CustomUserCreationForm
In your CustomUser model, in Meta class, you have used Model = CustomUser. Instead you need to use model = CustomUser.

django user creation using UserCreationForm issue

As per youtube tutorial the user is created with exactly same method but mine doesn't work. Why?
views.py
from django.shortcuts import render,redirect
from .forms import CreateUserForm
def registerView(request):
form=CreateUserForm()
if request.method=="POST":
form=CreateUserForm(request.POST)
if form.is_valid():
form.save()
user=form.cleaned_data.get('username')
messages.success(request,'Account was successfully created for '+ user)
return redirect('login')
context={'form':form}
return render(request,"accounts/register.html", context)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2']
Why is a user not created?

NameError at /register/ name 'user' is not defined

I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a NameError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = user in my views.py is creating the problem. Can anyone please help me with this?
my views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, ProfileForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
profile_form = ProfileForm(request.POST)
if form.is_valid() and profile_form.is_valid():
form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
profile_form = ProfileForm
return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form})
#login_required
def profile(request):
return render(request, 'users/profile.html')
my models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
CHOICES = (
('AB+', 'AB+'),
('AB-', 'AB-'),
('A+', 'A+'),
('A-', 'A-'),
('B+', 'B+'),
('B-', 'B-'),
('O+', 'O+'),
('O-', 'O-'),
)
bloodgroup = models.CharField(max_length=100, choices= CHOICES)
bio = models.TextField(max_length=300)
def __str__(self):
return f'{self.user.username} Profile'
my forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def save(self, commit=True):
user = super().save(commit=False)
if commit:
user.save()
return user
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('image', 'bloodgroup', 'bio')
profile.user = user change to profile.user = request.user
Just add
from django.contrib.auth.models import User
instead of
from django.contrib.auth import User

How to view (the same) data (of User) in UserProfile in Django

So I've got this situation.
-models.py
from django.db import models
from django.utils import timezone
from autoslug import AutoSlugField
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __unicode__(self):
return self.user.username
-forms.py
from django import forms
from django.forms import ModelForm
from tentagarden.models import UserProfile
from django.contrib.auth.models import User
from parsley.decorators import parsleyfy
#parsleyfy
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
-views.py
from django.shortcuts import render_to_response, render, redirect
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from tentagarden.forms import UserForm, UserProfileForm
def home(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render_to_response(
'tentagarden/home.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
-admin.py
from django.contrib import admin
from .models import File, Post, UserProfile
admin.site.register(File)
admin.site.register(Post)
admin.site.register(UserProfile)
And I'd like to have the User data (so First name, Last name and Email) visualized in "User profiles" (in the Admin page), other than in "Users" only.
What should I do?
Thank you!
Put this is in your admin.py
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('email', 'first_name', 'last_name', 'website')
search_fields = ('user__username', 'user__first_name', 'user__last_name', 'user__email')
# list_filter = ('some_field_to_filter')
readonly_fields = ('email', 'first_name', 'last_name')
def email(self, obj):
return obj.user.email
def first_name(self, obj):
return obj.user.first_name
def last_name(self, obj):
return obj.user.last_name
admin.site.register(UserProfile, UserProfileAdmin)
Use fieldsets to control the order of displayed fields in edit view.

Categories

Resources