I have this problem:::
IntegrityError at /addproject/
NOT NULL constraint failed: BekanSite_project.owner_id. I do not know how I can fix this problem.
This is my model ::
from django.db import models
from django import forms
from django.contrib.auth.models import User
from django.core.validators import URLValidator
class Project(models.Model):
project_name = models.CharField(verbose_name='Имя
проекта',max_length=200, default='')
project_cost = models.IntegerField(verbose_name='Сумма
инвестиции',default='')
investor = models.IntegerField(verbose_name='Долья
инвестерa',default='')
email = models.EmailField(verbose_name='Почта',max_length=50,
default='')..other fields
owner = models.ForeignKey(User)
def __str__(self):
return self.owner
views.py
#login_required
def addproject(request):
if request.POST:
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
form.owner = request.user
addproject = form.save()"<<<<where it fails"
addproject.save()
return HttpResponseRedirect(reverse('accounts:profile'))
else:
form = ProjectForm()
return render(request, 'BekanSite/addproject.html',
{'form':form,'username':auth.get_user(request).username})
forms.py
from django.db import models
from django import forms
from .models import Project
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from PIL import Image
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_name','project_cost',...(other fields),]
I think it is somehow related to ForeignKey. Please help. Thanks beforehand.
You might want to attach the user before you check form is valid:
if request.POST:
form = ProjectForm(request.POST, request.FILES)
form.owner = request.user
if form.is_valid():
addproject = form.save()"<<<<where it fails"
addproject.save()
return HttpResponseRedirect(reverse('accounts:profile'))
And you dont have to call addproject.save() since form.save() does that already.
I have solved it. I don't know how it works, but I just added commit=False addproject = form.save(commit=False). I found it in the book "python-crash-course-a-hands-on-eric-matthes ". now it works.Also Thank you RajKris for your effort to solve this problem.Good luck.
Related
I've been learning Django and I'm trying to understand how to extend some of the built-in functionality. To do that I've referenced Customizing Authentication in Django and tried to implement the instructions I've found there in a standard django-admin project.
The problem is that when I try to save the form to the database (sqlite3 included db), nothing is recorded. The form passes the is_valid check, but when I check the database however, nothing has been added to either my user or patients tables.
Hoping someone can point out where this is going wrong, thank you.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
isPatient = models.BooleanField(default=False)
class Patient(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
age = models.PositiveIntegerField()
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from .models import *
class RegisterPatient(UserCreationForm):
age = forms.IntegerField()
class Meta:
model = User
fields = UserCreationForm.Meta.fields + ("age")
#transaction.atomic
def save(self, commit=True):
user = super(RegisterPatient, self).save(commit=False)
user.isPatient = True
user.save()
patient = Patient.objects.create(user=user)
patient.firstName.add(*self.cleaned_data.get('age'))
patient.save()
views.py
def register(response):
form = RegisterPatient(response.POST)
if form.is_valid():
print("is Valid") # < Code reaches here
form.save
return redirect("/")
settings.py
AUTH_USER_MODEL = 'main.User'
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from . models import User
admin.site.register(User, UserAdmin)
You need to replace form.save with form.save(). The latter calls the save function, whereas the former does not.
i want to add user profile section for example superuser and simple_user so i can add permissions
But When I Submit my Registration Form I Get This Error:
AttributeError at /register/
'User' object has no attribute 'register'
How To Fix And Save User Profile Name?
Here is my Views.py
from django.shortcuts import render , get_object_or_404,redirect
from django.utils import timezone
from blog.models import *
from blog.forms import *
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
def user_register(request):
if request.method == "POST":
reg = register(request.POST or None)
if reg.is_valid():
user = reg.save()
user.profile = "simple_user"
user.set_password(user.password)
user.save()
else:
print(register.errors)
else:
reg = register()
return render(request,"registration/register.html",{'reg':reg})
Here is my Models.py
class register(models.Model):
user = models.OneToOneField(User,on_delete="Cascade", related_name="profile")
Here is my Forms.py
class register(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input-field'}))
class Meta():
model = User
fields = ('username','email','password')
Here is the Error Image:
Any Help Appreciated!
try this
user = reg.save()
p1 = register(user=user, #other colums if have) # register model
p1.save()
# user.profile = "simple_user"
user.set_password(user.password)
user.save()
hope it helps
I've been trying creating a user profile form using built-in User of django.contrib.auth.models. Everything is working fine but after filling the fields into the form(which is displaying), I am encountering an INTEGRITY ERROR AT / saying NOT NULL CONSTRAINT failed.
You can see this image using this link to know exactly what the error is showing.
This is my models.py file
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, null=True)
phone_number = models.PositiveIntegerField(validators=
[MaxValueValidator(9999999999)],blank=True)
def __str__(self): #This will print out this model
return self.user.username
This is my forms.py file.
from django import forms
from django.contrib.auth.models import User
from Login_Signup_Form.models import UserProfileInfo
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model=User
fields=('first_name','last_name','username','email','password',)
class UserProfileForm(forms.ModelForm):
class Meta:
model=UserProfileInfo #this is model
fields=('phone_number',)
This is my views.py file.
from django.shortcuts import render
from Login_Signup_Form.forms import UserForm,UserProfileForm
from Login_Signup_Form.models import UserProfileInfo
# Create your views here.
def index(request):
return render(request,'base.html')
def register(request):
registered=False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
user_phone_number=UserProfileForm(data=request.POST)
if user_form.is_valid() and user_phone_number.is_valid():
user=user_form.save()
user.set_password(user.password)
user.save()
phone = user_phone_number.save()
phone.user=user
else:
#Printing the errors
print(user_form.errors,user_phone_number.errors)
else:
user_form = UserForm()
user_phone_number = UserProfileForm()
return render(request, 'base.html',{'user_form':user_form, '
phone_number':user_phone_number})
The error probably comes from an empty phone number in your form. You allow an empty phone_number in your form with blank=True but you don't allow it on the database level, you need to add null=True as well:
phone_number = models.PositiveIntegerField(validators=
[MaxValueValidator(9999999999)], blank=True, null=True)
See this great answer.
With blank=True the field is not required and the form will validate but it will raise the integrity error because null=True is not here. That wouldn't happen with a CharField though, the blank value would be stored as empty string. This only happens because of the PositiveIntegerField.
models.py
from django.db import models
from accounts.models import User
# Create your models here.
class Customer(models.Model):
user_customer = models.OneToOneField(User)
customer_name = models.CharField(max_length=100,blank=True)
phone_no = models.CharField(max_length=100,blank=True)
inserted = models.DateTimeField(auto_now_add=True,null=True,blank=True)
created = models.DateTimeField(auto_now=True,)
views.py
from django.shortcuts import render,redirect
from django.views.generic.edit import CreateView
from accounts.models import User
from accounts.forms import RegisterForm
from .forms import CustomerRegistration
from .models import Customer
def CustomerSignupView(request):
r_form = RegisterForm(request.POST or None)
c_form = CustomerRegistration(request.POST or None)
context = {
"r_form":r_form ,
"c_form":c_form ,
}
if r_form.is_valid() and c_form.is_valid():
instance = r_form.save(commit=False)
instance.is_customer = True
instance.save()
c_form.save()
return redirect("/")
return render(request,"customerregister.html",context)
forms.py
from django import forms
from .models import Customer
class CustomerRegistration(forms.ModelForm):
class Meta:
model = Customer
fields = ('customer_name','phone_no',)
I have two separate forms - RegisterationForm(RF) and CustomerRegistrationForm(CRF).
CRF inherits RF, I want to save two forms in single view i.e.CustomerSignupView.
While submitting the forms Intergrity error pops up, and the data saved is only from RegistrationForm.
How do I save both forms in thier respective table with integrity maintained.
Thanks.
You haven't shown your forms, but it looks as if you have to set the user before you save the customer to the database:
if r_form.is_valid() and c_form.is_valid():
instance = r_form.save(commit=False)
instance.is_customer = True
instance.save()
customer = c_form.save(commit=False)
customer.user_customer = instance
customer.save()
return redirect("/")
You have to create a User from accounts.models before creating you Customer, if your r_form is a instance of User your c_form will fail because user is required to c_form be valid
if r_form.is_valid():
instance = r_form.save(commit=False)
instance.is_customer = True
instance.save()
if c_form.is_valid():
customer = c_form.save(commit=False)
customer.user_customer = instance
customer.save()
return redirect("/")
Suggestion: why you not Inherite User to your Customer since your Customer is once User
from accounts.models import User
class Costumer(User):
...
This way you can setup the Costumer and User in just one form, is easy to acess the data from Costumer.
Since django User model had only few fields in it, I made a custom model and used it's ModelForm to save data to User model and the custom model. The models.py is as shown below
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
import datetime
class Post(models.Model):
Author=models.ForeignKey(User)
title=models.CharField(max_length=66)
content=models.TextField()
created_date=models.DateField(default=datetime.datetime.now())
published_date=models.DateField()
def publish(self):
self.published_date=datetime.datetime.now()
self.save()
class UserDetails(models.Model): #the custom model
uname=models.CharField(max_length=55)
first_name=models.CharField(max_length=55)
last_name=models.CharField(max_length=55)
age=models.IntegerField()
contact=models.CharField(max_length=13)
email=models.EmailField()
pword=models.CharField(max_length=55)
modelform :
class RegisterForm(ModelForm):
class Meta:
model=UserDetails
fields=['uname','pword','first_name','last_name','email','contact']
the views.py is like this
from django.shortcuts import render
from .models import UserDetails
# Create your views here.
from django.contrib.auth import authenticate,login,logout
from .forms import RegisterForm,LoginForm,PostForm
from django.contrib.auth.models import User
from django.db import IntegrityError
def register(request):
if request.method=='POST':
form=RegisterForm(request.POST)
try:
if form.is_valid():
form.save()
uname=form.cleaned_data['uname']
fname=form.cleaned_data['first_name']
pword=form.cleaned_data['pword']
email=form.cleaned_data['email']
contact=form.cleaned_data['contact']
lname=form.cleaned_data['last_name']
user=User.objects.create_user(uname,password=pword,email=email)
user.last_name=lname
user.save()
#form.save()
#stuff after registration
message="registration done! login again"
return render(request,'register.html',locals())
except IntegrityError:
message="username already exists!! try another"
else:
form=RegisterForm()
return render(request,'register.html',locals())
The problem is that even if I make a fresh entry to the RegisterForm, the 'message' I get is, username already exists!! try another. The auth.User model is getting updated but UserDetails is not. What am I doing wrong? (spare me if this is a stupid question :) )
update: 1
from django.shortcuts import render
from .models import UserDetails
# Create your views here.
from django.contrib.auth import authenticate,login,logout
from .forms import RegisterForm,LoginForm,PostForm
from django.contrib.auth.models import User
from django.db import IntegrityError
def register(request):
if request.method=='POST':
form=RegisterForm(request.POST)
try:
if form.is_valid():
form.save()
uname=form.cleaned_data['uname']
fname=form.cleaned_data['first_name']
pword=form.cleaned_data['pword']
email=form.cleaned_data['email']
contact=form.cleaned_data['contact']
lname=form.cleaned_data['last_name']
if not User.objects.filter(username=uname,email=email).exists():
user=User.objects.create_user(uname,password=pword,email=email)
user.last_name=lname
user.save()
message="registration done! login again"
return render(request,'register.html',locals())
except IntegrityError:
message="username already exists!! try another"
else:
form=RegisterForm()
return render(request,'register.html',locals())
if form.is_valid():
# save a UserDetails obj (data are automatically get from the form) to db.
form.save()
# Get data from form
uname = form.cleaned_data['uname']
fname = form.cleaned_data['first_name']
pword = form.cleaned_data['pword']
email = form.cleaned_data['email']
contact = form.cleaned_data['contact']
lname = form.cleaned_data['last_name']
# Check if user already exists. If it doesn't, create it
if not User.objects.filter(username=uname, email=email).exists():
user=User.objects.create_user(uname, password=pword, email=email)
#stuff after registration
message = "registration done! login again"
return render(request,'register.html',locals())
See more on the ModelForm's save() method.
However, I noticed that the age model field is required. So, the save() will complain. You should better make it as: age = models.IntegerField(blank=True, null=True) or define a default value like this age = models.IntegerField(default=20). Although, defining a default age is awkward, better follow the blank=True null=True to allow empty ages.
Age was missing in model form Fields