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
Related
Hi im trying to add a DOB field to my django project but I keep getting this error but i cant find where to find it
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\urls.py", line 2, in <module>
from . import views
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\views.py", line 13, in <module>
from .forms import CreateUserForm
File "C:\Users\Ugur\Documents\Reply\Replyproject\accounts\forms.py", line 9, in <module>
class CreateUserForm(UserCreationForm):
File "C:\Users\Ugur\Anaconda3\envs\ECS639U\lib\site-packages\django\forms\models.py", line 276, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (dateofbirth) specified for User
My Forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'dateofbirth']
My views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
from .models import *
from .forms import CreateUserForm
def registerPage(request):
if request.user.is_authenticated:
return redirect('/home')
else:
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 created for ' + user)
return redirect('/login')
context = {'form':form}
return render(request, 'accounts/register.html', context)
def loginPage(request):
if request.user.is_authenticated:
return redirect('/home')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/home')
else:
messages.info(request, 'Username OR password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def logoutUser(request):
logout(request)
return redirect('/login')
#login_required(login_url='/login')
def home(request):
context = {}
return render(request, 'accounts/dashboard.html', context)
My models.py
from django.db import models
# Create your models here.
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
dateofbirth= models.CharField(max_length=200, null=True)
creditcard = models.CharField(max_length=16, null = True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
The console I cant understand where the issue is located to change to add the label onto the register area any help is fully thank have a good afternoon :)
In your forms, you specified a field for Modal = User, but your Class called Customer. When you say modal = User Django tries to use own User Modal which does not have dateofbirth field.
I am new to Django, I tried to create a new models forms but while running my server i got this error:
(The form should add a "number" to the Profile database) Thanks for helping
(The form should add a "number" to the Profile database) Thanks for helping
File "C:\Users\xxx\PycharmProjects\web_lead_app\venv\lib\site-packages\django\forms\models.py", line 266, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (number) specified for User
views.py
from .forms import UserRegisterForm, ProfileUpdateForm, UserUpdateForm
from django.contrib.auth.decorators import login_required
#login_required()
def profile(request):
u_form = UserUpdateForm()
p_form = ProfileUpdateForm()
context = {
"u_form": u_form,
"p_form": p_form
}
return render(request, "users/profile.html", context)
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 UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["email", "number"]
class ProfileUpdateForm(forms.ModelForm):
number = forms.CharField(max_length=100)
class Meta:
model = Profile
fields = ["number"]
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
number = models.CharField(max_length=100)
def __str__(self):
return f"{self.user.username} Profile"
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["email"]
Their is no number field in User model. So remove from form.
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().
I have a contact form/model in Django that isn't showing up on the admin management page.
I have no idea why it isn't showing up, I have tried to debug by running migrations, and also renaming some of the model variables.
models.py
from django.db import models
class Contact(models.Model):
their_name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
message = models.CharField(max_length=500)
def __str__(self):
return self.name
forms.py
from django import forms
class ContactForm(forms.Form):
their_name = forms.CharField(label='Name', max_length=100)
email = forms.EmailField(label='Email', max_length=100)
message = forms.CharField(label='Message', max_length=500, widget=forms.Textarea(attrs = {'id': 'Message_form'}))
admin.py
from django.contrib import admin
from .models import Contact
admin.register(Contact)
views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from .models import Contact
from .forms import ContactForm
...
def contact(request):
valid_input = 'no input'
if request.method == 'POST':
valid_input = 'invalid input'
TheForm = ContactForm(request.POST)
if TheForm.is_valid():
valid_input = 'valid input'
name = TheForm['name']
email = TheForm['email']
message = TheForm['message']
Contact.objects.create(name=name, email=email, message=message)
else:
TheForm = ContactForm()
return render(request, 'BlogHome/pages/contact.html', {'TheForm': TheForm, 'valid_input': valid_input})
Could this be the way I am importing the model? I have no idea what is causing this problem.
In your admin.py create an admin class for your Contact model and after register this model in admin using that class.
class ContactAdmin(admin.ModelAdmin):
list_display = ('id', 'their_name', 'email', 'message')
admin.site.register(Contact, ContactAdmin)
Could someone smart explain me please where I have a bug?
I get this error when I would like to send a profile user form
NOT NULL constraint failed: userprofile_userprofile.godzina_id
I have an app "userprofile"
forms.py
from django import forms
from models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('imie', 'godzina')
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.conf import settings
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'user_profile.html', args)
models.py:
from django.db import models
from django.contrib.auth.models import User
from godzina.models import Godzina
class UserProfile(models.Model):
user = models.OneToOneField(User)
imie = models.CharField(max_length=150)
godzina = models.ForeignKey('godzina.Godzina')
User.profile = property(lambda u:UserProfile.objects.get_or_create(user=u)[0])
You could add null=True to your godzina attribute:
godzina = models.ForeignKey('godzina.Godzina', null=True)