custom user registration form in django - django

I've created custom user registration form for django, but it's not working :-(
I've created LOGINSYS app to manipulate Users (Login, Profile page, Registration)
My forms.py looks like this:
#-*- coding:utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from datetime import date, timedelta
class MyRegistrationForm(UserCreationForm):
def get_image_path(self, filename):
path = ''.join([date.today().strftime('../static/user_image/%Y/%m/%d/'), translit.slugify(filename), ".jpg"])
return path
first_name = forms.CharField (required = True)
last_name = forms.CharField (required = True)
telephone = forms.CharField (required = True)
email = forms.EmailField (required = False)
#user_image = forms.ImageField(path = get_image_path, required = False, allow_empty_file = True )
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'telephone', 'email')
def save (self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.telephone = self.cleaned_data['telephone']
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data["password1"])
#user.user_image = self.cleaned_data['user_image']
if commit:
user.save()
my views.py looks like:
#-*- coding:utf-8 -*-
from django.shortcuts import render, render_to_response, redirect
from django.http.response import HttpResponse
from django.http import HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context
from django.template import RequestContext
from advert.models import Advert, AdvertCategory, AdvertSection
from django.core.exceptions import ObjectDoesNotExist
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator
from datetime import date, timedelta
from PIL import Image
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.contrib import auth
from django.contrib.auth.forms import UserCreationForm
from loginsys.forms import MyRegistrationForm
def register(request):
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
if request.POST:
newuser_form = MyRegistrationForm(request.POST)
if newuser_form.is_valid():
username = newuser_form.cleaned_data['username']
password = newuser_form.cleaned_data['password1']
#password2 = newuser_form.cleaned_data['password2']
first_name = newuser_form.cleaned_data['first_name']
last_name = newuser_form.cleaned_data['last_name']
telephone = newuser_form.cleaned_data['telephone']
email = newuser_form.cleaned_data['email']
newuser_form.save()
newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2'])
auth.login(request, newuser)
return redirect('/')
else:
args['reg_form'] = newuser_form
return redirect('/')
Unfortunately when i register on front-end it doesn't do anything :-(
Please help me

Your code does not render the form, see the usage of render in this example.
I recommend using django-auth-tools for building your own custom user model. It supplies basic models, views and forms which can be easily extended.

When you override the method save using 'super', you have to use the MyRegistrationForm, but not(!) superclass UserCreationForm.
Rewrite class method accordingly:
class MyRegistrationForm(UserCreationForm):
...
def save (self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
...

Related

how create a #username by taking username from registration form

i have setup the forms in the frontend what i want is that any User if gives his username for example username-> helloworld then it is interpreted as #helloworld and then this form with changed #username should be saved in the database so that i can use it afterwards.....
i am a noob in django framework .
i have been trying since last 2 days to find a answer here and by using google but unable to find a helpful answer
here is my ->forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
this is my -> views.py file
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from .forms import SignUpForm
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
UserModel = get_user_model()
#index and signin def have been removed because it is out of context of question
def signup(request):
if request.user.is_authenticated:
return redirect('index')
else:
form = SignUpForm()
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
User.username = "#{}".format(User.username)
user.is_active = False
user = form.save
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your account.'
message = render_to_string('activation_mail.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse('Please confirm your email address to complete the registration')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
Just override your form's save method to alter the data before saving.
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['first_name','last_name','username', 'email', 'password1', 'password2']
def save(self, *args, **kwargs):
self.instance.username = f"#{self.instance.username}"
return super().save(*args, **kwargs)

User register page using (contrib.auth.models User) but facing Not Null Constraint Error

I am first to Django.
I am making a registeration form only to facing NOT NULL constraint failed: blog_userprofile.user_id.
i have been trying to figure out but i can not. Thank you for any help:)
This is my models.py file
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.PROTECT,blank=True)
def __str__(self):
return self.user.name
This is my forms.py file
from django import forms
from .models import Post,Comment,UserProfile
class UserProfileForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
username = forms.CharField(max_length=200)
email = forms.EmailField()
class Meta():
model = UserProfile
fields = ['username','email','password']
And this is my views.py file
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect,HttpResponse
from django.urls import reverse_lazy,reverse
from django.views.generic import (TemplateView,ListView,DetailView)
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from .models import Post,Comment,UserProfile
from .forms import PostForm,CommentForm,UserProfileForm
def register(request):
registered = False
if request.method == 'POST':
user_form = UserProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
return HttpResponseRedirect(reverse('blog:user_login'))
else:
print('unvalid imformation')
else:
user_form = UserProfileForm()
return render(request,'register/registration.html',{'user_form':user_form, 'registered':registered})
And this comment shows up
IntegrityError at /signup/
NOT NULL constraint failed: blog_userprofile.user_id
If you get an existing user from your database you can use
user_form = UserProfileForm(request.POST, instance=a)
Or you can try this code
if request.method == 'POST':
# If you get an existing user from your database you can use
#user_form = UserProfileForm(request.POST, instance=a)
user_form = UserProfileForm(request.POST)
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user.password)
user.save()
registered = True
return HttpResponseRedirect(reverse('blog:user_login'))

