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!
Related
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.
I ve just create a project and setting authentification.
But for registeration, I m using UserCreateform expected to have username and password fields only. Instead I have many fields like last login, superuser_status, groups, etc... Where is my error ?
Forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
class SignUpform(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
Views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.forms import UserChangeForm
from .forms import SignUpform
def register_user(request):
if request.method == 'POST':
form = SignUpform(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(request, username=username, password=password)
login(request, user)
messages.success(request, 'You are registered')
# redirect to a succes page
return redirect('home')
else:
form = UserChangeForm()
context = {'form': form}
return render(request, 'register.html', context)
My goal:
having only fields defined in signupform. thanks for helping
Change you views.py to :
def register_user(request):
if request.method == 'POST':
form = SignUpform(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(request, username=username, password=password)
login(request, user)
messages.success(request, 'You are registered')
# redirect to a succes page
return redirect('home')
else:
form = SignUpform()
context = {'form': form}
return render(request, 'register.html', context)
I was trying to implement a basic login system using Django with a custom user using the AbstractUser class.
Here is my models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
class Stock(models.Model):
stock_name = models.CharField(max_length=10)
stock_price = models.FloatField()
def __str__(self):
return self.stock_name
class CustomUser(AbstractUser):
stocks = models.ManyToManyField(Stock)
def __str__(self):
return self.username
My forms.py:
from .models import CustomUser,Stock
from django.contrib.auth.forms import AuthenticationForm
class loginform(AuthenticationForm):
class Meta:
model = CustomUser
fields = ('username', 'password')
My views.py:
def successful_login(request, pk):
user = get_object_or_404(CustomUser, pk=pk)
return render(request, '../templates/stock_portfolio.html', {'user':user})
def loginview(request):
err=0
if request.method=="POST":
form = loginform(request.POST)
pdb.set_trace()
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
pdb.set_trace()
login(request, user)
pk = user.id
pdb.set_trace()
return redirect('successful_login', pk=pk)
else:
err=1
return render(request,'../templates/login.html',{'response':err,'form':form})
else:
form = loginform()
return render(request, '../templates/login.html',{'form':form})
While logging using pdb here is what I am getting for the form.
<loginform bound=False, valid=Unknown, fields=(username;password)>
How do I proceed now?
Answering this since I just had the same issue and found the problem. Change your
form = loginform(request.POST)
to
form = loginform(data=request.POST)
Worked like a charm for me.
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})
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