User creation form in Django - django

I am taking online Djago class and have no one to ask for help. I would appreciate to get any help and tips.
I am learning creating forms (login/singup).
So far i did in models.py
from django.db import models
from django.contrib import auth
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
In forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['email'].label = 'Email Address'
I want to add addtional firelds as surname , however when i add 'surname' in class meta in fields (forms.py) i get error, however the online training says i can easily add additional fields. Could you please tell what i am doing wrong and how i can add this field?
when i add those field 'surname' in forms.py:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'
it give the following error:
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (surname) specified for User
In views.py i ahve:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView,TemplateView
from . import forms
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

# In your forms.py, you need to add new field 'surname'
For Example:-
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
surname = forms.CharField(max_length=20)
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'

First of all you are using the get_user_model() method but you are working with a custom User model.
In you settings set AUTH_USER_MODEL:
AUTH_USER_MODEL = 'app.User'
Then add the surname field to your User model:
class User(auth.models.User):
surname = models.Charfield()
def __str__(self):
return "#{}".format(self.username)
Run and apply migration. Then you will be able to add the surname field to your form fields
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'

You need to make following changes to your forms.py file:-
from appname.models import USER
from django.contrib.auth.forms import UserCreationForm
class UserCreateForm(UserCreationForm):
class Meta:
fields = ('username','email','surname','password1','password2')
model = USER
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name'
self.fields['surname'].label = 'Surname'
self.fields['email'].label = 'Email Address'

Related

Cannot assign "<User: someuser>": "UserProfileInfo.user" must be a "User" instance

[enter image description here][1]I don't know what is causing this error but i couldn't find any solution for this. i checked everything and everything seems to be fine but i don't know why this error is occuring.
Views.py
from django.contrib.auth import get_user_model
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView,FormView
from . import forms
# Create your views here.
def signup(request):
if request.method =='POST':
user_create_form = forms.UserCreateForm(data=request.POST)
user_profile_form = forms.UserProfileInfoForm(data=request.POST)
if user_create_form.is_valid() and user_profile_form.is_valid():
user = user_create_form.save()
user.save()
profile = user_profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
else:
print(user_create_form.errors,user_profile_form.errors)
else:
user_create_form = forms.UserCreateForm()
user_profile_form = forms.UserProfileInfoForm()
return render(request,'accounts/signup.html',{'user_create_form':user_create_form,
'user_profile_form':user_profile_form})
Models.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)
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
Contact_number = models.IntegerField(blank=True)
joined_at = models.DateTimeField(auto_now=True)
profile_pic = models.ImageField(upload_to='profiles',blank=True)
def __str__(self):
return self.user.username + ' Profile'
Forms.py
from django.contrib.auth import get_user_model # this gets the model that is in the application
from django import forms
from django.contrib.auth.forms import UserCreationForm
from . import models
class UserCreateForm(UserCreationForm):
class Meta():
fields = ('username','email','password1','password2',)
model = get_user_model()
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].label = 'Display Name' # to set up a custom label for the field
self.fields['email'].label = "Email Address"
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model = models.UserProfileInfo
fields = ('Contact_number','profile_pic')
I am getting this error no matter what i do, i tried referencing other similar questions but couldn't find any solution for this error. pls help me out on this one.
Thanks in Advance !
image of the error
[1]: https://i.stack.imgur.com/HOcmf.png
You can overwrite save() method in your model to return a model instance after saving an object, for example:
class YourModel(models.Model):
name = models.CharField(max_length=20)
def save(self, *args, **kwargs):
super(YourModel, self).save(*args, **kwargs)
return self
your_model_saved_instance = YourModel(name='example').save()
Then you will receive an instance from the user class instead of the form class
user = user.save()

Django email address not showing in admin