How to setup registration and signals in django 2.0

Can someone help me figure out what i am doing wrong trying to setup authentication and signals to work along with the models created in django 2.0.
models.py
from django.db import models
from django.conf import settings.AUTH_USER_MODEL
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
bio = models.TextField(foo)
location = models.CharField(foo)
# Override save method
# Run after the method is saved to add signal functionality below
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
else:
instance.profile.save()
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.forms import ModelForm
from .models import Profile
Profile = get_user_model()
class UserRegisterForm(forms.ModelForm):
email = forms.EmailField(foo)
first_name = forms.CharField(foo)
last_name = forms.CharField(foo)
password = forms.CharField(foo)
password2 = forms.CharField(foo)
class Meta:
model = Profile
fields = [
'username',
'first_name',
'last_name',
'email',
'password1',
'password2'
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from .forms import UserRegisterForm
from .models import Profile
from django.conf import settings
def register(request):
next = request.GET.get('next')
form = UserRegisterForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
new_user = authenticate(username=user.username, password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect('accounts:login')
context = {
'form': form,
}
return render(request, "accounts/register.html", context)
Foo = just a placeholder
The code above create the user but not the profile associated to it.
Any help would be much appreciated.

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.

How to edit following Django Moellform

new to django. I am building a form for user to save to the database. the save to database part is working. However, I want to be able to view and edit the data on two separate template. let's call them view_self_eval.html and edit_self_eval.html. I am stuck.
following is my code for Models.py, Forms.py and View.py for the particular form
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.forms import ModelForm
class self_eval(models.Model):
Owner = models.OneToOneField(User, on_delete=models.CASCADE, default=None)
First_Name = models.CharField(max_length=100, default=None)
Last_Name = models.CharField(max_length=100, default=None)
Current_Role = models.CharField(max_length=100)
My_Strengths = models.CharField(max_length=1000)
Improvement = models.CharField(max_length=4000)
Goals = models.CharField(max_length=4000)
Profesional_Certification = models.CharField(max_length=4000)
Important_discussion = models.CharField(max_length=4000)
def __str__(self):
return self.Owner.username
def create_self_eval(sender, **kwargs):
if kwargs['created']:
self_eval = self_eval.objects.create(user=kwargs['instance'])
post_save.connect(create_self_eval, sender=User)
Forms.Py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from accounts.models import self_eval
class SelfEvalForm(forms.ModelForm):
class Meta:
model = self_eval
fields=(
'First_Name',
'Last_Name',
'Current_Role',
'My_Strengths',
'Improvement',
'Goals',
'Profesional_Certification',
'Important_discussion'
)
def save(self, commit=True):
self_eval = super(SelfEvalForm, self).save(commit=False)
self_eval.First_Name = self.cleaned_data['First_Name']
self_eval.Last_Name = self.cleaned_data['Last_Name']
self_eval.Current_Role = self.cleaned_data['Current_Role']
self_eval.My_Strengths = self.cleaned_data['My_Strengths']
self_eval.Improvement = self.cleaned_data['Improvement']
self_eval.Goals = self.cleaned_data['Goals']
self_eval.Profesional_Certification = self.cleaned_data['Profesional_Certification']
self_eval.Important_discussion = self.cleaned_data['Important_discussion']
if commit:
self_eval.save()
return self_eval
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm,
SelfEvalForm,
EditSelfEvalForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .models import self_eval
from django.views.generic import UpdateView
def self_eval(request):
if request.method == 'POST':
form = SelfEvalForm(request.POST)
if form.is_valid():
#save form data to DB
instance = form.save(commit=False)
instance.Owner=request.user
instance.save()
return redirect(reverse('accounts:self_eval'))
else:
form = SelfEvalForm()
args = {'form': form}
return render(request, 'accounts/self_eval_form.html', args)
def edit_self_eval(request, Owner_id):
self_eval = get_object_or_404(self_eval, pk=Owner_id)
if request.method == 'POST':
form = SelfEvalForm(request.POST, instance=Current_Role, Owner=request.user)
if form.is_valid():
self_eval = form.save()
else:
form = SelfEvalForm(intance=self_eval, Owner=request.user)
args = {'form':form,
'Current_Role':Current_Role
}
return render(request, 'accounts/edit_self_eval.html', args)