NOT NULL constraint failed: tasks_task.user_id - django

I'm working on a Django project using Python3. I have this error come ups when I'm trying to create a new task.
django.db.utils.IntegrityError: NOT NULL constraint failed: tasks_task.user_id
The web application works fine, but when I try to create a new task is when the error occurs, I have read all the posts related to the problem, but I have not found the solution.
I tried to update my sqlite3, but it didn't work.
This is my code
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from .forms import TaskForm
def home(request):
return render(request, 'home.html')
# Create your views here.
def signup(request):
if request.method == 'GET':
return render(request, 'signup.html', {
'form': UserCreationForm
})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(
username=request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
return redirect('tasks')
except IntegrityError:
return render(request, 'signup.html', {
'form': UserCreationForm,
'error': 'Username already taken'
})
return render(request, 'signup.html', {
'form': UserCreationForm,
'error': 'Passwords did not match'
})
def tasks(request):
return render(request, 'tasks.html')
def create_task(request):
if request.method == 'GET':
return render(request, 'create_task.html', {
'form': TaskForm,
})
else:
try:
form = TaskForm(request.POST)
new_task = form.save(commit=False)
new_task.User = request.user
new_task.save()
return redirect('tasks')
except ValueError:
return render(request, 'create_task.html', {
'form': TaskForm,
'error': 'Bad data passed in. Try again.'
})
def signout(request):
logout(request)
return redirect('home')
def signin(request):
if request.method == 'GET':
return render(request, 'signin.html', {
'form': AuthenticationForm
})
else:
user = authenticate(
request, username=request.POST['username'], password=request.POST['password'])
if user is None:
return render(request, 'signin.html', {
'form': AuthenticationForm,
'error': 'Username and password did not match'
})
else:
login(request, user)
return redirect('tasks')
Here's my models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title + ' | ' + str(self.user)

You seem to be using the wrong attribute name when setting the user. Note that all Python attributes are case sensitive:
class Task(models.Model):
...
user = models.ForeignKey(User, on_delete=models.CASCADE)
but
new_task.User = request.user
Changing it to new_task.user should solve the problem.

Related

Django CRUD - create and update view doesn't work

I'm really new to Django and I want to teach myself by making a simple note. I maked a simple form for creating a new note but I don't know how to make this just for the user is logged in. What I mean is that I want the user field from the creationNoteForm to be removed and the note to be sumbitted automatically for the person who is logged in. Hope that I was clear enough.
Here is my "view.py":
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from .forms import CreateUserForm, CreateNoteForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import *
# Create your views here.
def loginPage(request):
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 pasword is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
def registerPage(request):
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('home')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
def home(request):
if request.user.is_authenticated:
username = request.POST.get('username')
context = {'username': username}
return render(request, 'accounts/home.html', context)
#login_required(login_url='login')
def notes(request):
username = None
if request.user.is_authenticated:
username = request.user.username
user_id = request.user.pk
user_notes = Note.objects.filter(user=user_id)
context = {
'user_notes': user_notes,
'username': username,
#'user_id' : user_id,
}
return render(request, 'accounts/notes.html', context)
def createNote(request):
# username = request.user.username
# user_id = request.user.pk
# user_notes = Note.objects.filter(user=user_id)
form = CreateNoteForm()
if request.method == 'POST':
form = CreateNoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('notes')
context = {
'form': form,
}
return render(request, 'accounts/create_note.html', context)
def deleteNote(request, pk):
note = Note.objects.get(id=pk)
if request.method == 'POST':
note.delete()
return redirect('notes')
context = {'note': note}
return render(request, 'accounts/delete.html', context)
def updateNote(request, pk):
note = Note.objects.get(id=pk)
form = CreateNoteForm(instance=note)
if request.method == 'POST':
form = CreateNoteForm(request.POST, instance=note)
if form.is_valid():
form.save()
return redirect('notes')
context = {'form': form, 'note': note}
return render(request, 'accounts/update.html', context)
"forms.py":
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Note
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class CreateNoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['user', 'title', 'text']
and "models.py" just in case:
from django.db import models
from django.contrib.auth.models import User
class Note(models.Model):
#user = models.ForeignKey(Person, null=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, null=True,on_delete=models.SET_NULL)
title = models.CharField(max_length=200, null=True)
text = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Thank you and sorry I am a noob!

type object 'ProductForm' has no attribute 'cleaned_data' django

I am making a form using Django 2.0.x and Python 3.6 and I am getting an error
I'm not sure what's going on, can someone help me out? Thanks!
Product/forms.py
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
title = forms.CharField(label='',
widget=forms.TextInput(attrs={"placeholder": "Your title"}))
description = forms.CharField(
required=False,
widget=forms.Textarea())
class Meta:
model = Product
fields = [
'title',
'description',
]
Product/views.py
from django.shortcuts import *
from django.http import *
from .models import Product
from .forms import ProductForm
import hashlib
# Create your views here.
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=ProductForm.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/)
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
The code is giving me this error
type object 'ProductForm' has no attribute 'cleaned_data'
You fetch the cleaned_data from the ProductForm class, not from the form object that is an instance of ProductForm.
You can thus fix it by using form instead, like:
def home_view(request,slug,*args,**kwargs):
form= ProductForm(request.POST or None)
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if form.is_valid():
newProduct=Product.objects.create(
title = "jose",
description=form.cleaned_data.get["description"]
)
if newProduct:
return HttpResponseRedirect("/")
else:
newProduct = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)
But that being said, the workflow is not idiomatic. For example if newProduct will always succeed, regardless whether this is a valid newProduct or not. The Product.objects.create(..) however can raise an exception. A more idiomatic workflow is:
def home_view(request,slug,*args,**kwargs):
try:
productobject=Product.objects.get(id=1)
except Product.DoesNotExist:
raise Http404
if request.method = 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.instance.title = "jose"
form.save()
return redirect('home') # name of the view
else:
form = ProductForm()
context= {
"sampletext": "text",
"form": form,
"productobject":productobject,
}
return render(request, "home.html",context)

