models.py and views.py may be conflicting - python

Below are the output of the models.py
from django.db import models
from django.core.urlresolvers import reverse
#from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Registration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length = 250)
password = models.CharField(max_length = 250)
email = models.CharField(max_length = 250)
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Registration.objects.create(username=instance)
instance.registration.save()
Below is the output of the views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from .forms import SignUpForm
from django.views import generic
class IndexView(generic.View):
templet_name = 'user_info/index.html'
def signupview(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('registration_form.html')
else:
form = SignUpForm()
return render(request,'user_info/registration_form.html', {'form': form})
I have two questions:
1) In my models.py I have 4 fields, 'user','username','password','email'. In my first field "user", I guess, I shouldn't be using "models.OneToOneField(User, on_delete=models.CASCADE)", because, as per my understanding, it's used when we have a primary key and foreign key in working. Please correct me if I am wrong.
2) in my views.py, the function "signupview", I am saving the form in the database through form.save(), and then cleaned the data. have I done the right thing, as my models.py has 4 fields, but in view.py , I am giving only two fields
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password')
I hope I am making sense here. I am getting an error while creating a superuser through
python manage.py createsupseruser
Below is the error
django.db.utils.IntegrityError: NOT NULL constraint failed: user_info_registration.user_id
That is why I am asking these questions.
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django import forms
#from django.forms import ModelForm
class SignUpForm(UserCreationForm):
#first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
#last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username','password1','email')
Latest look of models.py:
from django.db import models
from django.contrib.auth.models import User
class Registration(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)

The reason you get the error is that the User post save signal tries to create a Registration instance, but you don't supply values for all the required fields.
#receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created:
Registration.objects.create(username=instance)
instance.registration.save()
You either have to remove this signal handler or you have to provide valid arguments to Registration.objects.create().

Related

Django save user and profile with signals

Im still learning Django and I am stuck at user registration / profile creation.
My goal
So, the purpose of this is to save the new user and at the same time save the profile of the new user with de data from the form. I use 2 forms u_form and p_form.
What I have done so far:
Created model Profile with OneToOneField to User
Created 2 forms for User (u_form) and Profile (p_form)
Created signals.py to create new Profile when new User is created
In the view I have create function with u_form.save()
Problem
This works, but the new Profile is completely empty.. When I put p_form.save() in my view it gives me this error:
NOT NULL constraint failed
The code
models.py
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)
voorletter = models.CharField(max_length=10)
voorvoegsel = models.CharField(max_length=10)
achternaam = models.CharField(max_length=200)
depers = models.CharField(max_length=25)
depersoud = models.CharField(max_length=25)
telefoonnummer = models.CharField(max_length=25)
class Meta:
verbose_name = "Collega"
verbose_name_plural = "Collega's"
def __str__(self):
return self.depers
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
views.py
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from gebruikers.forms import UserRegisterForm, ProfileRegisterForm
def gebruiker_create(request):
if request.method == "POST":
u_form = UserRegisterForm(request.POST)
p_form = ProfileRegisterForm(request.POST)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
messages.success(request, f'Account is aangemaakt.')
return redirect('login')
else:
u_form = UserRegisterForm()
p_form = ProfileRegisterForm()
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/register.html', context)
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email")
password1 = forms.CharField(widget=forms.TextInput(attrs={'type':'password'}), label="Wachtwoord", help_text=None)
password2 = forms.CharField(widget=forms.TextInput(attrs={'type':'password'}), label="Wachtwoord herhalen", help_text=None)
class Meta:
model = User
fields= ['username', 'email', 'password1', 'password2']
class ProfileRegisterForm(forms.ModelForm):
voorletters = forms.CharField(label="Voorletters", max_length=10)
voorvoegsel = forms.CharField(label="Voorvoegsel", max_length=50)
achternaam = forms.CharField(label='Achternaam', max_length=100)
depers = forms.CharField(label='Depers', max_length=8)
depersoud = forms.CharField(label='Oude Depers', max_length=50)
telnummer = forms.CharField(label="Telefoonnummer", max_length=20)
class Meta:
model = Profile
fields = ['voorletters', 'voorvoegsel', 'achternaam', 'depers', 'depersoud', 'telnummer']
If you want Profile fields to be empty initially just add blank=True in every model fields except for user .
voorletter = models.CharField(max_length=10, blank=True)
.....
.....
.....
telefoonnummer = models.CharField(max_length=25, blank=True)
Then run makemigrations and migrate command to successfully make the changes in the database.
it will solve NOT NULL constraint failed error