I'm trying to create a simple email and name collector , everything looks fine but I can only see the name option in the admin site the email option is not there
admin page model
Here is my code
Forms.py
from django import forms
from sonus import models
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label="Your Name",max_length=20)
your_email = forms.EmailField(label="Email",max_length=100)
Here Goes my Views.py
def get_name(request):
person = Person()
if request.method=="POST":
form = NameForm(request.POST)
if form.is_valid():
person.name = form.cleaned_data['your_name']
person.email = form.cleaned_data['your_email']
person.save()
return HttpResponseRedirect(reverse('index'))
else:
form = NameForm()
return render(request,'form.html',{ 'form': form })
My Admin.py
from django.contrib import admin
from django.contrib.admin.decorators import display
from django.contrib.auth.admin import UserAdmin
from .models import Details, Person,list
from sonus import models
# Register your models here.
admin.site.register(Person)
Here is the model
class Person(models.Model):
name = TextField(max_length=20)
email = EmailField(max_length=100)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('person',kwargs={'pk': self.pk})
In your admin.py change your code to that :
class PersonAdmin(admin.ModelAdmin):
list_display = ('name', 'email',)
admin.site.register(Person, PersonAdmin)

I am trying to create custom user registration form

I am getting this error.Below mentioned code is for forms.py
forms.py
from django import forms
from dappx.models import UserProfileInfo
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username','password','email']
class UserProfileInfoForm(forms.ModelForm):
class Meta:
model = UserProfileInfo
fields = ['portfolio_site','profile_pic']
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
"""
Form class to register a new user
"""
def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
class Meta:
model = User
fields = ['username','password','email']
I found this tutorial a good reading source

Exception Value:NOT NULL constraint failed: auth_user.username

I am creating a project to register and view profile using Django.
The problem is when I am trying to register a new user I am getting some errors
NOT NULL constraint failed: auth_user.username
Here is my form.py and view.py file:
form.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
class FileDataForm(forms.Form):
name = forms.CharField(max_length=50)
file = forms.FileField()
image = forms.ImageField()
class userregister(UserCreationForm):
first_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
last_name = forms.CharField(max_length=50, required = False ,help_text ='optional')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password1', 'password2', )
class editprofileform(UserChangeForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email','password')
View.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect,render_to_response
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from .models import FileData
from .forms import FileDataForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .forms import userregister,editprofileform
from django.contrib.auth.forms import UserChangeForm , PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
# Create your views here.
#login_required
def home(request):
return HttpResponse('<h1>Welcome to your first page<h1>')
def registration(request):
print request
print 'request'
if request.method == 'POST':
#save the user data
form = userregister(request.POST)
print form.errors
print 'here'
if form.is_valid():
print 'i am here'
form.save()
return render(request , 'registration/success.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' ,{'form' : form,} )
else:
form = userregister()
return render(request , 'registration/register.html' , {'form': form,})
models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length = 100,default='')
city = models.CharField(max_length =30)
mobile = models.IntegerField(default=0)
def create_profile(sender , **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user = kwargs['instance'])
post_save.connect(create_profile , sender=User)
error:
Exception Value:
NOT NULL constraint failed: auth_user.username
In your form.py file, try inserting 'username' as the first element in the 'fields' list. It looks like you're not using that in the form so when you submit, it's leaving the username null.

Using CustomUser as author giving problem with database?

I am a little stuck, i am using CustomUser in settings (AUTH_USER_MODEL = 'users.CustomUser') and i want to use the username as author in comments.
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
text = models.TextField()
when i run the migrations, it gives me this error
return self.cursor.execute(sql, params) django.db.utils.DataError:
invalid input syntax for integer: "Alandivar"
Alandivar being my superuser username in devmode,
so how can i make it so when a customer put a comment in (requires login), the username is automatically used as author
regards
customuser form
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
from django import forms
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
customuser model
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
class CustomUserManager(UserManager):
pass
class CustomUser(AbstractUser):
objects = CustomUserManager()
customuser view
from django.urls import reverse_lazy
from django.views import generic
from .forms import CustomUserCreationForm
class SignUp(generic.CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'