How do you enforce password complexity at user registration with Django authentication?

I'm using the built in Django authentication application. By default it has no password complexity so I'm trying to enable that.
I did find this documentation: https://docs.djangoproject.com/en/1.11/topics/auth/passwords/#module-django.contrib.auth.password_validation
But it specifically calls out that validators aren't applied when a user is created so it's no help to me.
I would really love to see a github project that uses this authentication app so I can see how to properly use this in a project.
Here are my forms.py and views.py files:
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import password_validation
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(label="Repeat Password", widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name', 'email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = {'first_name', 'last_name', 'email'}
views.py
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import LoginForm, UserRegistrationForm, UserEditForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'login.html', {'user_form': form})
def register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# set the pw
new_user.set_password(user_form.cleaned_data['password'])
# save the user object
new_user.save()
cd = user_form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
login(request, user)
return redirect('/plans/new')
else:
user_form = UserRegistrationForm()
return render(request, 'registration/register.html', {'user_form': user_form})
#login_required
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance=request.user, data=request.POST)
if user_form.is_valid():
user_form.save()
messages.success(request, 'Profile updated successfully')
return redirect('/plans')
else:
messages.error(request, 'Error updating profile.')
else:
user_form = UserEditForm(instance=request.user)
return render(request, 'registration/edit.html', {'user_form': user_form})

Editing a userprofile on django