How to resolve this UNIQUE constraint failed: auth_user.username

I need to register a user and use it's email as Username. I am getting this error (UNIQUE constraint failed: auth_user.username) when trying to register on the page. I AM NEW TO DJANGO AND PYTHON
My Code is
forms.py File
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from phonenumber_field.formfields import PhoneNumberField
from django.db import transaction
from .models import User
class UserRegistrationForm(UserCreationForm):
name = forms.CharField(max_length=60)
# Username = forms.CharField(max_length=15)
email = forms.EmailField()
class Meta(UserCreationForm.Meta):
models = User
fields = ['name','email','password1','password2']
views.py file
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import UserRegistrationForm
from django.contrib.auth import get_user_model
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
User = form.save()
else:
form = UserRegistrationForm()
return render(request, 'users/signup.html', {'form': form})
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""docstring for User"""
email = models.EmailField(verbose_name='Email Address', unique=True)
name = models.CharField(max_length=50)
USERNAME_FIELD = 'email'
user_permissions = None
groups = None
REQUIRED_FIELDS = []
def __str__():
return self.name

UNIQUE constraint failed: new__users_profile.user_id. Python Django

django.db.utils.IntegrityError UNIQUE constraint failed
sqlite3.IntegrityError: UNIQUE constraint failed: new__users_profile.user_id
The above exception was the direct cause of the following exception:
new__users_profile.user_id
Error occurs when I'm trying to register new user, login to an existing user and when I am trying to migrate. I've tried to delete all migrations and migrate once again but it didn't help
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, null=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
class Media(models.Model):
image_name = models.CharField(max_length=50)
image_description = models.CharField(max_length=80)
image_image = models.ImageField(upload_to='media', default='default.jpg')
views
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, MediaForm
from .models import Media
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.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()
return render(request, 'users/register.html', {'form': form})
#login_required
def profile(request):
if request.method == 'GET':
media_images = Media.objects.all()
context = {
'media_images':media_images,
}
return render(request, 'users/profile.html', context)
#login_required
def add_media(request):
if request.method == 'POST':
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('http://127.0.0.1:8000/')
else:
form = MediaForm()
return render(request, 'users/add_media.html', {'form':form})
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import *
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class MediaForm(forms.ModelForm):
class Meta:
model = Media
fields = ['image_name', 'image_description', 'image_image']
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
I think you need primary_key=True,
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, null=True)
In class profile, add primary_key=True and remove null=True
user = models.OneToOneField(User,primary_key=True, on_delete=models.CASCADE)
I hope it will work!

form not saving email in django admin

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']

Extending User model in django

I am trying to register a user in django extending the auth module. I read from here and there and now I am all over the place and dont know what I am doing.
Initially what I wanted to do is register a user with information name, email, mobile and password. since mobile is not in the default django auth I tried to extend auth.
here is the code.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class CustomerUserProfile(models.Model):
mobile = models.CharField(max_length = 20)
user = models.ForeignKey(User, unique=True)
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = CustomerUserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from neededform.models import CustomerUserProfile
class CustomerRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
mobile = forms.CharField(max_length = 20)
class Meta:
model = User
fields = ('username','email','mobile','password1','password2')
views.py
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.context_processors import csrf
from neededform.forms import CustomerRegistrationForm
from neededform.models import CustomerUserProfile
from django.contrib.auth.models import User
def register(request):
if request.method == 'POST':
form = CustomerRegistrationForm(request.POST)
if form.is_valid():
f = form.save()
return HttpResponseRedirect('/registered/')
else:
args = {}
args.update(csrf(request))
args['form'] = CustomerRegistrationForm()
return render_to_response('User_Registration.html', args ,context_instance = RequestContext(request))
This code upon execution makes an entry in auth_user table and an entry in CustomerUserProfile but the mobile coloumn is blank always.
what else am I suppose to add in the code ?
PS. please can some one explain me what is this code doing
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = CustomerUserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
as I copied it from somewhere I want to know how this works actually.
Thank you.
This is a 2-year old question but I am surprised that there was no correct answer.
The mobile field is not saved in your profile, simply because you create your CustomerUserProfile via the post_save signal, and the mobile field is not forwarded by the post_save signal.
I would suggest to simply update your CustomerUserProfile when you handle form.is_valid() in your register function.

Categories

Resources