How to create a userprofile editable page and upon clicking submission it updates the details provided during registration(the details stored in the database) using DJANGO?.
Creation of registration form for a user, and like i have said in my opening post, i want the user after he must have logged in to able to edit what he provided during registration and it will update the previous details stored in the database.
I know i need to create a view for it, but have not arrived at how to call on the details provided during registration. Well maybe using user.get_profile()
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from registeredmember.models import Registeredmember
class RegistrationForm(ModelForm):
first_name = forms.CharField(label=(u'First Name'))
middle_name = forms.CharField(label=(u'Middle Name'))
last_name = forms.CharField(label=(u'Last Name'))
occupation = forms.CharField(label=(u'Occupation'))
income = forms.IntegerField(label=(u'Income Amount'))
age = forms.IntegerField(label=(u'Age'))
address_line1 = forms.CharField(label=(u'Address line 1'))
address_line2 = forms.CharField(label=(u'Address line 2'))
city = forms.CharField(label=(u'City'))
state = forms.CharField(label=(u'State'))
phone_no_Mobile = forms.IntegerField(label=(u'Phone Number (Home)'))
phone_no_Work = forms.IntegerField(label=(u'Phone Number (Work)'))
purpose = forms.CharField(label=(u'Purpose'))
username = forms.CharField(label=(u'Username'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
password1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput)
class Meta:
model = Registeredmember
exclude = ('user','reference_number',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('That username is already taken, please select another.')
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError('That email address is already in the database, please provide another.')
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'),widget=forms.TextInput(attrs={'size': '30'}))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from registeredmember.forms import RegistrationForm, LoginForm
from registeredmember.models import Registeredmember
from django.contrib.auth import authenticate, login, logout
import random, time
from random import randint
def userregistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = RegistrationForm
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
user.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.save()
registeredmember = Registeredmember(user=user, prefix = form.cleaned_data['prefix'],first_name=form.cleaned_data['first_name'],\
middle_name=form.cleaned_data['middle_name'],last_name=form.cleaned_data['last_name'],gender=form.cleaned_data['gender'],\
occupation=form.cleaned_data['occupation'],income=form.cleaned_data['income'],age=form.cleaned_data['age'],\
address_line1=form.cleaned_data['address_line1'],address_line2=form.cleaned_data['address_line2'],city=form.cleaned_data['city'],\
state=form.cleaned_data['state'],phone_no_Mobile=form.cleaned_data['phone_no_Mobile'],phone_no_Work=form.cleaned_data['phone_no_Work'],\
purpose=form.cleaned_data['purpose'])
registeredmember.save()
return render_to_response('carloan/regsuccessful.html',{'ref_no': ref_no}, context_instance=RequestContext(request))
else:
return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
else:
'''user is not submitting the form, show them a blank registration form'''
form = RegistrationForm()
return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
registeredmember = request.user.get_profile
return render_to_response('carloan/profile.html', {'registeredmember': registeredmember}, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method =='POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
registeredmember = authenticate(username=username, password=password)
if registeredmember is not None:
login(request, registeredmember)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('carloan/loginerror.html', context_instance=RequestContext(request))
else:
'''user is submitting a blank login form, notify him that he submitted a blank form'''
return render_to_response('carloan/loginblank.html', context_instance=RequestContext(request))
else:
'''user is not submitting the form, show the login form'''
form = LoginForm()
return render_to_response('carloan/login.html',{'form': form}, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return render_to_response('carloan/logout.html', context_instance=RequestContext(request))
The code below gives the error username already exists, but when i specify a new username it updates although it doesn't update the username but the other fields
views.py for the editprofile
#login_required
def editprofile(request):
registeredmember = request.user.get_profile()
if request.method == 'POST':
userprofile_edit = RegistrationForm(request.POST, instance = registeredmember)
if userprofile_edit.is_valid():
userprofile_edit.save()
return HttpResponseRedirect('/profile/')
else:
userprofile_edit = RegistrationForm(instance = registeredmember)
return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
Got it sorted out with codes below:
forms.py
class EditForm(forms.ModelForm):
class Meta:
model = Registeredmember
exclude = ('user','username','email','password','password1',)
views.py
#login_required
def editprofile(request):
if request.method == 'POST':
userprofile_edit = EditForm(request.POST, instance = request.user.get_profile())
if userprofile_edit.is_valid():
userprofile_edit.save()
return HttpResponseRedirect('/profile/')
else:
userprofile_edit = EditForm(instance = request.user.get_profile())
return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
Thank you all...
Django 1.5 and custom user models will help with this, but in the mean time your ModelForm set up is fine.
To initialize a ModelForm from an instance of its object, do this:
user_profile_form = RegistrationForm(request.POST, instance=request.user.get_profile())
The request.POST in that line allows you to update the user_profile_form object with the user's input. It will nicely merge the existing data from your instance with the new info from the user.
You can then print this to a view, or you can save it doing this:
if user_profile_form.is_valid():
user_profile_form.save()
else
# do other stuff

What should the template be for a certain view and model . And what should be in the urls.py?

I am very new to Django , and learning it through a lot of trial and error process . Mostly errors .
This is what my view looks like
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
def login(request):
def errorHandle(error):
form = LoginForm()
return render_to_response('login.html', {
'error' : error,
'form' : form,
})
if request.method == 'POST': # If the form has been submitted...
form = LoginForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
# Redirect to a success page.
login(request, user)
return render_to_response('userprof/login.html', {
'username': username,
})
else:
# Return a 'disabled account' error message
error = u'account disabled'
return errorHandle(error)
else:
# Return an 'invalid login' error message.
error = u'invalid login'
return errorHandle(error)
else:
error = u'form is invalid'
return errorHandle(error)
else:
form = LoginForm() # An unbound form
return render_to_response('login.html', {
'form': form,
})
This is my model
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
What should be my template that must have a username and password field to send the value to this view .
I am very confused with the using of django user widget way of doing it , thus these doubts .
Another thing would be , what should be in my urls.py ?
Ps: I am getting a reverse error as of now .
Django already has a built-in view for it - django.contrib.auth.views.login (which is highly customizable). Documentation will provide with you with sample template and url pattern.